Search code examples
pythondiscorddiscord.py

Is there a way to stop discordpy bot from sending multiple messages from a reaction?


I'm creating a discordpy bot that will allow users to compete against each other to see who can react to a message the fastest. Right now, when a user reacts to a message, the bot displays the message multiple times and I'm not too sure why.

I've tried the message.author == bot.user but it hasn't appeared to be working at all and I've looked at other sites but they've not solved my problem at all...

@bot.listen('on_message')

async def on_message(message):
  if message.author == bot.user:
    return 
  channel = bot.get_channel("CHANNEL_ID")
  messages = [message async for message in channel.history(limit=15)]
  await asyncio.sleep(random.randint(0, 3))
  msg = messages[random.randint(0, 14)].add_reaction("\N{Snowman}")
  await msg
  def check(reaction, user):
      return str(reaction.emoji) == '\N{Snowman}' and user != bot.user
  try:
    reaction, user = await bot.wait_for('reaction_add', timeout = 30, check=check)
    embed = discord.Embed(description=f'{user.mention} received a snowman!', color=discord.Color.random())
    await channel.send(embed=embed)
  except asyncio.TimeoutError:
    pass

Solution

  • its because you are using the await channel.send in a try loop and this will "try run" the code before and if it works it will really run but by api requests this will just trigger the request 2times.

    so you should make something like

    try:
        reaction, user = await bot.wait_for('reaction_add', timeout = 30, check=check)
    except asyncio.TimeoutError:
        return
    embed = discord.Embed(description=f'{user.mention} received a snowman!', color=discord.Color.random())
    await channel.send(embed=embed)
    

    where the send request is not tried and only the check