getInt Function Doesn't Return Anything - java

I am currently trying to making a custom rules plugin (for minecraft) and I am trying to see if the player has something activated which I stored in the config file. It is in the listener class (which calls the config from the main). Here is my code:
#EventHandler
public void onEvent(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
if (config.getInt("EditingLine." + player.getName().toLowerCase()) == 1) {
int line = 0;
try {
line = Integer.parseInt(e.getMessage());
} catch (Exception b) {
player.sendMessage(ChatColor.RED + "Invalid Number.");
config.set("EditingLine." + player.getName().toLowerCase(), 0);
}
if (!(line == 0)) {
config.set("EditingLine." + player.getName().toLowerCase(), 0);
config.set("EditingText." + player.getName().toLowerCase(), 1);
e.setCancelled(true);
player.sendMessage(ChatColor.GRAY + "[" + ChatColor.GOLD + "Custom Rules" + ChatColor.GRAY + "]" + ChatColor.GREEN + " Enter the text you would now like on that line.");
}
}
}
The, config.getInt() function in the if then statement currently returns nothing. This may be happening because the config in the Listener Class is actually calling a custom made config, called 'playerdata.yml' and not the actual 'config.yml'. If there is any easier way to write this script, also let me know. I'm trying to make this as simple as I can.

The answer has been solved by merging my two configuration files together.

Related

Seperating ArrayList items to a regular keyword group

I started Java for plugin codding in minecraft. now I'm trying to add role names as prefix and show it in chat.
ArrayList<String> userRoles = new ArrayList<String>();
if(player.hasPermission("chat.rank.admin")){
userRoles.add("[Admin]");
} if(player.hasPermission("chat.rank.vip")) {
userRoles.add("[VIP]");
}
event.setFormat(userRoles<>(1) + " " + player.getDisplayName() + "§7: " + msg);
// In this line, the expected output is "[Admin] user: msg" or both [Admin] [VIP] user: msg"
// But it gives "([Admin],[VIP]) user: msg"
// I'm sure it has a simple solution but as I said, I'm new here. thanks from now
It seems like you are trying to create a list which only stores one value.
You might want to try creating a function that get the rank name of the player outside of your PlayerChatEvent listener.
Here's a demo code:
public String getPlayerRankName(Player p){
if (p.hasPermission("chat.rank.admin"))
return "[Admin]";
else if (p.hasPermission("chat.rank.vip"))
return "[VIP]";
else
return "";
}
And in your PlayerChatEvent event listener, call this function in your chat line:
event.setFormat(getPlayerRankName(event.getPlayer()) + " " + player.getDisplayName() + "§7: " + msg);

Youtube Search Command for JDA Discord Music Bot

I've been working on a Discord bot for a few days now.
Initially only with simpler commands etc. But slowly I also devoted myself to the topic of music bot.
I also use the YouTube Data API for this and everything works so far. However, I would now like to incorporate a Youtube Search Command or build it into another (Play Command). I already have half a search command.
So far you can do $play (song title)
and the first track found will be selected.
However, I want to be able to see the first 10 search results and then choose between them.
I have already figured out how to display the search results, but now I need a little help with how to enter a command, after you have already entered another.
So you enter: $play Faded
Then a normal EmbedBuilder comes up and shows you the search results, and then you can select the desired track by entering 1, 2, 3, 4, 5, 6, 7, 8, 9 or 10.
This is the code:
public class PlayCommand implements ServerCommand {
private final YouTube youTube;
public PlayCommand() {
YouTube temp = null;
try {
temp = new YouTube.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
null
)
.setApplicationName("JDA Discord Bot")
.build();
} catch (Exception e) {
e.printStackTrace();
}
youTube = temp;
}
#Override
public void performCommand(List<String> args, Member m, TextChannel channel, Message message) throws RiotApiException {
String input = String.join(" ", args.subList(1, args.size() - 1));
if (!isUrl(input)) {
String ytSearched = searchYoutube(channel, input);
if (ytSearched == null) {
channel.sendMessage("Keine Ergebnisse!").queue();
return;
}
input = ytSearched;
}
PlayerManager manager = PlayerManager.getInstance();
manager.loadAndPlay(channel, input);
manager.getGuildMusicManager(channel.getGuild()).player.setVolume(100);
}
private boolean isUrl(String input) {
try {
new URL(input);
return true;
} catch (MalformedURLException ignored) {
return false;
}
}
#Nullable
private String searchYoutube(TextChannel channel, String input) {
String youtubeKey = "AIzaSyDoQ4OInMTYth7hdlWwQSIaHuxpxxv7eJs";
try {
List<SearchResult> results = youTube.search()
.list("id,snippet")
.setQ(input)
.setMaxResults(10L)
.setType("video")
.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)")
.setKey(youtubeKey)
.execute()
.getItems();
if (!results.isEmpty()) {
String videoId = results.get(0).getId().getVideoId();
/*EmbedBuilder builder = new EmbedBuilder();
builder.setTitle("Suchergebnisse");
builder.setColor(Color.RED);
builder.setDescription( "1. " + results.get(0).getSnippet().getTitle() + "\n" +
"2. " + results.get(1).getSnippet().getTitle() + "\n" +
"3. " + results.get(2).getSnippet().getTitle() + "\n" +
"4. " + results.get(3).getSnippet().getTitle() + "\n" +
"5. " + results.get(4).getSnippet().getTitle() + "\n" +
"6. " + results.get(5).getSnippet().getTitle() + "\n" +
"7. " + results.get(6).getSnippet().getTitle() + "\n" +
"8. " + results.get(7).getSnippet().getTitle() + "\n" +
"9. " + results.get(8).getSnippet().getTitle() + "\n" +
"10. " + results.get(9).getSnippet().getTitle());
channel.sendMessage(builder.build()).queue();
*/
return "https://www.youtube.com/watch?v=" + videoId;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
I think you are looking for an EventWaiter.
With JDA-Utilities you can achieve what you want.
You just basically wait for an event, check if it's suitable for the use case of yours (eg: is a specific event, or contains a specific text)
Check out this stackoverflow answer about EventWaiter and adding it as an EventListener.
You would want to check if the received text for example is part of the youtube search result. Also don't forget about having a time limit for accepting answers.

Bukkit plugin kick reason only using first word

So I'm making a kick/ban command for my server and the format is /kick name reason.
I got it all working but the reason can only be 1 word and anything over that excludes it, for example /kick BattleDash hello world would say BattleDash was kicked for hello.
Here's my code:
if (cmd.getName().equalsIgnoreCase("kick") && sender instanceof Player) {
Player player = (Player) sender;
int length = args.length;
if (length >= 2) {
boolean playerFound = false;
for (Player playerToKick : Bukkit.getServer().getOnlinePlayers()) {
if(playerToKick.getName().equalsIgnoreCase(args[0])) {
playerToKick.kickPlayer(ChatColor.RED + "Kicked by Administrator " + player.getName() + "\nReason: " + args[1]);
player.sendMessage(ChatColor.RED + "[BATTLEDASHLOGS]: Kicked player " + playerToKick.getName() + "succesfully!");
break;
}
}
if (playerFound == false) {
player.sendMessage(ChatColor.RED + "[BATTLEDASHLOGS]: " + args[0] + " was not found!");
}
} else player.sendMessage(ChatColor.RED + "[BATTLEDASHLOGS]: Incorrect arguments!" + ChatColor.RED + " /kick <PlayerName> <reason>");
return true;
}
(Also if you don't include a reason it gives internal error in chat and exception occured in console)
Your code is doing that due to the way it was programmed.
If we take a look at line that takes the argument:
playerToKick.kickPlayer(ChatColor.RED + "Kicked by Administrator " + player.getName() + "\nReason: " + args[1]);
We can see that you're only using args[1]. If we see a message as an array, the problem will be clear:
At position 0 (remember arrays start at 0): BattleDash
1: hello
2: world
When you take only args[1] to your message, only hello would be used! What we need to do instead, is use all the arguments. One way to do that is like this:
// First, transform your array into a list, so it's easier to understand
List<String> arguments = new ArrayList<>(args);
String playerName = arguments.get(0); // Get the player name
arguments.remove(0); // Remove the player name from our arguments list, we don't want it in the message
String message = String.join(" ", arguments); // Combine all the other arguments into a message

How to save information from JTable to a File?

Here is my case:
So far my group and I, managed to read information from an external file and place it in a JTable. But we need an update button. So we guess we should take all the information from JTable after editting something inside it, and replace it with the current information in the same file. So we kind of think we have to overwrite the old file.
So far we got this: (for int i... is a part of the code but can't get it inside the grey area :P)
for(int i = 0; i < model.getRowCount(); i++) {
p += model.getValueAt(i, 0) + " "
+ model.getValueAt(i, 1) + " "
+ (Integer) model.getValueAt(i, 2) + " "
+ model.getValueAt(i, 3) + " "
+ (Integer)model.getValueAt(i, 4) + " "
+ model.getValueAt(i, 5) + " "
+ model.getValueAt(i, 6) + " "
+ model.getValueAt(i, 7) + " "
+ (Integer)model.getValueAt(i, 8) + "\n";
}
// Update File
SaveMember sm = new SaveMember();
sm.update(p);
Inside our SaveMember.java we got:
public void update(String x) throws Exception {
File f = new File("Members/Members.txt");
PrintStream output = new PrintStream(f);
output.print(x);
So by now when we go and change the data and press the button update, it doesn't do anything at all, and doesn't replace the old data with the new.. Thanks for reading! :)
I'm not sure. If you have double checked that your code is executed at all (maybe you forgot to attach the ActionListener to your button - we all do that from time to time...) try flush the output stream and close the stream afterwards.
First check if your code in the for loop is executed at all. Set a breakpoint after the for loop and inspect the string p. If you are not familiar with debugging, print the string to the console with System.out.println(p).
If your code is NOT executed: Check why the method your code is in is not called. Perhaps you forgot to attach an action listener to your update button or the action listener has an early return under some circumstances.
If your code is executed: What do you do with the exception that is thrown by the method update? Make sure to log it with your logger or print it to the console (again via System.out.println(exc)). If you get a FileNotFoundException the path to the file is not correct.

Threads in Java, states? Also what is the right way to use them?

I'm up for my exame presentation the day after tomorrow, so i need to get some straight before it which i hope you guys can help me with.
First i do know that there are 4 states of Threads (i.e Running, Ready, Blocked, Terminated), however i'm not quite sure how it works in Java. In my code i use the thread.sleep(3000) to do some waiting in the program, does this make the thread Blocked or Ready?
Also it have come to my attention that i might not have used the threads the right way, let me show you some code
public class BattleHandler implements Runnable {
private Player player;
private Monster enemyMonster;
private Dungeon dungeon;
private JTextArea log;
private GameScreen gScreen;
public void run() {
try {
runBattle();
}
catch(Exception e) { System.out.println(e);}
}
public BattleHandler(Player AttackingPlayer, JTextArea log, GameScreen gScreen) {
this.player = AttackingPlayer;
this.log = log;
this.gScreen = gScreen;
}
public void setDungeon(Dungeon dungeon) {
this.dungeon = dungeon;
}
public Dungeon getDungeon() {
return dungeon;
}
public Monster getEnemyMonster() {
return enemyMonster;
}
public void setMonster() {
// First check if dungeon have been init, if not we can't generate the mob
if(dungeon != null) {
enemyMonster = new Monster();
// Generate monster stats
enemyMonster.generateStats(dungeon);
}else {
System.out.println("Dungeon was not initialized");
}
}
public void runBattle() throws InterruptedException {
// Start battle, and run until a contester is dead.
while(player.getHealth() > 0 && enemyMonster.getHealth() > 0) {
int playerStrikeDmg = player.strike();
if(enemyMonster.blockDefend()) {
log.setText( log.getText() + "\n" + player.getName() +" tried to strike " + enemyMonster.getName()+ ", but " + enemyMonster.getName() + " Blocked.");
}else if(enemyMonster.dodgeDefend()) {
log.setText( log.getText() + "\n" + player.getName() +" tried to strike " + enemyMonster.getName()+ ", but " + enemyMonster.getName() + " Blocked.");
}else {
enemyMonster.defend(playerStrikeDmg);
log.setText( log.getText() + "\n" + player.getName() +" strikes " + enemyMonster.getName()+ " for: " + playerStrikeDmg + " left: "+ enemyMonster.getHealth());
}
if(enemyMonster.getHealth() < 1) break;
Thread.sleep(3000);
// Monster Turn
int monsterDmg = enemyMonster.strike();
if(player.blockDefend()) {
log.setText( log.getText() + "\n" + enemyMonster.getName() +" tried to strike " + player.getName()+ ", but " + player.getName()+ " Blocked.");
}else if(player.dodgeDefend()) {
log.setText( log.getText() + "\n" + enemyMonster.getName() +" tried to strike " + player.getName()+ ", but " + player.getName()+ " Dodged.");
}else {
player.defend(monsterDmg);
log.setText( log.getText() + "\n" + enemyMonster.getName() +" strikes " + player.getName()+ " for: " + monsterDmg + " left: "+ player.getHealth());
}
gScreen.updateBot();
Thread.sleep(3000);
}
When i coded this i thought it was cool, but i have seen some make a class just for controlling the Thread itself. I have just made the class who uses the Sleep runable(Which is not shown in the code, but its a big class).
Would be good to get this straight, so i can point i out before they ask me about it, you know take away there ammunition. :D
Hope you guys can help me :).
Thx
Threads have more than 4 states. Also, I recommend reading Lesson: Concurrency for more information regarding threads.
Note that if you're looking to execute a task at a set interval, I highly recommend using the Executors framework.
Blocked - it will not run at all until timeout. Ready is 'runnable now but there is no processor available to run it - will run as soon as a processor becomes available'.
As all the other guys state, there are more than those, here's a simple listing:
Running - Guess what, it's running
Waiting - It waits for another thread to complete its calculation (that's the wait() method in Java). Basically such a thread can also be run by the scheduler, like the "ready" state threads.
Ready - Means that the Thread is ready for execution, once the OS-Scheduler turns to this Thread, it will execute it
Blocked - Means that there is another operation, blocking this threads execution, such as IO.
Terminated - Guess what, it's done and will be removed by the OS-Scheduler.
For a complete listing, look at the famous Wikipedia ;)
http://en.wikipedia.org/wiki/Process_state

Categories