Reputation: 67
I'm learning Java at the moment by coding a discord bot using JDA. Now I just can't figure what my mistake is using the Role entitiy.
if (content.equalsIgnoreCase("$addrole")){
channel.sendMessage("Please select the role you want!\n\n\u2694\uFE0F\tFighter\n\uD83D\uDEE1\tTank").queue(message -> {
message.addReaction("\u2694\uFE0F").queue();
message.addReaction("\uD83D\uDEE1").queue();
});
//Role role = event.getGuild().getRolesByName("@everyone", true).get(0);
if (event.getGuild().getRolesByName("fighter", true).isEmpty()){
role1 = event.getGuild().createRole().setName("Fighter").setPermissions(0L).complete();
} else {
System.out.println("Role already exists");
}
if (event.getGuild().getRolesByName("tank", true).isEmpty()){
role2 = event.getGuild().createRole().setName("Tank").setPermissions(0L).complete();
} else {
System.out.println("Role already exists");
}
System.out.println("Role1 ID is: " + role1.getId());
System.out.println("Role2 ID is: " + role2.getId());
}
I do create role1 and role2 as empty objects at the beginning of my MessageListener using Role role1;
and Role role2;
.
Now when executing the command $addrole, the message appears and the roles are created, but I can't use role1 and role2. Whenever I try to call them e.g. in System.out.println("Role1 ID is: " + role1.getId());
I get a load of errors including a nullpointer exception saying that "this.role1 is null". I just can't find my mistake.
Upvotes: 0
Views: 436
Reputation: 329
I tried your code, and it worked the first time I was executing the code. The second time it did not work and threw me a NPE. I quickly found out that the issue you have is that you are trying to print out the Role-ID even if the role already exists. Note that you only assign the role to the variables role1
or role2
if the role does not exist.
So to fix this, you could either return after the printing that the role already exists or just assigning the existing role to the variable.
An example implementation of that would be:
String content = e.getMessage().getContentRaw();
TextChannel channel = e.getTextChannel();
Role role1 = null;
Role role2 = null;
if (content.equalsIgnoreCase("$addrole")) {
channel.sendMessage("Please select the role you want!\n\n\u2694\uFE0F\tFighter\n\uD83D\uDEE1\tTank")
.queue(message -> {
message.addReaction("\u2694\uFE0F").queue();
message.addReaction("\uD83D\uDEE1").queue();
});
if (e.getGuild().getRolesByName("fighter", true).isEmpty()) {
role1 = e.getGuild().createRole().setName("fighter").setPermissions(0L).complete();
} else {
role1 = e.getGuild().getRolesByName("fighter", true).get(0);
}
if (e.getGuild().getRolesByName("tank", true).isEmpty()) {
role2 = e.getGuild().createRole().setName("tank").setPermissions(0L).complete();
} else {
role2 = e.getGuild().getRolesByName("tank", true).get(0);
}
System.out.println("Role1 ID is: " + role1.getId());
System.out.println("Role2 ID is: " + role2.getId());
}
Upvotes: 0