Search code examples
javascriptdiscorddiscord.jsembed

Edit part of a Message Embed (Discord.JS)


I have a channel that contains 10 embedded messages (1 embed per message). Each embed is a leaderboard for people's best lap times, by Track.

The layout of each embed is

const trackName = new MessageEmbed
.setTitle(trackName) 
.addField(user1, lapTime)
.addField(user2, lapTime) 
.addField(user3, lapTime)

Assume for example the 3rd embed looks something like this:

| Track 3 Name

| John 37 seconds

| Chris 39 seconds

| Jeff 40 seconds

Beyond simply editing the embed and sending all the information updated manually, how could I update just one particular slot? For example, say Clark comes in with a 38 second lap, how would I move Chris to 3rd, remove Jeff, and add Clark to 2nd so the embed looks as such

| Track 3 Name

| John 37 seconds

| Clark 38 seconds

| Chris 39 seconds

Without changing any other embeds in the channel


Solution

  • Thanks to Cannicide's helpful answer, it led me down the right track.

    To achieve the end result of sorting times and overwriting existing times, I ended up with the following function. I require all times be submitted in the format: MINUTES:SECONDS (0:35 = 35s | 4:24 = 4m24s | 62:08 = 1h2m8s).

    function editLb(theMessage, newUser, newTime) {
        //get the embed you want to edit
        let currentEmbed = theMessage.embeds[0];
    
        //Check all existing fields for the same newUser, if the same newUser
        //is found, replace that entire field with the name: "Placeholder"
        //and the value: "999:99". This will also remove any existing duplicates.
        currentEmbed.fields.forEach(field => {
            if (field.name == newUser) {
                field.name = `Placeholder`;
                field.value = `999:99`;
            }
        })
    
        //add the newUser and the newTime to a new field
        currentEmbed.addField(`${newUser}`, `${newTime}`);
    
        //sort all available fields effectively by seconds, by taking 
        // (minutes*60) + (seconds)
        currentEmbed.fields.sort((a, b) => Number((a.value.split(":")[0])*60 + (a.value.split(":")[1])) - Number((b.value.split(":")[0])*60 + (b.value.split(":")[1])));
        
        //If there are now 4 fields, remove the slowest(last) one.
        if (currentEmbed.fields.length == 4) currentEmbed.fields.splice(3, 1);
    }