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:
- Add a boolean and let’s call it trigger
boolean trigger = true;
. - 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() - After removing a reaction, do
trigger = false;
. - Since the .complete() method will block the current Thread,
MessageReactionRemoveEvent
will not be called before the code inMessageReactionAddEvent
is finished. - In
MessageReactionRemoveEvent
, simply appliesif (!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. - At the end of the method, make sure includes
trigger = true;
to reset the trigger. - (Optional) Includes
trigger = true;
at the beginning ofMessageReactionAddEvent
.
This works for me like magic.