Какая структура и на чём всё хранится в данном плагине: package net.pandadev.chattr;…
- 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); } }}
- 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
-
Package and Imports:
- Package:
net.pandadev.chattrindicates the organization's domain and project name (pandadevandchattrrespectively). - Imports: The plugin imports classes from
com.velocitypowered.apifor interacting with the Velocity API,net.kyori.adventure.textfor handling text components, and standard Java utilities.
- Package:
-
Main Class (
Commands):- This class contains all the command implementations and shared resources.
-
Static Fields:
lastMessaged: AMap<Player, Player>that keeps track of the last player each player messaged or was messaged by.miniMessage: An instance ofMiniMessagefor parsing formatted strings.random: ARandomobject used for selecting a random player.
-
Nested Classes Implementing Commands:
MsgCommand:- Implements
SimpleCommandto handle the/msgcommand. - Constructor: Accepts a
ProxyServerinstance to access server-wide player data. executeMethod:- Parses command arguments to determine the target player(s) and message content.
- Uses
resolveSelectorto 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
lastMessagedto track recent messaging interactions.
suggestMethod:- Provides command suggestions for player names and selectors.
- Implements tab-completion functionality.
resolveSelectorMethod:- Determines the list of target players based on the selector or player name.
- Implements
ReplyCommand:- Implements
SimpleCommandto handle the/rcommand. executeMethod:- Checks if the sender has someone to reply to using the
lastMessagedmap. - Sends the reply message to the last player they interacted with.
- Updates
lastMessagedaccordingly.
- Checks if the sender has someone to reply to using the
- Implements
Data Storage in the Plugin
-
In-Memory Storage:
- The plugin uses a static
Map<Player, Player>calledlastMessagedto 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 (
/rcommand). - Scope: Being static, this map is shared across all instances of the command classes and persists as long as the server is running.
- The plugin uses a static
-
Data Lifecycle:
- Addition: Entries are added to
lastMessagedwhenever a player sends a message using/msgor/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.
- Addition: Entries are added to
-
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
MiniMessagefor rich text formatting, allowing for colored and styled messages.
- Uses
-
Selectors Handling:
- The plugin supports special selectors (
@a,@r,@s) akin to those in Minecraft command syntax, enhancing its flexibility.
- The plugin supports special selectors (
-
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.
-