Files
src
INTEGRATION_EXAMPLE.txt
Code
3 335
src/main/java/com/mcnetworkplus/command/ServerCommandManager.java
package com.mcnetworkplus.command;
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.minimessage.MiniMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
public class ServerCommandManager {
private final ProxyServer proxyServer;
private final Function<String, String> messageProvider;
private final Function<String, Component> colorizer;
public ServerCommandManager(ProxyServer proxyServer, Function<String, String> messageProvider, Function<String, Component> colorizer) {
this.proxyServer = proxyServer;
this.messageProvider = messageProvider;
this.colorizer = colorizer;
}
public void registerAllServerCommands() {
for (RegisteredServer server : proxyServer.getAllServers()) {
String serverName = server.getServerInfo().getName().toLowerCase();
registerServerCommand(serverName);
}
}
private void registerServerCommand(String serverName) {
proxyServer.getCommandManager().register(
proxyServer.getCommandManager().metaBuilder(serverName)
.build(),
new DynamicServerCommand(serverName)
);
}
private class DynamicServerCommand implements SimpleCommand {
private final String targetServerName;
public DynamicServerCommand(String targetServerName) {
this.targetServerName = targetServerName;
}
@Override
public void execute(Invocation invocation) {
if (!(invocation.source() instanceof Player)) {
return;
}
Player player = (Player) invocation.source();
Optional<RegisteredServer> serverOptional = proxyServer.getServer(targetServerName);
if (!serverOptional.isPresent()) {
String message = messageProvider.apply("movecommands_server_not_found")
.replace("{server}", targetServerName);
player.sendMessage(colorizer.apply(message));
return;
}
RegisteredServer targetServer = serverOptional.get();
if (player.getCurrentServer().isPresent() &&
player.getCurrentServer().get().getServer().equals(targetServer)) {
String message = messageProvider.apply("movecommands_already_connected")
.replace("{server}", targetServerName);
player.sendMessage(colorizer.apply(message));
return;
}
player.createConnectionRequest(targetServer).fireAndForget();
}
@Override
public boolean hasPermission(Invocation invocation) {
return invocation.source().hasPermission("mcnp.server." + targetServerName);
}
@Override
public List<String> suggest(Invocation invocation) {
return new ArrayList<>();
}
}
}