| 1 | package net.minecraft.server.commands;
|
| 2 |
|
| 3 | import com.mojang.brigadier.CommandDispatcher;
|
| 4 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 5 | import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
| 6 | import java.util.Collection;
|
| 7 | import net.minecraft.commands.CommandSourceStack;
|
| 8 | import net.minecraft.commands.Commands;
|
| 9 | import net.minecraft.commands.arguments.EntityArgument;
|
| 10 | import net.minecraft.commands.arguments.MessageArgument;
|
| 11 | import net.minecraft.network.chat.Component;
|
| 12 | import net.minecraft.server.level.ServerPlayer;
|
| 13 |
|
| 14 | public class KickCommand {
|
| 15 | private static final SimpleCommandExceptionType ERROR_KICKING_OWNER = new SimpleCommandExceptionType(Component.translatable("commands.kick.owner.failed"));
|
| 16 | private static final SimpleCommandExceptionType ERROR_SINGLEPLAYER = new SimpleCommandExceptionType(
|
| 17 | Component.translatable("commands.kick.singleplayer.failed")
|
| 18 | );
|
| 19 |
|
| 20 | public static void register(final CommandDispatcher<CommandSourceStack> dispatcher) {
|
| 21 | dispatcher.register(
|
| 22 | Commands.literal("kick")
|
| 23 | .requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
| 24 | .then(
|
| 25 | Commands.argument("targets", EntityArgument.players())
|
| 26 | .executes(c -> kickPlayers(c.getSource(), EntityArgument.getPlayers(c, "targets"), Component.translatable("multiplayer.disconnect.kicked")))
|
| 27 | .then(
|
| 28 | Commands.argument("reason", MessageArgument.message())
|
| 29 | .executes(c -> kickPlayers(c.getSource(), EntityArgument.getPlayers(c, "targets"), MessageArgument.getMessage(c, "reason")))
|
| 30 | )
|
| 31 | )
|
| 32 | );
|
| 33 | }
|
| 34 |
|
| 35 | private static int kickPlayers(final CommandSourceStack source, final Collection<ServerPlayer> players, final Component reason) throws CommandSyntaxException {
|
| 36 | if (!source.getServer().isPublished()) {
|
| 37 | throw ERROR_SINGLEPLAYER.create();
|
| 38 | }
|
| 39 |
|
| 40 | int count = 0;
|
| 41 |
|
| 42 | for (ServerPlayer player : players) {
|
| 43 | if (!source.getServer().isSingleplayerOwner(player.nameAndId())) {
|
| 44 | player.connection.disconnect(reason);
|
| 45 | source.sendSuccess(() -> Component.translatable("commands.kick.success", player.getDisplayName(), reason), true);
|
| 46 | count++;
|
| 47 | }
|
| 48 | }
|
| 49 |
|
| 50 | if (count == 0) {
|
| 51 | throw ERROR_KICKING_OWNER.create();
|
| 52 | } else {
|
| 53 | return count;
|
| 54 | }
|
| 55 | }
|
| 56 | }
|
| 57 |
|