alternate solutions to "JDA Member may not be null" error - java

I'm trying to make it so when someone with the role "Owner" types the mute command, it takes the person they #mentioned and gives them the "Muted" role.
The rest of the code works on it's own, the only part that is not working is the line
event.getGuild().addRoleToMember(member,event.getGuild().getRoleById(0)).complete();
and the variable "member" is defined by
Member member = event.getGuild().getMemberById(mentionid);
The full chunk of code is:
package radishmouse.FoodWorld.Events;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import radishmouse.FoodWorld.FoodWorld;
public class GuildMessageReceived extends ListenerAdapter {
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String[] args = event.getMessage().getContentRaw().split("\\s+");
if (args[0].equalsIgnoreCase(FoodWorld.prefix + "mute")) {
if (hasRole("Owner", event)) {
if (args.length == 2) {
String mentionid = args[1].replace("<#!", "").replace(">", "");
Member member = event.getGuild().getMemberById(mentionid);
event.getGuild().addRoleToMember(member, event.getGuild().getRoleById(0)).complete();
EmbedBuilder msg = FoodWorld.sendMessage(null, "idk " + mentionid + member, "Blue");
event.getChannel().sendMessageEmbeds(msg.build()).queue();
}
else {
EmbedBuilder msg = FoodWorld.sendMessage("Specify Who To Mute", "Usage: " + FoodWorld.prefix + "mute [#mention who to mute]", "Blue");
event.getChannel().sendMessageEmbeds(msg.build()).queue();
}
}
}
/* If the bot ever sends a message, then add a ❌ reaction so users can delete that message */
if (event.getAuthor().equals(event.getJDA().getSelfUser())) {
event.getMessage().addReaction("❌").queue();
}
}
private boolean hasRole(String string, GuildMessageReceivedEvent event) {
Boolean toReturn = false;
for(int i=0; i < event.getMember().getRoles().size(); i++){
if("Owner".equals(event.getMember().getRoles().get(i).getName())){
toReturn = true;
}
}
return toReturn;
}
For reference, I'm following this tutorial on youtube: tutorial.
I'm not the most familiar with JDA and don't know how this would be done in an easier way.

Instead of parsing the string:
String mentionid = args[1].replace("<#!", "").replace(">", "");
Member member = event.getGuild().getMemberById(mentionid);
Use getMentionedMembers:
List<Member> mentions = event.getMessage().getMentionedMembers();
if (mentions.isEmpty()) {
EmbedBuilder msg = FoodWorld.sendMessage("Specify Who To Mute", "Usage: " + FoodWorld.prefix + "mute [#mention who to mute]", "Blue");
event.getChannel().sendMessageEmbeds(msg.build()).queue();
} else {
Member member = mentions.get(0);
event.getGuild().addRoleToMember(member, event.getGuild().getRoleById(0)).queue();
EmbedBuilder msg = FoodWorld.sendMessage(null, "idk " + member.getId() + member, "Blue");
event.getChannel().sendMessageEmbeds(msg.build()).queue();
}

Related

Why is my Stack empty? EmptyStackException

I'm working with Stacks in Java at the moment.
The problem I'm facing is that I want to create a Stack which stores items of the type "candy".
I want to add that "candy" at the Producer.java
But when I run the code shown below I get the error:
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at java.util.Stack.pop(Stack.java:84)
at app.fachinformatiker.myMashup.Model.Consumer.(Consumer.java:10)
at app.fachinformatiker.myMashup.Main.Main.initializeConsumers(Main.java:84)
at app.fachinformatiker.myMashup.Main.Main.main(Main.java:42)
These are the corresponding lines
Consumer.java:10
String Candy = candyStack.pop();
Main.java:84
consumerList.add(new Consumer(candyStack));
Main.java:42
initializeConsumers();
I don't get it why my stack isn't properly filled.
Below you will find some snippets of my code.
If you want to download my whole code and run it in an IDE of your choice (I use IntelliJ IDEA), here's a direct link to the archive on GitHub (specific commit) : https://github.com/fachinformatiker/myMashup/archive/97e3ffb.zip
Here's some snippets of my code:
In my Main.java
private static final Stack<String> candyStack = new Stack<>();
private static final ArrayList<Producer> producerList = new ArrayList<>();
private static final ArrayList<Consumer> consumerList = new ArrayList<>();
...
private static void startProducers() {
for (int i = 0; i < producerList.size(); i++) {
System.out.println("I would start producer Nr. " + i + " now.");
producerList.get(i).start();
}
}
private static void startConsumer() {
for (int i = 0; i < consumerList.size(); i++) {
Debug.gebeInfoAus("I would start consumer Nr. " + i + " now.");
consumerList.get(i).start();
}
}
private static void initializeProducers() {
if (ArgController.istAusgewertet) {
Debug.gebeInfoAus("Producer istAusgewertet");
return;
}
for (int i = 0; i < ArgController.getAnzahlProduzenten(); i++) {
Debug.gebeInfoAus("Producer Nr. " + i + " added to candyStack");
producerList.add(new Producer(candyStack, i));
}
}
in my Producer.java
public class Producer {
private Candy candy = new Candy();
private String myCandy;
int hell = candy.getHell();
String hope = candy.getHope();
public Producer(Stack<String> candyStack, int i) {
myCandy = i + ";" + hell + ";" + hope;
candyStack.push(myCandy);
Debug.gebeInfoAus(myCandy);
}
public void start() {
}
}
In my Consumer.java
public class Consumer {
public Consumer(Stack<String> candyStack) {
String Candy = candyStack.pop();
Debug.gebeInfoAus(Candy);
}
public void start() {
}
}

Config questions

I would like to know how to send a player a list of their shops when they type /shoplist. Also, I would like to know how to change the name of a shop depending on what they type so if they use /shopname Shop1 Pie it would change the name of Shop1 to pie. Or if they do not have a shop called shop1 then it would say a message if they don't have any shops when they make a shop then it builds a new section in the config for them.
Here is my main file:
public class Shops extends JavaPlugin implements Listener {
public void onEnable() {
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getLogger().info("*Shops Plugin Enabled *");
Bukkit.getServer().getLogger().info("*Shops by McMatt *");
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getPluginManager().registerEvents(new Signs(), this);
getConfig().options().copyDefaults(true);
saveConfig();
}
public void onDisable() {
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getLogger().info("*Shops Plugin Disabled *");
Bukkit.getServer().getLogger().info("*Shops by McMatt *");
Bukkit.getServer().getLogger().info("************************");
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("shops")) {
if (!(sender instanceof Player)) {
sender.sendMessage("You must be a player to run this command");
return true;
}
Player player = (Player) sender;
if (!player.hasPermission("shops.shops")) {
player.sendMessage(ChatColor.RED + "You do not have to permission (shops.shops)");
return true;
} else {
player.sendMessage(ChatColor.GOLD + "Shops:");
player.sendMessage(ChatColor.RED + "---" + ChatColor.GOLD + "Commands" + ChatColor.RED + "---");
player.sendMessage(ChatColor.DARK_GREEN + "/shops" + ChatColor.GREEN + " Displays this");
player.sendMessage(ChatColor.DARK_GREEN + "/shopslist" + ChatColor.GREEN + " Used to list shops");
player.sendMessage(ChatColor.RED + "---" + ChatColor.GOLD + "Signs" + "---");
player.sendMessage(ChatColor.DARK_GREEN + "First line:" + ChatColor.GREEN + " [shop]");
player.sendMessage(ChatColor.DARK_GREEN + "Second line:" + ChatColor.GREEN + " {Open or Closed}");
}
}
return true;
}
public boolean onCommand1(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("shopslist")) {
sender.sendMessage("Getting shops info!");
sender.sendMessage(getConfig().getString("" + sender.getName()));
return true;
}
return false;
}
}
Here's my listener file
public class Signs implements Listener {
#EventHandler
public void onSignChange(SignChangeEvent e) {
if (e.getLine(0).equalsIgnoreCase("[shop]")) {
Block attached = e.getBlock().getRelative(0, -1, 0);
String name = e.getPlayer().getDisplayName();
if (!(attached.getType() == Material.CHEST))
e.getPlayer().sendMessage(ChatColor.RED + "Please place the shop on a chest!");
else {
if (!e.getPlayer().hasPermission("shops.create"))
e.getPlayer().sendMessage(ChatColor.RED + "You don't have permission to create a shop! (shops.create)");
else {
if (!Arrays.asList("open", "closed").contains(e.getLine(1).toLowerCase())) {
e.getPlayer().sendMessage(ChatColor.RED + "You must specify if the shop is open or closed on the second line!");
} else {
boolean closed = true;
if ("open".equalsIgnoreCase(e.getLine(1))) {
closed = false;
}
String lineThree = closed ? "§cClosed" : "§aOpen";
e.setLine(3, lineThree);
e.setLine(0, "§9[Shop]");
e.setLine(1, "§b" + name + "'s");
e.setLine(2, "§bShop");
e.getPlayer().sendMessage(ChatColor.GREEN + "Shop Created!");
e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.LEVEL_UP, 10, 10);
//if(getConfig().equals(null)){
//int shopAmount = 0;
//shopAmount = shopAmount + 1;
//getConfig().createSection(name);
//getConfig().addDefault(name + ":.Shops:", "Shop" + shopAmount);
}
}
}
}
}
#EventHandler
public void onPlayerInteract(PlayerInteractEvent e) {
if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Player p = e.getPlayer();
Block b = e.getClickedBlock();
Material m = b.getType();
if (!(m == Material.SIGN_POST)) {
return;
} else {
Sign sign = (Sign) e.getClickedBlock().getState();
if ((sign.getLine(0).equalsIgnoreCase("§9[Shop]"))) {
if ((sign.getLine(3).equalsIgnoreCase("§aOpen"))) {
p.sendMessage("I opened the shop!");
}
}
}
}
}
}
And here's my configuration file
McMatt:
- Shop1
You could get the List<String> of all of the player's shops by using
config.getStringList(playerName);
So, for example, if your config looked like this:
McMatt:
- "Shop1"
- "Awesome Shop"
jojodmo:
- "Jojo Shop"
using
config.getStringList("McMatt");
Would return a List<String> containing the strings Shop1 and Awesome Shop.
Also, to avoid a NullPointerException, you should make sure the player has shops in the config by using
if(config.contains(playerName))
and send the player a message telling them that they have no shops.
So, your code could look something like this:
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
if(cmd.getName().equalsIgnoreCase("shops")){
//your code
if(sender instanceof Player){
Player player = (Player) sender;
String name = player.getName();
if(config.contains(name)){
List<String> shops = config.getStringList(name);
for(String shop : shops){
//do something with the shop
}
}
else{
//the user has no shops
}
}
//...
}
}

Number of kills is always the same for every player. (Bukkit)

As I was coding, I tested my plugin and this seemed to happen:
basically, when a player kills another player, his kill count goes up by one. However, when a player has for instance 5 kills, so will all the other players. Here is my code:
public class KillDeathCounter extends JavaPlugin {
public void onEnable() {
new PlayerListener(this);
getLogger().info("Players will not be able to kit spam.");
this.getConfig().addDefault("playerkills", 0);
this.getConfig().addDefault("playerdeaths", 0);
this.getConfig().options().copyDefaults(true);
saveConfig();
}
public void onDisable() {
getLogger().info("Kill Death Counter has been disabled.");
saveConfig();
}
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
if (cmd.getName().equalsIgnoreCase("digipvp")) {
Player p = (Player) sender;
p.sendMessage(ChatColor.AQUA
+ "Our PVP plugin was developed by Pierre Lichtlé, the owner, also known as Master Digi."
+ " If you would like to contact him for a plugin, send him an email at developer.petlamb#gmail.com."
+ " Thanks for playing on our server!");
return true;
}
return false;
}
}
package me.katsunicalis.plugin;
import org.bukkit.ChatColor;
import org.bukkit.Statistic;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
public class PlayerListener implements Listener {
KillDeathCounter kdc;
public PlayerListener(KillDeathCounter plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
kdc = plugin;
}
#EventHandler
public void playerKillsPlayer(EntityDeathEvent e) {
Entity deade = e.getEntity();
Entity killer = e.getEntity().getKiller();
if (killer instanceof Player && deade instanceof Player){
int kills = kdc.getConfig().getInt("playerkills");
int deaths = kdc.getConfig().getInt("playerdeaths");
kdc.getConfig().set("playerkills", kills += 1);
kdc.getConfig().set("playerdeaths", deaths += 1);
killer.sendMessage("You now have " + kills + " kills!");
deade.sendMessage("You now have " + deaths + " deaths!");
}
}
}
Thanks very much guys! :)
The problem is that you're increasing the same variable for every time a player kills another player. To fix this, you should use a different variable for each player, for example "kills.playerUUIDHere" and "deaths.playerUUIDHere".
To get a player's UUID, you can use player.getUniqueId(), then to get the String representation of the UUID, you could use uuid.toString(). So, you could do something like this to change a player's kills:
String uuid = player.getUniqueId().toString();
int kills = kdc.getConfig().getInt("playerkills." + uuid);
kdc.getConfig().set("playerkills." + uuid, kills += 1);
The same logic can be used for deaths, so, you could use something like this for your playerKillsPlayer() method:
#EventHandler
public void playerKillsPlayer(EntityDeathEvent e) {
Entity dead = e.getEntity();
Entity killer = e.getEntity().getKiller();
if(killer instanceof Player && dead instanceof Player){
String killerUUID = ((Player) killer).getUniqueId().toString();
String deadUUID = ((Player) dead).getUniqueId().toString();
int kills = kdc.getConfig().getInt("playerkills." + killerUUID);
int deaths = kdc.getConfig().getInt("playerdeaths." + deadUUID);
kdc.getConfig().set("playerkills." + killerUUID + , kills += 1);
kdc.getConfig().set("playerdeaths." + deadUUID, deaths += 1);
killer.sendMessage("You now have " + kills + " kills!");
dead.sendMessage("You now have " + deaths + " deaths!");
}
}

ArrayList<String> not being adding to object (JAVA)

Programme class which contains a code and module(s)
import java.util.ArrayList;
public class Programme {
private ArrayList<String> modules = new ArrayList<String>();
private String ProgrammeCode;
public Programme(String ProgrammeName) {
this.ProgrammeCode = ProgrammeName;
if (modules.size() > 0) {
modules.clear(); //clear if something in modules
}
}
public Programme(String programmeCode, ArrayList<String> moduleList) {
this.ProgrammeCode = programmeCode;
modules = moduleList;
}
public void addModule(String name) {
if (name != null && !name.equals("")) {
modules.add(name);
}
}
public String getProgrammeCode() {
return ProgrammeCode;
}
public ArrayList<String> getModules() {
return modules;
}
public int getModuleCount() {
return modules.size();
}
}
This is in the class that reads csv files and stores them into type Programme, but i have a problem adding the strings into modules.
public ArrayList<Programme> loadProgrammes() {
ArrayList<String> modules = new ArrayList<String>(); //.... modules are being read from
//a csv file and have done multiple tests and its working correctly
modules.add(".....");
//PROBLEM HERE
programmes.add(new Programme(programmeStrings.get(i).get(0), modules));
//this displays as i want it to e.g. when added:3:[MA4102, CS4092, CS4162]
System.out.print("when added:" + programmes.get(i).getModuleCount() + ":" + modules);
//where as this doesn't work e.g. //Finished list:3 //LM023 0 []
//LM051 0 [] //LM110 0 []
System.out.println("\nFinished list:" + programmes.size());
for (int t = 0; t < programmes.size(); t++) {
System.out.println(programmes.get(t).getProgrammeCode() + " " + programmes.get(t).getModuleCount() + " "
+ programmes.get(t).getModules());
}
return programmes;
}
I'm not sure what is going wrong. Why isn't it adding the modules to the programme object

Using Rhino's Javascript parser, how to get the comments?

I have some javascript files and parse it using Rhino's javascript parser.
but I can't get the comments.
How can I get the comments?
here's a part of my code.
run this code, "comment" variable has null.
also, while running "astRoot.toSource();", it shows only javascript code. no comment included. it disappeared!
[java code]
public void parser() {
AstRoot astRoot = new Parser().parse(this.jsString, this.uri, 1);
List<AstNode> statList = astRoot.getStatements();
for(Iterator<AstNode> iter = statList.iterator(); iter.hasNext();) {
FunctionNode fNode = (FunctionNode)iter.next();
System.out.println("*** function Name : " + fNode.getName() + ", paramCount : " + fNode.getParamCount() + ", depth : " + fNode.depth());
AstNode bNode = fNode.getBody();
Block block = (Block)bNode;
visitBody(block);
}
System.out.println(astRoot.toSource());
SortedSet<Comment> comment = astRoot.getComments();
if(comment == null)
System.out.println("comment is null");
}
Configure your CompilerEnvirons and use AstRoot.visitAll(NodeVisitor):
import java.io.*;
import org.mozilla.javascript.CompilerEnvirons;
import org.mozilla.javascript.Parser;
import org.mozilla.javascript.ast.*;
public class PrintNodes {
public static void main(String[] args) throws IOException {
class Printer implements NodeVisitor {
#Override public boolean visit(AstNode node) {
String indent = "%1$Xs".replace("X", String.valueOf(node.depth() + 1));
System.out.format(indent, "").println(node.getClass());
return true;
}
}
String file = "foo.js";
Reader reader = new FileReader(file);
try {
CompilerEnvirons env = new CompilerEnvirons();
env.setRecordingLocalJsDocComments(true);
env.setAllowSharpComments(true);
env.setRecordingComments(true);
AstRoot node = new Parser(env).parse(reader, file, 1);
node.visitAll(new Printer());
} finally {
reader.close();
}
}
}
Java 6; Rhino 1.7R4

Categories