Discord.py: Bot Keeps Writing Previous Values

Question:

So, I have a command that should give me an image and after that bot should ask whether user wants to keep it or not (I use thumbs-up reaction for the answer). If user reacts with ‘thumbs-up’, then bot says ‘Saved!’ and actually save the image URL to a .txt file. The problem is if user doesn’t react with thumbs up and after that types command again and save this latest image, bot saves previous ones too. I use Replit for hosting. Here is the code block that doesn’t work as expected:

@bot.command()
async def myfunc(ctx):
    ... # here goes the message attributes, requests (no problem with the requests)
    thumb_up = " "
    thumb_down = " "
    imagesList = []

    await message.add_reaction(thumb_up)
    userDict = {}
    n = 0
    while True:
      try:
        reaction, user = await bot.wait_for("reaction_add", timeout=30)
        if user not in userDict:
          userDict[user] = 0
        if userDict[user] == 0:
          if (str(reaction.emoji) == thumb_up and user != bot.user):
              
              imagesList.append(url)
              fileWrite = open(f"data{user}.txt", "a")
              fileWrite.write(f"{url} n")
              fileWrite.close()
              await ctx.send("Saved!")
              userDict[user] += 1
              imagesList.clear()
      except:
        pass
    
    imagesList.clear()

@bot.event
async def on_reaction_add(reaction, user):
    embed = reaction.message.attachments
    emoji = reaction.emoji

    if emoji == ":thumbsup:":
        await reaction.channel.send(embed)

It shouldn’t save previous URL’s to users file. It should save only URL’s that the user reacted with ‘thumbs-up’. I use dict to avoid that but didn’t work.

Asked By: melikechan

||

Answers:

Okay, so I am not much familiar with discord.py and have no clue why it writes multiple times, but I think the problem is if the message id that the user reacted is the message user reacted, I mean if there are multiple lines get written, we should discard or not to use previous of them. That’s why I created a check function:

msgId = message.id
def check(reaction, user):
    if user != bot and reaction.emoji == thumb_up and reaction.message.id == msgId :
        return True
    else:
        return False

userDict = {}
while True:
    reaction, user = await bot.wait_for("reaction_add", check=check, timeout=30)
    if(user.id not in userDict.keys() and user.id != <id of bot>):
      userDict[user.id] = 0
    if(reaction.emoji == thumb_up and user.id != <id of bot> and userDict[user.id] == 0 ):
      userDict[user.id] = 1
      fileWrite = open(f"data{user}.txt", "a")
      fileWrite.write(f"{url} n")
      fileWrite.close()
      await ctx.send(f"Saved {user}")
userDict[user.id] = 1
Answered By: sourlemon.mp5