Java Code Examples for org.bukkit.event.player.AsyncPlayerChatEvent#getPlayer()

The following examples show how to use org.bukkit.event.player.AsyncPlayerChatEvent#getPlayer() . 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: CommandEventHandler.java    From GriefDefender with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerChatPost(AsyncPlayerChatEvent event) {
    final Player player = event.getPlayer();
    final Iterator<Player> iterator = event.getRecipients().iterator();

    while (iterator.hasNext()) {
        final Player receiver = iterator.next();
        if (receiver == player) {
            continue;
        }

        final GDPlayerData receiverData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(receiver.getWorld(), receiver.getUniqueId());
        if (receiverData.isRecordingChat()) {
            iterator.remove();
            final String s = String.format(event.getFormat(), event.getPlayer().getDisplayName(), event.getMessage());
            final Component message = LegacyComponentSerializer.legacy().deserialize(s, '&');
            final Component component = TextComponent.builder()
                    .append(TextComponent.builder()
                            .append(message)
                            .hoverEvent(HoverEvent.showText(TextComponent.of(formatter.format(Instant.now()))))
                            .build())
                    .build();
            receiverData.chatLines.add(component);
        }
    }
}
 
Example 2
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 onPlayerChat(AsyncPlayerChatEvent event) {
    if (settings.getProperty(RestrictionSettings.ALLOW_CHAT)) {
        return;
    }

    final Player player = event.getPlayer();
    final boolean mayPlayerSendChat = !listenerService.shouldCancelEvent(player)
        || permissionsManager.hasPermission(player, PlayerStatePermission.ALLOW_CHAT_BEFORE_LOGIN);
    if (mayPlayerSendChat) {
        removeUnauthorizedRecipients(event);
    } else {
        event.setCancelled(true);
        messages.send(player, MessageKey.DENIED_CHAT);
    }
}
 
Example 3
Source File: IndicatorListener.java    From HoloAPI with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onAsyncPlayerChat(AsyncPlayerChatEvent event) {
    if (!event.isCancelled()) {
        final Player p = event.getPlayer();
        if (!HoloAPI.getVanishProvider().isVanished(p)) {
            final String msg = event.getMessage();
            if (event.isAsynchronous()) {
                HoloAPI.getCore().getServer().getScheduler().scheduleSyncDelayedTask(HoloAPI.getCore(), new BukkitRunnable() {
                    @Override
                    public void run() {
                        showChatHologram(p, msg);
                    }
                });
            } else {
                this.showChatHologram(p, msg);
            }
        }
    }
}
 
Example 4
Source File: MentionListener.java    From NyaaUtils with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void AsyncChatEvent(AsyncPlayerChatEvent e) {
    if (!plugin.cfg.mention_enable) return;
    Runnable r = () -> { // In case if we got an asynchronous event
        if (e.getMessage().contains("@")) {
            Player sender = e.getPlayer();
            String raw = e.getMessage();
            String rep = raw.replace("@ ", "@");
            Set<Player> playersNotified = Bukkit.getOnlinePlayers().parallelStream()
                                                .filter(p -> rep.contains("@" + p.getName()))
                                                .collect(Collectors.toSet());
            notify(sender, raw, playersNotified, plugin);
        }
    };
    if (e.isAsynchronous()) {
        Bukkit.getScheduler().runTask(plugin, r);
    } else {
        r.run();
    }
}
 
Example 5
Source File: PlayerListener.java    From WorldGuardExtraFlagsPlugin with MIT License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onAsyncPlayerChatEvent(AsyncPlayerChatEvent event)
{
	Player player = event.getPlayer();
	
	ApplicableRegionSet regions = this.plugin.getWorldGuardCommunicator().getRegionContainer().createQuery().getApplicableRegions(player.getLocation());
	
	String prefix = WorldGuardUtils.queryValue(player, player.getWorld(), regions.getRegions(), Flags.CHAT_PREFIX);
	String suffix = WorldGuardUtils.queryValue(player, player.getWorld(), regions.getRegions(), Flags.CHAT_SUFFIX);

	if (prefix != null)
	{
		event.setFormat(prefix + event.getFormat());
	}
	
	if (suffix != null)
	{
		event.setFormat(event.getFormat() + suffix);
	}
}
 
Example 6
Source File: PlayerListener.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerChat(AsyncPlayerChatEvent event) {
	if (event.isCancelled() && !DiscordBotCore.getInstance().getConfiguration().isForceChat()) {
		return;
	}
	
	Player player = event.getPlayer();
	String permission = DiscordBotCore.getInstance().getConfiguration().getChannels().get("Global").getPermission();
	boolean hasPermission = false;
	
	if (permission == null || permission.trim().equals("") || permission.trim().equals("null")) {
		hasPermission = false;
	} else if (permission.equals("*") || player.hasPermission(permission)) {
		hasPermission = true;
	}
	
	if (!DiscordBotCore.getInstance().getConfiguration().isPlayerChat() || !hasPermission || DiscordBotCore.getInstance().getDatabaseManager().checkDatabase(player.getUniqueId())) {
		return;
	}
	
	Message message = new Message()
			.setChannel(DiscordBotCore.getInstance().getConfiguration().getChannels().get("Global").getChannel())
			.setFormat(DiscordBotCore.getInstance().getConfiguration().getChannelFormat().get("Global"))
			.setName(player.getName())
			.setNick(player.getDisplayName())
			.setServer("Unknown")
			.setMessage(event.getMessage())
			.setDiscord(true)
			.setMinecraft(false)
			.setConsole(false)
			.setRedis(false);
	
	if (player.getServer() != null && player.getServer().getName() != null) {
		message.setServer(player.getServer().getName());
	}
	
	DiscordBotCore.getInstance().getMessageSender().sendMessage(message);
	return;
}
 
Example 7
Source File: ChatListener.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
   public void signPlaced(AsyncPlayerChatEvent event) {
	Player player = event.getPlayer();
	UUID uuid = event.getPlayer().getUniqueId();
	if (chatList.containsKey(uuid)) {
		if (Math.abs((System.currentTimeMillis() - chatList.get(uuid))) < 20000) {
			ChatListener.chatList.remove(uuid);
			event.setCancelled(true);
			String[] settings = toChange.get(uuid).split(":");
			GameMap gMap = GameMap.getMap(settings[0]);
			String setting = settings[1];
			String variable = event.getMessage();
			if (gMap != null && setting.equals("display")) {
				gMap.setDisplayName(variable);
				player.sendMessage(new Messaging.MessageFormatter().setVariable("mapname", gMap.getName()).setVariable("displayname", variable).format("maps.name"));
				new BukkitRunnable() {
					@Override
					public void run() {
						gMap.update();
					}
				}.runTask(SkyWarsReloaded.get());
				SkyWarsReloaded.getIC().show(player, gMap.getArenaKey());
			} else if (gMap != null && setting.equalsIgnoreCase("creator")) {
				gMap.setCreator(variable);
				player.sendMessage(new Messaging.MessageFormatter().setVariable("mapname", gMap.getName()).setVariable("creator", variable).format("maps.creator"));
				new BukkitRunnable() {
					@Override
					public void run() {
						gMap.update();
					}
				}.runTask(SkyWarsReloaded.get());
				SkyWarsReloaded.getIC().show(player, gMap.getArenaKey());
			}
			ChatListener.toChange.remove(uuid);
		} else {
			ChatListener.chatList.remove(uuid);
			ChatListener.toChange.remove(uuid);
		}
	}
}
 
Example 8
Source File: PlayerChat.java    From FunnyGuilds with Apache License 2.0 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onChat(AsyncPlayerChatEvent event) {
    Player player = event.getPlayer();
    User user = User.get(player);
    PluginConfiguration c = FunnyGuilds.getInstance().getPluginConfiguration();
    
    if (user.hasGuild()) {
        Guild guild = user.getGuild();
        String message = event.getMessage();
        if (sendGuildMessage(event, message, c, player, guild)) {
            return;
        }
    }
    
    int points = user.getRank().getPoints();
    String format = event.getFormat();
    
    format = StringUtils.replace(format, "{RANK}", StringUtils.replace(c.chatRank, "{RANK}", String.valueOf(user.getRank().getPosition())));
    format = StringUtils.replace(format, "{POINTS}", c.chatPoints);
    format = StringUtils.replace(format, "{POINTS-FORMAT}", IntegerRange.inRange(points, c.pointsFormat, "POINTS"));
    format = StringUtils.replace(format, "{POINTS}", String.valueOf(points));
    
    if (user.hasGuild()) {
        format = StringUtils.replace(format, "{TAG}", StringUtils.replace(c.chatGuild, "{TAG}", user.getGuild().getTag()));
        format = StringUtils.replace(format, "{POS}", StringUtils.replace(c.chatPosition, "{POS}", getPositionString(user, c)));
    } else {
        format = StringUtils.replace(format, "{TAG}", "");
        format = StringUtils.replace(format, "{POS}", "");
    }
    
    event.setFormat(format);
}
 
Example 9
Source File: ListenerChat.java    From CombatLogX with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority=EventPriority.LOW, ignoreCancelled=true)
public void onChat(AsyncPlayerChatEvent e) {
    FileConfiguration config = this.expansion.getConfig("cheat-prevention.yml");
    if(!config.getBoolean("disable-chat")) return;

    Player player = e.getPlayer();
    ICombatManager combatManager = this.plugin.getCombatManager();
    if(!combatManager.isInCombat(player)) return;

    e.setCancelled(true);
    String message = this.plugin.getLanguageMessageColoredWithPrefix("cheat-prevention.no-chat");
    this.plugin.sendMessage(player, message);
}
 
Example 10
Source File: ChatEvent.java    From MCAuthenticator with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerChat(AsyncPlayerChatEvent event) {
    Player player = event.getPlayer();
    User user = instance.getCache().get(player.getUniqueId());

    if (user == null) {
        event.getRecipients().clear();
        return;
    }

    if (user.authenticated()) {
        Iterator<Player> recipients = event.getRecipients().iterator();
        while(recipients.hasNext()) {
            User u = instance.getCache().get(recipients.next().getUniqueId());
            if(u != null && !u.authenticated()) recipients.remove();
        }
        return;
    }

    if (instance.getC().getBungeePluginChannel() == null) {
        boolean authenticate = false;
        try {
            authenticate = user.authenticate(event.getMessage(), player);
        } catch (Exception e) {
            instance.getC().sendDirect(player, "&cThere was a fatal exception when trying to authenticate you!");
        }

        if (authenticate) {
            instance.getC().send(player, instance.getC().message("authenticated"));
        } else {
            instance.getC().send(player, instance.getC().message("authFailed"));
        }
    }

    event.setCancelled(true);
}
 
Example 11
Source File: SimpleInterceptor.java    From BetonQuest with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onChat(AsyncPlayerChatEvent event) {
    // store all messages so they can be displayed to the player
    // once the conversation is finished
    if (event.getPlayer() != player && event.getRecipients().contains(player)) {
        event.getRecipients().remove(player);
        addMessage(String.format(event.getFormat(), event.getPlayer().getDisplayName(), event.getMessage()));
    }
}
 
Example 12
Source File: ChatListener.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void actOnChatEvent(AsyncPlayerChatEvent event) {
    long time = System.currentTimeMillis();
    Player player = event.getPlayer();
    UUID uuid = player.getUniqueId();
    String displayName = player.getDisplayName();

    dbSystem.getDatabase().executeTransaction(new NicknameStoreTransaction(
            uuid, new Nickname(displayName, time, serverInfo.getServerUUID()),
            (playerUUID, name) -> nicknameCache.getDisplayName(playerUUID).map(name::equals).orElse(false)
    ));
}
 
Example 13
Source File: ChatEvent.java    From StackMob-3 with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event){
    Player player = event.getPlayer();
    if(StackTools.hasValidMetadata(player, GlobalValues.WAITING_FOR_INPUT)){
        if(!(player.getMetadata(GlobalValues.WAITING_FOR_INPUT).get(0).asBoolean())){
            return;
        }
        event.setCancelled(true);
        sm.getStickTools().updateStack(player, event.getMessage());
    }
}
 
Example 14
Source File: PlayerChatListener.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority=EventPriority.HIGH)
public void onPlayerChat(AsyncPlayerChatEvent e){
	Player player = e.getPlayer();
	GameManager gm = GameManager.getGameManager();
	MainConfiguration cfg = gm.getConfiguration();

	if (e.isCancelled()){
	    return;
       }

	UhcPlayer uhcPlayer = gm.getPlayersManager().getUhcPlayer(player);

	// Spec chat
       if(!cfg.getCanSendMessagesAfterDeath() && uhcPlayer.getState() == PlayerState.DEAD){
       	// check if has override permissions
		if (player.hasPermission("uhc-core.chat.override")) return;

		// Send message in spec chat.
		String message = Lang.DISPLAY_SPECTATOR_CHAT
				.replace("%player%", player.getDisplayName())
				.replace("%message%", e.getMessage());

		gm.getPlayersManager().getOnlineSpectatingPlayers().forEach(p -> p.sendMessage(message));
           e.setCancelled(true);
           return;
       }

       // Team chat
	if (
			uhcPlayer.getState() == PlayerState.PLAYING && isTeamMessage(cfg, e, uhcPlayer)
	){
		e.setCancelled(true);
		uhcPlayer.getTeam().sendChatMessageToTeamMembers(uhcPlayer, e.getMessage());
       }

}
 
Example 15
Source File: CMListener.java    From ChatMenuAPI with GNU Lesser General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent e)
{
	Player player = e.getPlayer();
	BiFunction<Player, String, Boolean> listener = chatListeners.get(player);
	if(listener != null)
	{
		e.setCancelled(true);
		if(listener.apply(player, e.getMessage()))
			chatListeners.remove(player);
	}
}
 
Example 16
Source File: CommandEventHandler.java    From GriefDefender with MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerChatInput(AsyncPlayerChatEvent event) {
    final Player player = event.getPlayer();
    final GDPlayerData playerData = this.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    // check for command input
    if (playerData.isWaitingForInput()) {
        playerData.commandInput = event.getMessage();
        playerData.commandConsumer.accept(player);
        event.setCancelled(true);
    }
}
 
Example 17
Source File: ChatListener.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
private void teamChat(final AsyncPlayerChatEvent event, String message) {
    Player player = event.getPlayer();
    UUID playerUUID = player.getUniqueId();
    //Bukkit.getLogger().info("DEBUG: post: " + message);
    // Is team chat on for this player
    // Find out if this player is in a team (should be if team chat is on)
    // TODO: remove when player resets or leaves team
    if (plugin.getPlayers().inTeam(playerUUID)) {
        List<UUID> teamMembers = plugin.getPlayers().getMembers(player.getUniqueId());
        // Tell only the team members if they are online
        boolean onLine = false;
        if (Settings.chatIslandPlayer.isEmpty()) {
            message = plugin.myLocale(playerUUID).teamChatPrefix + message;
        } else {
            message = plugin.myLocale(playerUUID).teamChatPrefix.replace(Settings.chatIslandPlayer,player.getDisplayName()) + message;
        }
        for (UUID teamMember : teamMembers) {
            Player teamPlayer = plugin.getServer().getPlayer(teamMember);
            if (teamPlayer != null) {
                Util.sendMessage(teamPlayer, message);
                if (!teamMember.equals(playerUUID)) {
                    onLine = true;
                }
            }
        }
        // Spy function
        if (onLine) {
            for (Player onlinePlayer: plugin.getServer().getOnlinePlayers()) {
                if (spies.contains(onlinePlayer.getUniqueId()) && onlinePlayer.hasPermission(Settings.PERMPREFIX + "mod.spy")) {
                    Util.sendMessage(onlinePlayer, ChatColor.RED + "[TCSpy] " + ChatColor.WHITE + message);
                }
            }
            //Log teamchat
            if(Settings.logTeamChat) plugin.getLogger().info(ChatColor.stripColor(message));
        }
        if (!onLine) {
            Util.sendMessage(player, ChatColor.RED + plugin.myLocale(playerUUID).teamChatNoTeamAround);
            Util.sendMessage(player, ChatColor.RED + plugin.myLocale(playerUUID).teamChatStatusOff);
            teamChatUsers.remove(playerUUID);
        }
    } else {
        Util.sendMessage(player, ChatColor.RED + plugin.myLocale(playerUUID).teamChatNoTeamAround);
        Util.sendMessage(player, ChatColor.RED + plugin.myLocale(playerUUID).teamChatStatusOff);
        // Not in a team any more so delete
        teamChatUsers.remove(playerUUID);
    }
}
 
Example 18
Source File: ChatPlaceholder.java    From uSkyBlock with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler
public void onChatEvent(AsyncPlayerChatEvent e) {
    Player player = e.getPlayer();
    e.setFormat(PlaceholderHandler.replacePlaceholders(player, e.getFormat()));
    e.setMessage(PlaceholderHandler.replacePlaceholders(player, e.getMessage()));
}
 
Example 19
Source File: ChatEventListener.java    From ChatItem with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)  //We need to have lowest priority in order to get to the event before DeluxeChat or other plugins do
public void onChat(final AsyncPlayerChatEvent e) {
    if(e.getMessage().indexOf(SEPARATOR)!=-1){  //If the BELL character is found, we have to remove it
        String msg = e.getMessage().replace(Character.toString(SEPARATOR), "");
        e.setMessage(msg);
    }
    boolean found = false;

    for (String rep : c.PLACEHOLDERS)
        if (e.getMessage().contains(rep)) {
            found = true;
            break;
        }

    if (!found) {
        return;
    }

    Player p = e.getPlayer();

    if (!p.hasPermission("chatitem.use")) {
        if(!c.LET_MESSAGE_THROUGH) {
            e.setCancelled(true);
        }
        if(!c.NO_PERMISSION_MESSAGE.isEmpty() && c.SHOW_NO_PERM_NORMAL){
            p.sendMessage(c.NO_PERMISSION_MESSAGE);
        }
        return;
    }
    if (p.getItemInHand().getType().equals(Material.AIR)) {
        if (c.DENY_IF_NO_ITEM) {
            e.setCancelled(true);
            if (!c.DENY_MESSAGE.isEmpty())
                e.getPlayer().sendMessage(c.DENY_MESSAGE);
            return;
        }
        if(c.HAND_DISABLED) {
            return;
        }
    }
    if(c.COOLDOWN > 0 && !p.hasPermission("chatitem.ignore-cooldown")){
        if(COOLDOWNS.containsKey(p.getName())){
            long start = COOLDOWNS.get(p.getName());
            long current = System.currentTimeMillis()/1000;
            long elapsed = current - start;
            if(elapsed >= c.COOLDOWN){
                COOLDOWNS.remove(p.getName());
            }else{
                if(!c.LET_MESSAGE_THROUGH) {
                    e.setCancelled(true);
                }
                if(!c.COOLDOWN_MESSAGE.isEmpty()){
                    long left = (start + c.COOLDOWN) - current;
                    p.sendMessage(c.COOLDOWN_MESSAGE.replace(LEFT, calculateTime(left)));
                }
                return;
            }
        }
    }
    String s = e.getMessage();
    for(String placeholder : c.PLACEHOLDERS){
        s = s.replace(placeholder, c.PLACEHOLDERS.get(0));
    }
    int occurrences = countOccurrences(c.PLACEHOLDERS.get(0), s);

    if(occurrences>c.LIMIT){
        e.setCancelled(true);
        if(c.LIMIT_MESSAGE.isEmpty()){
            return;
        }
        e.getPlayer().sendMessage(c.LIMIT_MESSAGE);
        return;
    }

    String oldmsg = e.getMessage();
    StringBuilder sb = new StringBuilder(oldmsg);
    sb.append(SEPARATOR).append(e.getPlayer().getName());
    e.setMessage(sb.toString());
    Bukkit.getConsoleSender().sendMessage(String.format(e.getFormat(), e.getPlayer().getDisplayName(), oldmsg));
    if(!p.hasPermission("chatitem.ignore-cooldown")) {
        COOLDOWNS.put(p.getName(), System.currentTimeMillis() / 1000);
    }
}
 
Example 20
Source File: AsyncPlayerChat.java    From StaffPlus with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onChat(AsyncPlayerChatEvent event)
{
	Player player = event.getPlayer();
	String message = event.getMessage();
	
	if(shouldCancel(player, message))
	{
		event.setCancelled(true);
		return;
	}
	
	List<User> mentioned = getMentioned(message);
	
	if(!mentioned.isEmpty())
	{
		for(User user : mentioned)
		{
			alertCoordinator.onMention(user, player.getName());
		}
	}
	
	if(options.chatBlacklistEnabled && options.chatEnabled)
	{
		BlacklistFactory blacklistFactory = new BlacklistFactory(message);
		
		if(blacklistFactory.runCheck().hasChanged()&& !permission.has(player, options.permissionBlacklist))
		{
			event.setMessage(blacklistFactory.getResult());
			
			if(options.chatBlacklistHoverable)
			{
				Set<Player> staffPlayers = new HashSet<Player>();
				
				for(Player p : Bukkit.getOnlinePlayers())
				{
					if(permission.has(p, options.permissionBlacklist))
					{
						event.getRecipients().remove(p);
						staffPlayers.add(p);
					}
				}
				
				versionProtocol.sendHoverableJsonMessage(staffPlayers, messages.blacklistChatFormat.replace("%player%", player.getName()).replace("%message%", blacklistFactory.getResult()), message);
			}
		}
	}
}