Search code examples
javaminecraftbukkit

Is there a way to catch a players chat input without an AsyncPlayerChatEvent?


I'm once again writing another Banksystem plugin, but this time with an ATM. I'm trying to figure out how to get a players chat-input after clicking on the option, to prevent clicking 100 times to deposit 50,000 Dollars on the bank-account.

I'm writing this Plugin with Paper-Spigot 1.14.4 and I've tried following steps:

  • A AsyncPlayerChatEvent as a separate Class, which activates only when I register the Event with the Pluginmanager:
Bukkit.getPluginManager().registerEvents(new ChatListener(), Main.getPlugin());
  • Creating a private AsyncPlayerChatEvent variable e with get- and set-method, and calling it in the method when I need it.
String input = getChat().getMessage();

My current chatListener() Method:

public void chatListener(Inventory inv, Player pl) {
        pl.closeInventory();
        pl.sendMessage("§6Please enter your amount:");
        String input = getChat().getMessage();
        if(input.matches("[0-9]+")) {
            pl.openInventory(inv);
            inv.setItem(0, new ItemStack(Material.AIR));
            inv.setItem(0, CustomHeads.customHead(CustomHeads.BITCOIN,
                    input));
        } else {
            pl.sendMessage("§cPlease enter only numeric characters!");
        }
    }

AsyncPlayerChatEvent get-method:

public AsyncPlayerChatEvent getChat() {
        return chat;
    }

I expect the message of the player to be saved inside the input variable, after the message "Please enter your amount:" appears.

When I create a System.out.println(input), the console shows nothing, including neither errors nor any warnings.


Solution

  • Create an AsyncPlayerChatEvent and a public static ArrayList.

    ExampleChatEvent.class

    public static ArrayList<Player> waitingForAmountPlayers = new ArrayList<>();
    
    public void onChat(AsyncPlayerChatEvent e) {
    
     Player p = e.getPlayer();
    
     if (waitingForAmountPlayers.indexOf(p) != -1) {
    
      //
      // YOUR CODE
      //
    
      waitingForAmountPlayers.remove(p);
    
     }
    
    }
    

    Don't forget to add the player to waitingForAmountPlayers when you want to type the player the amount in the chat (ExampleChatEvent.waitingForAmountPlayers.add(p);).