How to create command arguments?

Got it! As soon as I update the code, I will post it here.

Why don’t you just upload it to github instead?

Nah. The code is supposed to be private for my server.

I need help. I need to get the player UUiD from the CommandSource. Below is a preview of my code:

package com.blockenton.plugins.base.voter.command;

import com.blockenton.plugins.base.voter.message.ErrorMessage;

import com.google.common.base.Optional;

import org.slf4j.Logger;
import org.spongepowered.api.Server;
import org.spongepowered.api.entity.player.Player;
import org.spongepowered.api.util.command.CommandCallable;
import org.spongepowered.api.util.command.CommandException;
import org.spongepowered.api.util.command.CommandSource;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VoteCommand implements CommandCallable {

    private final Server server;

    private Logger logger;

    private Logger getLogger() {
        return logger;
    }

    private final Optional desc = Optional.of("Vote for a specific map");
    private final Optional help = Optional.of("Vote for a specific map");

    public Map PlayerMap = new HashMap();

    public VoteCommand(Server server) {
        this.server = server;
    }

    public boolean call(CommandSource source, String arguments, List parents) throws CommandException {
        String[] args = arguments.split(" ");
        try {
            int MapNumber = Integer.parseInt(args[1]);
            
            if (MapNumber == 1) {
                
            }

            if (MapNumber == 2) {

            }

            if(MapNumber == 3) {

            }

            if(MapNumber == 4) {

            }

            if(MapNumber == 5) {

            }

            if(MapNumber == 6) {

            }
            else if(MapNumber < 1 & MapNumber > 6) {
                source.sendMessage(ErrorMessage.InvalidOptionError());
            }
        } catch (Exception e) {
            source.sendMessage(ErrorMessage.InvalidOptionError());
        }
        return true;
    }

    public boolean testPermission(CommandSource source) {
        return source.hasPermission("groups.user");
    }

    public Optional getShortDescription() {
        return desc;
    }

    public Optional getHelp() {
        return help;
    }

    public String getUsage() {
        return "/ ";
    }

    public List getSuggestions(CommandSource source, String arguments) throws CommandException {
        return Collections.emptyList();
    }
}

You should consult the JavaDocs before asking simple questions.

Anyways, you use sender.getUniqueId() but you need to cast it as a Player first.

It seems to me you know basic java and that you had enough knowledge to survive making plugins in bukkit. You really do need to familiarize yourself with JavaDocs, learn some of the more intermediate things in java and you will not have a problem with this. Practice your google-fu too, its a wonderful resource.

Ah. So Player player = (Player) sender.getUniqueId()?

So you post it on a public forum instead of a public codebase? because #logic. Really, though, listen to the other guys: learn java first. I recommend TheNewBoston on youtube. Also, go read through A LOT of source code before jumping into new territory. otherwise threads like this happen. :slight_smile:

All I did was provide a short Java class. My server won’t by like the next Mineplex so I don’t mind. I want to thank the Sponge community for their help. Now I know exactly what to do.

Problem. I need to get the player UUiD from the CommandSource. What @DotDash said didn’t quite work…

Zoom into the picture! IntelliJ said that getUniqueId() is non-exsistant. I tried scanning through the possible suggestions, but I couldn’t find anything.

@frogocomics Think for a moment, take a step back and look at the various classes (interfaces in this case) there are.

source is a CommandSource (JavaDoc, Source Code)
A CommandSource is well, the source of a command. To quote from the JavaDoc:

Something that can execute commands.
Examples of potential implementations include players, the server console,
Rcon clients, web-based clients, command blocks, and so on.

OK, so you’re only interested in players right? Lets look at the Player interface (JavaDoc, Source Code)
Ahah! Player extends CommandSource
Now what?
We check to see if the source parameter is a Player

if (source instanceof Player) {
    // The command was sent by a player
}

So…
Now we know that source is a player, we can safely cast it as one.

Note: The rest of the code it to be executed within the if statement.

Player player = (Player) source;

It should be easy from there, in your IDE, you can type player. and a list of all methods will appear.

But just to complete this, Player extends Identifiable (JavaDoc, Source Code)
So you can simply call getUniqueId() on the player to get the UUID.

Complete code:

public boolean call(CommandSource source, String arguments, List<String> parents) throws CommandException {
    [...] // Stuff before?
    if (source instanceof Player) {
        Player player = (Player) source;
        UUID playerUuid = player.getUniqueId();
        // Do something with playerUuid here
    }
    [...] // Stuff after?

Now, I went into a long, slow process to explain this but the key is to look at the API, figure out how to use it, experiment, test things, ask google for any java questions and so on.

3 Likes

I sent you a private message. :smile:

Why would you do that? You ar get the players UUID, you can’t cast that to a player.

Hint: callers.add(UUID playerUID = sender.getUniqueId())
Not that this assumes a List<UUID> callers

1 Like

Question: To store the player’s UUID temporary, what collection should I use. A List? A HashMap? A Vector?

It depends, do you want to map it to anything? If so, HashMap. If you want a list use ArrayList.

1 Like

Preview of my code:

package com.blockenton.plugins.base.voter.command;

/*
Manage Imports
*/
import com.blockenton.plugins.base.voter.message.ErrorMessage;

import com.google.common.base.Optional;

import org.slf4j.Logger;

import org.spongepowered.api.Server;
import org.spongepowered.api.entity.player.Player;
import org.spongepowered.api.util.command.CommandCallable;
import org.spongepowered.api.util.command.CommandException;
import org.spongepowered.api.util.command.CommandSource;

import java.util.*;

/**
 * 

* The main class of the /vote command. * This class is registered in the {@link com.blockenton.plugins.base.voter.JavaPlugin} * class. This class implements {@link org.spongepowered.api.util.command.CommandCallable} * in order to create a command. *

* * @since 0.0.1-DEV-2 * @author Jeff Chen */ public class VoteCommand implements CommandCallable { private final Server server; private Logger logger; private Logger getLogger() { return logger; } private final Optional desc = Optional.of("Vote for a specific map"); private final Optional help = Optional.of("Vote for a specific map"); public VoteCommand(Server server) { this.server = server; } /** *

* What happens when the command is called by the * player or the console is below. *

* * @param source The source of the command, who it was sent by. * @param arguments Any arguments the player supplies. * @param parents Any traits the command inherits from. * @return If the command was successfully sent. * @throws CommandException * * @since 0.0.1-DEV-2 * @see org.spongepowered.api.util.command.CommandSource */ public boolean call(CommandSource source, String arguments, List parents) throws CommandException { String[] args = arguments.split(" "); if(!(source instanceof Player)) { source.sendMessage(ErrorMessage.PlayerOnlyError()); return false; } Player player = (Player) source; UUID playerUUID = player.getUniqueId(); /* If someone uses the /vote command without providing arguments, it will show the player all the possible choices(arguments) */ if(args.length <= 0) { } /* If someone using the /vote command supplies two arguments such as "/vote argument1 argument2", it will notify the player about this problem. */ if(args.length >= 2) { } try { int MapNumber = Integer.parseInt(args[1]); if (MapNumber == 1) { } if (MapNumber == 2) { } if(MapNumber == 3) { } if(MapNumber == 4) { } if(MapNumber == 5) { } if(MapNumber == 6) { } else if(MapNumber < 1 & MapNumber > 6) { player.sendMessage(ErrorMessage.InvalidOptionError()); getLogger().info(player.getName() + " has entered an invalid option."); return false; } } catch (NumberFormatException e) { player.sendMessage(ErrorMessage.InvalidOptionError()); getLogger().info(player.getName() + " has entered an invalid option."); return false; } return true; } /** *

* Test if a player has the correct permissions to * use this plugin. *

* * @param source The source of the command, who it was sent by. * @return If the source has the correct permissions. * * @since 0.0.1-DEV-2 */ public boolean testPermission(CommandSource source) { return source.hasPermission("groups.user"); } public Optional getShortDescription() { return desc; } public Optional getHelp() { return help; } /** *

* Gets the usage of the command. *

* * @return The usage of the command. * @since 0.0.1-DEV-2 */ public String getUsage() { return "/ "; } public List getSuggestions(CommandSource source, String arguments) throws CommandException { return Collections.emptyList(); } }

I really can’t tell what you want list-wise, but I would either use an else if setup or a switch case setup for the MapNumber choosing.

A switch would probably be better looking here. IMO

Just to quickly mention one thing I spotted - at the line:

else if(MapNumber < 1 & MapNumber > 6) {

you’ll want it to be “&&” (logical AND) rather than “&” (bitwise AND). While I think about it, if you follow @RobodudeMC’s suggestion of switches (which isn’t a bad one - though it might be easier to convert what you have to else ifs now given most of it is there!), make sure you include break statements too at the end of each case block. His suggestion is a good one, as you don’t want to make any unnecessary checks.

See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html for information on switches. Good luck with learning Java, and good luck with the plugin.

1 Like

Just read about you storing UUIDs temporarily. I suspect you want to prevent the users from running the command twice in a set period? If so, it depends on how long you want to store the information.

If you want to stop a player from running the command again for, say 30 minutes: I would consider using a HashMap<UUID, Date> collection, and when you run the command, compare the current time with the time stored in the value for the given UUID. Be sure to check for nulls though. Note you can only store a UUID once in such a collection, attempting to add a UUID again here would overwrite the previous value.

If you are preventing players from running the command until a certain server event such as a map change, i.e., everyone can vote again after a certain point, I would just add UUIDs to a HashSet<UUID> if you only need to store the UUID once (Sets don’t allow duplicates) or an ArrayList<UUID>, and clear it when the event happens. HashSets tend to be faster than ArrayLists or larger amounts of data, though (obligitory reference to Stack Overflow)

If I’ve got why you want to store player data temporarily totally wrong - sorry!

1 Like