DJS - Edit the embed when someone reacts with specific emoji

Viewed 148

What I'm trying to do is to change the color of an embed when someone adds a reaction. The struggle I'm currently facing is making it the if statement fire. So haven't gotten very far.

I'm also probably not targeting any specific embed. As the embed (suggestionsEmbed) has been sent multiple times.

EDIT: Updated with current code. This is working except for one thing. No embed other than the last sent can be edited. See what I mean here.

   // SUGGESTIONS EMBED - BEGINS
var suggestionsEmbed;
client.on('messageCreate', async message => {
  if (message.channel.id === channelSuggestions && !message.author.bot) {
    db.add('counterP.plus', 1);
    const embed = new MessageEmbed()
    .setColor('#f9db73')
    .setTitle(`Suggestion #${await db.fetch('counterP.plus') + await db.fetch('counterM.minus')}`)
    .setDescription(message.content)
    .setAuthor({ name: message.author.username, iconURL: message.author.displayAvatarURL() })
    .setTimestamp()
    .setFooter({ text: message.author.id });
    suggestionsEmbed = await message.channel.send({ embeds: [embed] })
    suggestionsEmbed.react('')
    suggestionsEmbed.react('');
        message.delete({ timeout: 0 });
        console.log(db.fetch('counterP.plus'));
}
})
// SUGGESTIONS EMBED - ENDS

// CHANGE EMBED COLOR - BEGINS
const suggestionsApproved = '';
const suggestionsDenied = '';
client.on('messageReactionAdd', (reaction, user) => {
  if (reaction.message.channel.id === channelSuggestions) {
    if (reaction.emoji.name === suggestionsApproved && reaction.message.id === suggestionsEmbed.id) {
        const suggestionsEmbedApproved = new MessageEmbed(suggestionsEmbed.embeds[0]).setColor('#76de51')
            suggestionsEmbed.edit({ embeds: [suggestionsEmbedApproved] });
    }
  }
})
3 Answers

After the introduction of discord.js v13, you need intents declared in your bot. They were introduced so that developers could choose which types of events their bot wanted to receive. You can learn more about Intents here => Gateway Intents. First, you have to add the GUILD_MESSAGE_REACTIONS intent in your client by using:

const { Client, Intents } = require('discord.js')
const client = new Client({
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MESSAGES,
        Intents.FLAGS.GUILD_MESSAGE_REACTIONS
    ]
})

Then after that, you can just use your original code to do whatever you want. Although you might get an error saying DiscordAPIError: Invalid Form Body embeds[0].description: This field is required, so to fix that, all you have to do is add the .setDescription() to your edited embed and then send it. Your final code might look something like this:

const { Client, Intents, MessageEmbed } = require('discord.js')
const client = new Client({
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MESSAGES,
        Intents.FLAGS.GUILD_MESSAGE_REACTIONS
    ]
})
const suggestionsApproved = '';
const suggestionsDenied = '';
const channelSuggestions = 'your channel id'
client.on('messageReactionAdd', (reaction, user) => {
    if (reaction.message.channel.id === channelSuggestions) { // Check if the reaction was in a particular channel
        if (reaction.emoji.name === suggestionsApproved) { // Check which emoji was selected
            const suggestionsEmbedApproved = new MessageEmbed()
                .setColor('your color')
                .setDescription('your description');
            suggestionsEmbed.edit({ embeds: [suggestionsEmbedApproved]});
        }
    }
})

Edit

In response to the new question, here is the answer: Instead of naming the embed as suggestionsEmbed, the correct way to do it would be to first create an embed with a different name and then use const suggestionsEmbed = await message.channel.send({ embeds: [embedName] }) so that the code will be like:

const embed = new MessageEmbed()
    .setTitle('title')
    .setDescription('description')
    .setColor('color')
const suggestionsEmbed = await message.channel.send({
    embeds: [embed]
})

Second Edit

Since you are already using await message.channel.send(), you don't have to use .then(). All you have to do is change this:

const suggestionsEmbed = await message.channel.send({ embeds: [embed] }).then(sentEmbed => {
    sentEmbed.react("")
    sentEmbed.react("")
});

to this:

const suggestionsEmbed = await message.channel.send({ embeds: [embed] })
suggestionsEmbed.react('')
suggestionsEmbed.react('')

Editing the Embed:

Use:

const suggestionsEmbedApproved = new MessageEmbed(suggestionsEmbed.embeds[0]).setTitle('asdfasdf')
suggestionsEmbed.edit({ embeds: [suggestionsEmbedApproved] });

So your code is trying to edit the embed rather than the message that the embed is in, (weird I know) but this should work for you.

Discord intents may vary based on your coding but should look similiar

const client = new Client({
    intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS],
    partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
})

It should be able to pick up those reactions with the below.

const suggestionsApproved = 'insertReactionEmojiName'
const suggestionsDenied = 'insertReactionEmojiName'
const channelSuggestions = 'yaddayadda'

// I would use a different emoji, one that you can get an name from like this
//  which in discord is named :thumbsup:


client.on('messageReactionAdd', (reaction, user) => {
    if (reaction.partial) {
        // If the message this reaction belongs to was removed, the fetching might result in an API error which should be handled
        try {
            await reaction.fetch();
        } catch (error) {
            console.error('Something went wrong when fetching the message:', error);
            // Return as `reaction.message.author` may be undefined/null
            return;
        }
    }   

    const targetMessage = reaction.message
    const channel = targetMessage.channel

    if (channel.id === channelSuggestions) {
        if (reaction.emoji.name === suggestionsApproved) {
            const suggestionsEmbedApproved = new MessageEmbed()
                .setColor('#1dce1d')
            
            targetMessage.edit({
                embeds: [suggestionsEmbedApproved]
            })
            console.log('fired!')
        }
    }
}) 

To edit any embed which was reacted to instead of only the previous sent one, you can use:

const suggestionsEmbedApproved = new MessageEmbed(reaction.message.embeds[0]).setColor("Your color")
reaction.message.edit({ embeds: [suggestionsEmbedApproved] });
Related