JDA add reaction when reacted with specific reaction

Viewed 21

I want to create a Discord Bot with JDA in Java which adds ✔ and ❌ when a user reacts with to a message and afterwards deletes the reaction.

package me.beemo.commands;

import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;


public class makesurvey extends ListenerAdapter {

    @Override
    public void onMessageReactionAdd(MessageReactionAddEvent event) {
        boolean check;

        if (event.getReaction().equals("")) {
            //when message has  then continue
            check = true;
        } else {
            //when message has not  then abort
            check = false;
        }

        if (event.getReaction().equals("✅")){
            //when message has ✅ then abort
            check = false;
        } else {
            //when message has not ✅ then continue
            check = true;
        }

        if (event.getReaction().equals("❌")){
            //when message has ❌ then abort
            check = false;
        } else {
            //when message has not ❌ then continue
            check = true;
        }

        if (check == true) {
            Message message = event.getChannel().getHistory().getMessageById(event.getMessageId());
                message.removeReaction(Emoji.fromUnicode("U+274C"));
                message.addReaction(Emoji.fromUnicode("U+274C")).queue();
                message.addReaction(Emoji.fromUnicode("U+2705")).queue();
                message.removeReaction(Emoji.fromUnicode("U+1F4DD")).queue();
        } else {
            return;
        }
    }
}

But every time I add the reaction I get this error

[JDA MainWS-ReadThread] ERROR JDA - One of the EventListeners had an uncaught exception
java.lang.NullPointerException: Cannot invoke "net.dv8tion.jda.api.entities.Message.removeReaction(net.dv8tion.jda.api.entities.emoji.Emoji)" because "message" is null
    at me.beemo.commands.makesurvey.onMessageReactionAdd(makesurvey.java:41)

I don't know why exactly the message is still null after getting the ID of the message

1 Answers

You can use MessageChannel#addReactionById

event.getChannel().addReactionById(event.getMessageId(), emoji).queue();

Also, it looks like your use of the check variable is incorrect, it will only be false if the reaction is . Since you have an else that makes it true regardless of what other reaction it is, meaning your other 2 if/else checks are doing nothing at all.

The getReaction() also does not return a string, so your equality check can only be false regardless.

Related