Resource Sane plugin messaging with CompletableFutures

Discussion in 'Spigot Plugin Development' started by Pikachu920, Aug 13, 2018.

  1. Dealing with plugin messages in Bukkit's API is really cumbersome, and I feel it could be improved a ton. Because of this, I decided to write an easier to use implementation of plugin messages using CompletableFutures. Here is an example usage of this API to get all bungee servers via the bungee plugin message API:
    Code (Text):
        public static void test() {
            Utils.sendPluginMessage(BUNGEE_CHANNEL, r -> GET_SERVERS_CHANNEL.equals(r.readUTF()), GET_SERVERS_CHANNEL)
                    .thenAccept(r -> Skript.info("response is " + r))
                    .exceptionally(ex -> { // this will happen if there wasn't a player online to send the message through
                        Skript.warning("woopsie! the request failed");
                        return null;
                    });
        }
    and here is a more complete example that shows actually reading data from the response:
    Code (Text):
        @Override
        protected void execute(Event e) {
            String server = this.server.getSingle(e);
            if (server == null)
                return;

            Player[] players = this.players.getArray(e);
            if (ArrayUtils.isEmpty(players))
                return;

            // the message channel is case sensitive so let's fix that
            Utils.sendPluginMessage(BUNGEE_CHANNEL, r -> GET_SERVERS_CHANNEL.equals(r.readUTF()), GET_SERVERS_CHANNEL)
                .thenAccept(response ->
                    Stream.of(response.readUTF().split(", "))
                            .filter(s -> s.equalsIgnoreCase(server))
                            .findFirst()
                            .ifPresent(s -> {
                                for (Player player : players)
                                    Utils.sendPluginMessage(player, BUNGEE_CHANNEL, CONNECT_CHANNEL, s);
                            })
                );
        }

    You can find the code here.

    Note that the code contains plugin specific code (Skript#getInstance), so you'll have to replace that before using it in your plugin.
     

Share This Page