Java Code Examples for org.bukkit.entity.Player#kickPlayer()

The following examples show how to use org.bukkit.entity.Player#kickPlayer() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DeathBansModule.java    From UHC with MIT License 6 votes vote down vote up
@Override
public void run() {
    timers.remove(uuid);

    final Player player = Bukkit.getPlayer(uuid);
    player.sendMessage(message);

    if (types.contains(BanType.BAN)) {
        final Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, (int) duration);

        Bukkit.getBanList(BanList.Type.NAME).addBan(player.getName(), message, calendar.getTime(), "UHC");
    }

    if (types.contains(BanType.MOVE_SERVER)) {
        player.sendPluginMessage(plugin, "BungeeCord", ("Connect" + serverName).getBytes());
    }

    if (types.contains(BanType.KICK)) {
        player.kickPlayer(message);
    }
}
 
Example 2
Source File: KickArgument.java    From Hawk with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean process(CommandSender sender, Command cmd, String label, String[] args) {
    if (args.length < 3)
        return false;
    Player target = Bukkit.getPlayer(args[1]);
    if (target == null) {
        sender.sendMessage(ChatColor.RED + "Unknown player \"" + args[1] + "\"");
        return true;
    }
    List<String> list = new LinkedList<>(Arrays.asList(args));
    list.remove(0);
    list.remove(0);
    String reason = ChatColor.translateAlternateColorCodes('&', String.join(" ", list));
    target.kickPlayer(reason);
    sender.sendMessage(ChatColor.GOLD + target.getName() + " has been kicked.");
    return true;
}
 
Example 3
Source File: PlayerListener.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
    String cmd = event.getMessage().split(" ")[0].toLowerCase();
    if (settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD) && "/motd".equals(cmd)) {
        return;
    }
    if (settings.getProperty(RestrictionSettings.ALLOW_COMMANDS).contains(cmd)) {
        return;
    }
    final Player player = event.getPlayer();
    if (!quickCommandsProtectionManager.isAllowed(player.getName())) {
        event.setCancelled(true);
        player.kickPlayer(messages.retrieveSingle(player, MessageKey.QUICK_COMMAND_PROTECTION_KICK));
        return;
    }
    if (listenerService.shouldCancelEvent(player)) {
        event.setCancelled(true);
        messages.send(player, MessageKey.DENIED_COMMAND);
    }
}
 
Example 4
Source File: Whitelist.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public int kickAll() {
    int count = 0;
    for(Player player : onlinePlayers.all()) {
        if(!isWhitelisted(player)) {
            player.kickPlayer(renderer.renderLegacy(new TranslatableComponent("whitelist.kicked"), player));
            count++;
        }
    }
    return count;
}
 
Example 5
Source File: OnJoinVerifier.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Handles the case of a full server and verifies if the user's connection should really be refused
 * by adjusting the event object accordingly. Attempts to kick a non-VIP player to make room if the
 * joining player is a VIP.
 *
 * @param event the login event to verify
 *
 * @return true if the player's connection should be refused (i.e. the event does not need to be processed
 *         further), false if the player is not refused
 */
public boolean refusePlayerForFullServer(PlayerLoginEvent event) {
    final Player player = event.getPlayer();
    if (event.getResult() != PlayerLoginEvent.Result.KICK_FULL) {
        // Server is not full, no need to do anything
        return false;
    } else if (!permissionsManager.hasPermission(player, PlayerStatePermission.IS_VIP)) {
        // Server is full and player is NOT VIP; set kick message and proceed with kick
        event.setKickMessage(messages.retrieveSingle(player, MessageKey.KICK_FULL_SERVER));
        return true;
    }

    // Server is full and player is VIP; attempt to kick a non-VIP player to make room
    Collection<Player> onlinePlayers = bukkitService.getOnlinePlayers();
    if (onlinePlayers.size() < server.getMaxPlayers()) {
        event.allow();
        return false;
    }
    Player nonVipPlayer = generateKickPlayer(onlinePlayers);
    if (nonVipPlayer != null) {
        nonVipPlayer.kickPlayer(messages.retrieveSingle(player, MessageKey.KICK_FOR_VIP));
        event.allow();
        return false;
    } else {
        logger.info("VIP player " + player.getName() + " tried to join, but the server was full");
        event.setKickMessage(messages.retrieveSingle(player, MessageKey.KICK_FULL_SERVER));
        return true;
    }
}
 
Example 6
Source File: RequireLinkModule.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
public void noticePlayerUnlink(Player player) {
    if (!isEnabled()) return;
    if (getBypassNames().contains(player.getName())) return;
    if (checkWhitelist()) {
        boolean whitelisted = Bukkit.getServer().getWhitelistedPlayers().stream().map(OfflinePlayer::getUniqueId).anyMatch(u -> u.equals(player.getUniqueId()));
        if (whitelisted) {
            DiscordSRV.debug("Player " + player.getName() + " is bypassing link requirement, player is whitelisted");
            return;
        }
    }

    DiscordSRV.info("Kicking player " + player.getName() + " for unlinking their accounts");
    player.kickPlayer(ChatColor.translateAlternateColorCodes('&', getUnlinkedKickMessage()));
}
 
Example 7
Source File: GameMap.java    From AnnihilationPro with MIT License 5 votes vote down vote up
public void unLoadMap()
	{
		//World tpworld = Bukkit.getWorlds().size() > 0 ? Bukkit.getWorlds().get(0) : null;
		World tpworld = Game.LobbyMap != null ? Game.LobbyMap.getWorld() : null;
		if(tpworld == null)
			tpworld = Bukkit.getWorlds().size() > 0 ? Bukkit.getWorlds().get(0) : null;
		for(Player p : Bukkit.getOnlinePlayers())
		{
			if(p.getWorld().getName().equals(this.getWorldName()))
			{
				if(tpworld != null)
					p.teleport(tpworld.getSpawnLocation());
				else
					p.kickPlayer("Unloading the world and we dont want you to get trapped or glitched!");
			}
		}
		this.unregisterListeners();

		boolean b = Bukkit.unloadWorld(super.getWorldName(), false);
        Bukkit.getLogger().info("[Annihilation] "+super.getNiceWorldName()+" was unloaded successfully: "+b);
//		try
//		{
//			FileUtils.deleteDirectory(this.mapDirec);
//			FileUtils.copyDirectory(this.tempDirec, this.mapDirec);
//			FileUtils.deleteDirectory(this.tempDirec);
//		}
//		catch (IOException e)
//		{
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}
 
Example 8
Source File: ViaVersionPlugin.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public void onReload() {
    if (Bukkit.getPluginManager().getPlugin("ProtocolLib") != null) {
        getLogger().severe("ViaVersion is already loaded, we're going to kick all the players... because otherwise we'll crash because of ProtocolLib.");
        for (Player player : Bukkit.getOnlinePlayers()) {
            player.kickPlayer(ChatColor.translateAlternateColorCodes('&', conf.getReloadDisconnectMsg()));
        }

    } else {
        getLogger().severe("ViaVersion is already loaded, this should work fine. If you get any console errors, try rebooting.");
    }
}
 
Example 9
Source File: ViaVersionPlugin.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public boolean kickPlayer(UUID uuid, String message) {
    Player player = Bukkit.getPlayer(uuid);
    if (player != null) {
        player.kickPlayer(message);
        return true;
    } else {
        return false;
    }
}
 
Example 10
Source File: WhitelistCommands.java    From CardinalPGM with MIT License 5 votes vote down vote up
@Command(aliases = {"kick"}, desc = "Kicks everyone who is not on the whitelist.", min = 0, max = 0)
@CommandPermissions("cardinal.whitelist.kick")
public static void kick(final CommandContext args, final CommandSender sender) throws CommandException {
    for (Player player : Bukkit.getOnlinePlayers()) {
        if (!player.isWhitelisted() && !player.isOp() && !player.hasPermission("cardinal.whitelist.bypass")) {
            player.kickPlayer(ChatColor.RED + ChatConstant.GENERIC_KICKED_NOT_WHITELISTED.getMessage(ChatUtil.getLocale(player)));
        }
    }
    ChatUtil.getGlobalChannel().sendLocalizedMessage(new UnlocalizedChatMessage(ChatColor.RED + "{0}", ChatConstant.GENERIC_KICKED_NOT_WHITELISTED.asMessage()));
}
 
Example 11
Source File: ModerationCommand.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
@Command(
    aliases = {"kick", "k"},
    usage = "<player> <reason> -s (silent)",
    desc = "Kick a player from the server",
    flags = "s",
    perms = Permissions.KICK)
public void kick(
    CommandSender sender,
    Player target,
    Match match,
    @Text String reason,
    @Switch('s') boolean silent) {
  silent = checkSilent(silent, sender);
  MatchPlayer targetMatchPlayer = match.getPlayer(target);
  if (punish(PunishmentType.KICK, targetMatchPlayer, sender, reason, silent)) {

    // Unfreeze players who are kicked
    FreezeMatchModule fmm = match.getModule(FreezeMatchModule.class);
    if (fmm.isFrozen(targetMatchPlayer)) {
      fmm.setFrozen(sender, targetMatchPlayer, false, false);
    }

    target.kickPlayer(
        formatPunishmentScreen(
            PunishmentType.KICK,
            UsernameFormatUtils.formatStaffName(sender, match),
            reason,
            null));
  }
}
 
Example 12
Source File: BanArgument.java    From Hawk with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean process(CommandSender sender, Command cmd, String label, String[] args) {
    if (args.length < 4)
        return false;
    Player target = Bukkit.getPlayer(args[1]);
    if (target == null) {
        sender.sendMessage(ChatColor.RED + "Unknown player \"" + args[1] + "\"");
        return true;
    }
    if (target.hasPermission(Hawk.BASE_PERMISSION + ".admin")) {
        sender.sendMessage(ChatColor.RED + "You may not ban that player.");
        return true;
    }
    long expireTime = -1;
    long seconds = -1;
    try {
        seconds = Long.parseLong(args[2]);
        expireTime = seconds * 1000 + System.currentTimeMillis();
    } catch (NumberFormatException ignore) {
    }
    if (seconds < 1) {
        sender.sendMessage(ChatColor.RED + "Third argument must be a positive integer.");
        return true;
    }

    List<String> list = (new LinkedList<>(Arrays.asList(args))).subList(3, args.length);
    String reason = ChatColor.translateAlternateColorCodes('&', String.join(" ", list));

    hawk.getBanManager().ban(target.getUniqueId(), expireTime, reason);
    target.kickPlayer(reason);
    sender.sendMessage(ChatColor.GOLD + target.getName() + " has been banned for " + seconds + (seconds == 1 ? " second." : " seconds."));
    return true;
}
 
Example 13
Source File: IllegalPacketEvent.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
public static void process(Player player, String type, String kickMessage, Exception exception) {
    IllegalPacketEvent event = new IllegalPacketEvent(player, type, kickMessage, exception);
    event.callEvent();
    if (event.shouldKick) {
        player.kickPlayer(kickMessage);
    }
    Bukkit.getLogger().severe(player.getName() + "/" + type + ": " + exception.getMessage());
}
 
Example 14
Source File: ConnectionImpl.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void disconnect(String message) {
	Player player = getPlayer();
	if (player != null) {
		player.kickPlayer(message);
		return;
	}
	Object packetListener = networkmanager.getPacketListener();
	if (packetListener instanceof IPacketListener) {
		((IPacketListener) packetListener).disconnect(message);
		return;
	}
	close();
}
 
Example 15
Source File: PlayerDeathListener.java    From UhcCore with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerDeath(PlayerDeathEvent event){
	Player player = event.getEntity();
	GameManager gm = GameManager.getGameManager();
	PlayersManager pm = gm.getPlayersManager();
	MainConfiguration cfg = gm.getConfiguration();
	UhcPlayer uhcPlayer = pm.getUhcPlayer(player);

	if (uhcPlayer.getState() != PlayerState.PLAYING){
		Bukkit.getLogger().warning("[UhcCore] " + player.getName() + " died while already in 'DEAD' mode!");
		player.kickPlayer("Don't cheat!");
		return;
	}

	pm.setLastDeathTime();

	// kill event
	Player killer = player.getKiller();
	if(killer != null){
		UhcPlayer uhcKiller = pm.getUhcPlayer(killer);

		uhcKiller.kills++;

		// Call Bukkit event
		UhcPlayerKillEvent killEvent = new UhcPlayerKillEvent(uhcPlayer, uhcKiller);
		Bukkit.getServer().getPluginManager().callEvent(killEvent);

		if(cfg.getEnableKillEvent()){
			double reward = cfg.getRewardKillEvent();
			List<String> killCommands = cfg.getKillCommands();
			if (reward > 0) {
				VaultManager.addMoney(killer, reward);
				if (!Lang.EVENT_KILL_REWARD.isEmpty()) {
					killer.sendMessage(Lang.EVENT_KILL_REWARD.replace("%money%", "" + reward));
				}
			}
			// If the list is empty, this will never execute
			killCommands.forEach(cmd -> {
				try {
					Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replace("%name%", uhcKiller.getRealName()));
				} catch (CommandException exception){
					Bukkit.getLogger().warning("[UhcCore] Failed to execute kill reward command: " + cmd);
					exception.printStackTrace();
				}
			});
		}
	}

	// Store drops in case player gets re-spawned.
	uhcPlayer.getStoredItems().clear();
	uhcPlayer.getStoredItems().addAll(event.getDrops());

	// eliminations
	ScenarioManager sm = gm.getScenarioManager();
	if (!sm.isActivated(Scenario.SILENTNIGHT) || !((SilentNightListener) sm.getScenarioListener(Scenario.SILENTNIGHT)).isNightMode()) {
		gm.broadcastInfoMessage(Lang.PLAYERS_ELIMINATED.replace("%player%", player.getName()));
	}

	if(cfg.getRegenHeadDropOnPlayerDeath()){
		event.getDrops().add(UhcItems.createRegenHead(uhcPlayer));
	}

	if(cfg.getEnableGoldenHeads()){
		if (cfg.getPlaceHeadOnFence() && !gm.getScenarioManager().isActivated(Scenario.TIMEBOMB)){
			// place head on fence
			Location loc = player.getLocation().clone().add(1,0,0);
			loc.getBlock().setType(UniversalMaterial.OAK_FENCE.getType());
			loc.add(0, 1, 0);
			loc.getBlock().setType(UniversalMaterial.PLAYER_HEAD_BLOCK.getType());

			Skull skull = (Skull) loc.getBlock().getState();
			VersionUtils.getVersionUtils().setSkullOwner(skull, uhcPlayer);
			skull.setRotation(BlockFace.NORTH);
			skull.update();
		}else{
			event.getDrops().add(UhcItems.createGoldenHeadPlayerSkull(player.getName(), player.getUniqueId()));
		}
	}

	if(cfg.getEnableExpDropOnDeath()){
		UhcItems.spawnExtraXp(player.getLocation(), cfg.getExpDropOnDeath());
	}

	uhcPlayer.setState(PlayerState.DEAD);
	pm.strikeLightning(uhcPlayer);
	pm.playSoundPlayerDeath();

	// handle player leaving the server
	boolean canContinueToSpectate = player.hasPermission("uhc-core.spectate.override")
			|| cfg.getCanSpectateAfterDeath();

	if (!canContinueToSpectate) {
		if (cfg.getEnableBungeeSupport()) {
			Bukkit.getScheduler().runTaskAsynchronously(UhcCore.getPlugin(), new TimeBeforeSendBungeeThread(uhcPlayer, cfg.getTimeBeforeSendBungeeAfterDeath()));
		} else {
			player.kickPlayer(Lang.DISPLAY_MESSAGE_PREFIX + " " + Lang.KICK_DEAD);
		}
	}

	pm.checkIfRemainingPlayers();
}
 
Example 16
Source File: PlayerServerChanger.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public ListenableFuture<?> kickPlayer(Player player, String message) {
    // Magic color sequence signals Bungee to disconnect the player
    player.kickPlayer(ChatColor.BLACK.toString() + ChatColor.RED + ChatColor.RESET + message);
    return quitFuture(player);
}
 
Example 17
Source File: PollKick.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void executeAction() {
    Player player = this.server.getPlayerExact(this.player);
    if(player != null) player.kickPlayer(ChatColor.DARK_RED + "You were poll-kicked.");
    this.server.broadcastMessage(ChatColor.RED + this.player + ChatColor.YELLOW + " has been kicked.");
}
 
Example 18
Source File: MatchImpl.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void addPlayer(Player bukkit) {
    try {
        MapUtils.computeIfAbsent(players, bukkit, () -> {
            final MatchUserContext userContext = MapUtils.computeIfAbsent(users, bukkit.getUniqueId(), () -> {
                final User user = userStore.getUser(bukkit);
                logger.fine("Adding user " + user.username());

                // Create the user's Injector
                // Get a new context and enable it
                final MatchUserContext newUserContext = userInjectorFactory.createChildInjector(new MatchUserManifest(user))
                                                                           .getInstance(MatchUserContext.class);
                newUserContext.enableAll();

                callEvent(new MatchUserAddEvent(this, user));

                return newUserContext;
            });

            logger.fine("Adding player " + bukkit);

            // Create the player and initialize facets. At this point, the
            // player has no party and is not in any collections. Facets should
            // be careful not to assume otherwise in their enable/disable
            // methods. If they want the player in a more complete state, they
            // can listen for events that fire later in the join process.
            final MatchPlayer player = userContext.playerInjectorFactory.createChildInjector(new MatchPlayerManifest(bukkit))
                                                                        .getInstance(MatchPlayer.class);
            player.enableAll();

            callEvent(new MatchPlayerAddEvent(this, player));

            // If the player hasn't joined a party by this point, join the default party
            if(!player.hasParty()) {
                setPlayerParty(player, getDefaultParty());
            }

            return player;
        });
    } catch(Exception e) {
        exceptionHandler.handleException(e);
        bukkit.kickPlayer("Internal error");
    }
}
 
Example 19
Source File: ModerationCommand.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
@Command(
    aliases = {"ipban", "banip", "ipb"},
    usage = "<player|ip address> <reason> -s (silent)",
    desc = "IP Ban a player from the server",
    flags = "s",
    perms = Permissions.BAN)
public void ipBan(
    Audience viewer,
    CommandSender sender,
    MatchManager manager,
    String target,
    @Text String reason,
    @Switch('s') boolean silent)
    throws CommandException {
  silent = checkSilent(silent, sender);

  Player targetPlayer = Bukkit.getPlayerExact(target);
  String address = target; // Default address to what was input

  if (targetPlayer != null) {
    // If target is a player, fetch their IP and use that
    address = targetPlayer.getAddress().getAddress().getHostAddress();
  } else if (getBanWithMatchingName(target).isPresent()) {
    address = getBanWithMatchingName(target).get().getAddress();
  }

  // Validate if the IP is a valid IP
  if (InetAddresses.isInetAddress(address)) {
    // Special method for IP Ban
    Bukkit.getBanList(BanList.Type.IP)
        .addBan(
            address,
            reason,
            null,
            TextTranslations.translateLegacy(
                UsernameFormatUtils.formatStaffName(sender, manager.getMatch(sender)), sender));

    int onlineBans = 0;
    // Check all online players to find those with same IP.
    for (Player player : Bukkit.getOnlinePlayers()) {
      MatchPlayer matchPlayer = manager.getPlayer(player);
      if (player.getAddress().getAddress().getHostAddress().equals(address)) {
        // Kick players with same IP
        if (punish(PunishmentType.BAN, matchPlayer, sender, reason, silent)) {

          // Ban username to prevent rejoining
          banPlayer(
              player.getName(),
              reason,
              UsernameFormatUtils.formatStaffName(sender, matchPlayer.getMatch()),
              null);

          player.kickPlayer(
              formatPunishmentScreen(
                  PunishmentType.BAN,
                  UsernameFormatUtils.formatStaffName(sender, manager.getMatch(sender)),
                  reason,
                  null));
          onlineBans++;
        }
      }
    }

    Component formattedTarget = TextComponent.of(target, TextColor.DARK_AQUA);
    if (onlineBans > 0) {
      viewer.sendWarning(
          TranslatableComponent.of(
              "moderation.ipBan.bannedWithAlts",
              formattedTarget,
              TextComponent.of(
                  Integer.toString(
                      targetPlayer == null ? onlineBans : Math.max(0, onlineBans - 1)),
                  TextColor.AQUA)));
    } else {
      viewer.sendMessage(
          TranslatableComponent.of("moderation.ipBan.banned", TextColor.RED, formattedTarget));
    }

  } else {
    viewer.sendMessage(
        TranslatableComponent.of(
            "moderation.ipBan.invalidIP",
            TextColor.GRAY,
            TextComponent.of(address, TextColor.RED, TextDecoration.ITALIC)));
  }
}
 
Example 20
Source File: AbstractLoginListenerPlay.java    From ProtocolSupport with GNU Affero General Public License v3.0 4 votes vote down vote up
protected void joinWorld() {
	if (!ServerPlatform.get().getMiscUtils().isRunning()) {
		disconnect(org.spigotmc.SpigotConfig.restartMessage);
		return;
	}

	UUID uuid = connection.getProfile().getUUID();
	for (Player player : new ArrayList<>(Bukkit.getOnlinePlayers())) {
		if (player.getUniqueId().equals(uuid)) {
			player.kickPlayer("You logged in from another location");
		}
	}

	JoinData joindata = createJoinData();

	connection.setWrappedProfile(joindata.player);

	PlayerSyncLoginEvent syncloginevent = new PlayerSyncLoginEvent(connection, joindata.player);
	Bukkit.getPluginManager().callEvent(syncloginevent);
	if (syncloginevent.isLoginDenied()) {
		disconnect(syncloginevent.getDenyLoginMessage());
		joindata.close();
		return;
	}

	PlayerLoginEvent bukkitevent = new PlayerLoginEvent(
		joindata.player,
		connection.getVirtualHost().toString(),
		networkManager.getAddress().getAddress(),
		networkManager.getRawAddress().getAddress()
	);
	checkBans(bukkitevent, joindata.data);
	Bukkit.getPluginManager().callEvent(bukkitevent);
	if (bukkitevent.getResult() != PlayerLoginEvent.Result.ALLOWED) {
		disconnect(bukkitevent.getKickMessage());
		joindata.close();
		return;
	}

	networkManager.sendPacket(ServerPlatform.get().getPacketFactory().createEmptyCustomPayloadPacket("finishlogin"));

	joinGame(joindata.data);
}