Search code examples
pythondiscorddiscord.py

Cannot edit embed message with reaction command in discord.py


I have been working on a discord bot for a bit now, and now wanting to make it so that the bot calculates the average of the reactions/votes and changes it to the message footer. I have gotten everything else to work, however I can't seem to fiqure out how to edit the message.

Code siplified.

#imports

intents = discord.Intents.default()
intents.message_content = True
intents.members = True
intents.dm_messages = True

#bot client
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'Logged in as {client.user}')

divider=0
sumofnumbers=0
average=0

@client.event
async def on_message(message):
      if message.content.startswith('!viikonlista'):
        embed=discord.Embed(color=0x76b52f)
        embed.add_field(name="Vote now!", value="Votes appear on the footer")
        embed.set_footer(text=average)
        msg=await message.channel.send("Here's the embed!",embed=embed)
        await msg.add_reaction("1️⃣")
        await msg.add_reaction("2️⃣")
        await msg.add_reaction("3️⃣")
        await msg.add_reaction("4️⃣")
        await msg.add_reaction("5️⃣")


@client.event
async def on_reaction_add(reaction, user):
    global divider
    global sumofnumbers
    global average
    if reaction.emoji == "1️⃣" and not user.bot:
      divider+=1
      sumofnumbers+=1
      average=(sumofnumbers)/divider
      embed.set_footer(text=average)
      msg.edit(embed=embed)
      print(average)
#same for the other numbers

#same but minus

client.run("token")

Whenever I react, the folloing error is given:

NameError: name 'embed' is not defined

Solution

  • The error message is pretty much stating what the issue is here. embed isn't defined within the scope of the on_reaction_add function.

    @client.event
    async def on_reaction_add(reaction, user):
        global divider
        global sumofnumbers
        global average
        if reaction.emoji == "1️⃣" and not user.bot:
            divider += 1
            summat += 1
            keskiarvo = (sumofnumbers) / divider
            embeds = reaction.message.embeds
            if embeds:
                embed = embeds[0]
            else:
                # no embed
                return
    
            embed.set_footer(text=average)
            msg.edit(embed=embed)
            print(average)
    

    You can get the the message embeds by looking at embeds property on the Message object via the reaction.message property.

    Or, alternatively, create a new instance of the embed here and then do what you want to do.

    Docs: