Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Какая структура и на чём всё хранится в данном плагине: package net.pandadev.chattr;…

  1. User

    Какая структура и на чём всё хранится в данном плагине: package net.pandadev.chattr;

    import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.command.SimpleCommand; import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.server.RegisteredServer; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.minimessage.MiniMessage;

    import java.util.*; import java.util.stream.Collectors;

    public class Commands {

    private static final Map<Player, Player> lastMessaged = new HashMap<>();
    private static final MiniMessage miniMessage = MiniMessage.miniMessage();
    private static final Random random = new Random();
    
    public static class MsgCommand implements SimpleCommand {
        private final ProxyServer server;
    
        public MsgCommand(ProxyServer server) {
            this.server = server;
        }
    
        @Override
        public void execute(Invocation invocation) {
            CommandSource source = invocation.source();
            String[] args = invocation.arguments();
    
            if (args.length < 2) {
                source.sendMessage(Component.text("Usage: /msg <selector> <message>", NamedTextColor.RED));
                return;
            }
    
            String selector = args[0];
            String message = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
            List<Player> targets = resolveSelector(selector, source);
    
            if (targets.isEmpty()) {
                source.sendMessage(Component.text("Player not found.", NamedTextColor.RED));
                return;
            }
    
            for (Player target : targets) {
                if (source instanceof Player playerSource) {
                    lastMessaged.put(target, playerSource);
                    lastMessaged.put(playerSource, target);
                }
    
                String formattedMsgTo = "<#ff6f00>[MSG To] <dark_gray>•</dark_gray> <white>" + target.getUsername()
                        + "</white> <#ff6f00>" + message;
                String formattedMsgFrom = "<#ff6f00>[MSG From] <dark_gray>•</dark_gray> <white>"
                        + (source instanceof Player ? ((Player) source).getUsername() : "<bold>Server</bold>")
                        + "</white> <#ff6f00>" + message;
    
                source.sendMessage(miniMessage.deserialize(formattedMsgTo));
                target.sendMessage(miniMessage.deserialize(formattedMsgFrom));
            }
        }
    
        @Override
        public List<String> suggest(Invocation invocation) {
            String[] args = invocation.arguments();
            List<String> suggestions = new ArrayList<>();
    
            if (args.length == 0 || args.length == 1) {
                suggestions.add("@a");
                suggestions.add("@r");
                suggestions.add("@s");
    
                CommandSource finalSource = invocation.source();
                suggestions.addAll(server.getAllPlayers().stream()
                        .map(Player::getUsername)
    

    // .filter(username -> !(finalSource instanceof Player && username.equals(((Player) finalSource).getUsername()))) .toList()); } if (args.length == 1 && !args[0].isEmpty()) { String currentInput = args[0].toLowerCase(); return suggestions.stream() .filter(s -> s.toLowerCase().startsWith(currentInput)) .collect(Collectors.toList()); } return suggestions; }

        private List<Player> resolveSelector(String selector, CommandSource source) {
            return switch (selector) {
                case "@a" -> new ArrayList<>(server.getAllPlayers());
                case "@r" -> {
                    List<Player> allPlayers = new ArrayList<>(server.getAllPlayers());
                    yield List.of(allPlayers.get(random.nextInt(allPlayers.size())));
                }
                case "@s" -> source instanceof Player player ? List.of(player) : List.of();
                default -> server.getAllPlayers().stream()
                        .filter(player -> player.getUsername().equalsIgnoreCase(selector))
                        .toList();
            };
        }
    }
    
    public static class ReplyCommand implements SimpleCommand {
        public ReplyCommand() {
    
        }
    
        @Override
        public void execute(Invocation invocation) {
            CommandSource source = invocation.source();
            String[] args = invocation.arguments();
    
            if (!(source instanceof Player playerSource)) {
                source.sendMessage(Component.text("Only players can use this command.", NamedTextColor.RED));
                return;
            }
    
            if (args.length < 1) {
                source.sendMessage(Component.text("Usage: /r <message>", NamedTextColor.RED));
                return;
            }
    
            Player target = lastMessaged.get(playerSource);
    
            if (target == null) {
                playerSource.sendMessage(Component.text("No one to reply to.", NamedTextColor.RED));
                return;
            }
    
            String message = String.join(" ", args);
            String formattedMsgTo = "<#ff6f00>[Reply To] <dark_gray>•</dark_gray> <white>" + target.getUsername()
                    + "</white> <#ff6f00>" + message;
            String formattedMsgFrom = "<#ff6f00>[Reply From] <dark_gray>•</dark_gray> <white>"
                    + playerSource.getUsername() + "</white> <#ff6f00>" + message;
    
            playerSource.sendMessage(miniMessage.deserialize(formattedMsgTo));
            target.sendMessage(miniMessage.deserialize(formattedMsgFrom));
            lastMessaged.put(target, playerSource);
            lastMessaged.put(playerSource, target);
        }
    }
    

    }

  2. Assistant

    The plugin you've provided is designed for the Velocity proxy server, commonly used in Minecraft server networks. It implements private messaging functionality with support for replying to the last messaged player. Here's an in-depth explanation of its structure and how data is stored:

    Structure of the Plugin

    1. Package and Imports:

      • Package: net.pandadev.chattr indicates the organization's domain and project name (pandadev and chattr respectively).
      • Imports: The plugin imports classes from com.velocitypowered.api for interacting with the Velocity API, net.kyori.adventure.text for handling text components, and standard Java utilities.
    2. Main Class (Commands):

      • This class contains all the command implementations and shared resources.
    3. Static Fields:

      • lastMessaged: A Map<Player, Player> that keeps track of the last player each player messaged or was messaged by.
      • miniMessage: An instance of MiniMessage for parsing formatted strings.
      • random: A Random object used for selecting a random player.
    4. Nested Classes Implementing Commands:

      • MsgCommand:
        • Implements SimpleCommand to handle the /msg command.
        • Constructor: Accepts a ProxyServer instance to access server-wide player data.
        • execute Method:
          • Parses command arguments to determine the target player(s) and message content.
          • Uses resolveSelector to handle selectors like @a (all players), @r (random player), @s (command sender), or specific player names.
          • Sends formatted messages to the sender and targets.
          • Updates lastMessaged to track recent messaging interactions.
        • suggest Method:
          • Provides command suggestions for player names and selectors.
          • Implements tab-completion functionality.
        • resolveSelector Method:
          • Determines the list of target players based on the selector or player name.
      • ReplyCommand:
        • Implements SimpleCommand to handle the /r command.
        • execute Method:
          • Checks if the sender has someone to reply to using the lastMessaged map.
          • Sends the reply message to the last player they interacted with.
          • Updates lastMessaged accordingly.

    Data Storage in the Plugin

    • In-Memory Storage:

      • The plugin uses a static Map<Player, Player> called lastMessaged to store data about the last messaging interactions between players.
      • Purpose: Allows the plugin to track who each player last sent a message to or received a message from, which is essential for the reply functionality (/r command).
      • Scope: Being static, this map is shared across all instances of the command classes and persists as long as the server is running.
    • Data Lifecycle:

      • Addition: Entries are added to lastMessaged whenever a player sends a message using /msg or /r.
      • Retrieval: When a player uses /r, the plugin looks up the last player they communicated with from the map.
      • Updating: The map is updated with each new messaging interaction to ensure it always reflects the most recent communication.
      • Persistence: The data is not saved to disk; it exists only in memory. If the server restarts, the map is cleared.
    • Thread Safety:

      • Since Velocity plugins typically run on a single thread (the main server thread), concurrent access issues are minimal. However, if the plugin were to be used in a multithreaded context, synchronization mechanisms would be needed to prevent concurrent modification exceptions.

    Key Components and Flow

    • Command Registration:

      • Both commands need to be registered with the Velocity server for players to use them.
    • Message Formatting:

      • Uses MiniMessage for rich text formatting, allowing for colored and styled messages.
    • Selectors Handling:

      • The plugin supports special selectors (@a, @r, @s) akin to those in Minecraft command syntax, enhancing its flexibility.
    • Player Interaction:

      • The commands check whether the source of the command is a player or the console, ensuring appropriate handling and feedback.

    Summary

    The plugin is structured around two main commands that facilitate private messaging between players on a Velocity proxy server. It stores interaction data in a static in-memory map (lastMessaged), which serves as a lookup table for reply functionality. The reliance on in-memory storage means the plugin is straightforward but does not retain data between server restarts.


    Note: For persistent storage (e.g., across server restarts), additional mechanisms like writing to a file or database would need to be implemented.