Skip to content
Advertisement

How to tell if a reaction is removed by a discord bot using JDA?

I have a MessageReactionRemoveEvent in my code and it triggered whenever a reaction is removed.

However, I also have my bot executing some automatic reaction removal (removing the user’s reaction).

I want to prevent MessageReactionRemoveEvent triggered when the reaction is removed by a bot.

My code for preventing MessageReactionRemoveEvent triggered by a bot:

if (event.getMember().getUser().equals(event.getJDA().getSelfUser())) return;

But the getUser() method in MessageReactionRemoveEvent always returns the ID of the user who reacts instead of the ID of the bot.

My question is how do I detect if a reaction is removed by a bot?

Advertisement

Answer

Since the MessageReactionRemoveEvent will not return the bot ID and therefore I am not able to validate if the reaction is removed by the Bot. I work the other way round to achieve preventing MessageReactionRemoveEvent triggered when the reaction is removed by a bot.

Here’s how:

  1. Add a boolean and let’s call it trigger boolean trigger = true;.
  2. Make sure use .complete() to remove reactions instead of .queue(), the differences can be seen here: https://ci.dv8tion.net/job/JDA/javadoc/net/dv8tion/jda/api/requests/RestAction.html#queue()
  3. After removing a reaction, do trigger = false;.
  4. Since the .complete() method will block the current Thread, MessageReactionRemoveEvent will not be called before the code in MessageReactionAddEvent is finished.
  5. In MessageReactionRemoveEvent, simply applies if (!trigger) // do something, it means that if the reaction is removed by the bot, code after the if statement won’t be executed, and that is where you want to do something if the reaction is removed by a user.
  6. At the end of the method, make sure includes trigger = true; to reset the trigger.
  7. (Optional) Includes trigger = true; at the beginning of MessageReactionAddEvent.

This works for me like magic.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement