Discord.js deleting field and replacing it with a new one Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Discord.js deleting field and replacing it with a new one without wasting too much if your time.

The question is published on by Tutorial Guruji team.

So, I’m trying to replace an embed with another embed with the same things, but I want to replace a field. Here’s what I’ve got so far:

const modlog = bot.channels.cache.get("770389813345255454");
const caseNumber = args[0];
const newReason = args.slice(1).join(" ");

await modlog.messages.fetch({ limit: 100 }).then((messages) => {
    const caseLog = messages
        .filter((m) => m.author.id === bot.user.id && m.embeds[0] && m.embeds[0].type === "rich" && m.embeds[0].footer && m.embeds[0].footer.text.startsWith("Case") && m.embeds[0].footer.text === `Case ${caseNumber}`)
        .first();
    modlog.messages.fetch(caseLog.id).then((logMsg) => {
        const embed = logMsg.embeds[0];
        let newEmb = new MessageEmbed(embed).spliceFields(2, 1); // field 2 is the one i want to delete, and i want to delete 1 field.
        newEmb.addField("Reason:", newReason);
        logMsg.edit(newEmb);
    });
});

I try the command and it doesn’t delete the other field but adds the new field. What am I doing wrong?

Answer

You can update the field directly without using spliceFields(). embed.fields contains an array of fields so you can access an element by its index.

If you want to edit the second field, you can update embed.fields[1]. You can assign a new object with name, value, and inline keys. The new object would be { name: 'Reason', value: newReason } in your case.

Check out the snippet below. I’ve also changed those .then()s to awaits as you’re already using them.

const messages = await modlog.messages.fetch({ limit: 100 });
const caseLog = messages
  .filter(
    (m) =>
      m.author.id === bot.user.id &&
      m.embeds[0] &&
      m.embeds[0].type === 'rich' &&
      m.embeds[0].footer &&
      m.embeds[0].footer.text.startsWith('Case') &&
      m.embeds[0].footer.text === `Case ${caseNumber}`,
  )
  .first();

const logMsg = await modlog.messages.fetch(caseLog.id);
const embed = logMsg.embeds[0];

// the second field is index 1
embed.fields[1] = { name: 'Reason', value: newReason };

logMsg.edit(embed);

If you want to use spliceFields(), you can replace the field by adding a third argument, the same object I mentioned above:

const logMsg = await modlog.messages.fetch(caseLog.id);
const embed = logMsg.embeds[0];

// the second field is index 1
embed.spliceFields(1, 1, { name: 'Reason', value: newReason });

logMsg.edit(embed);
We are here to answer your question about Discord.js deleting field and replacing it with a new one - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji