Java Code Examples for org.spongepowered.api.entity.living.player.Player#sendMessage()

The following examples show how to use org.spongepowered.api.entity.living.player.Player#sendMessage() . 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: UCChannel.java    From UltimateChat with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Send a message from a channel as console.
 *
 * @param sender  {@code ConsoleSource} - Console sender.
 * @param message {@code Text} - Message to send.
 * @param direct  {@code boolean} - Send message direct to players on channel.
 */
public void sendMessage(ConsoleSource sender, Text message, boolean direct) {
    if (direct) {
        for (Player p : Sponge.getServer().getOnlinePlayers()) {
            UCChannel chp = UChat.get().getPlayerChannel(p);
            if (UChat.get().getPerms().channelReadPerm(p, this) && !this.isIgnoring(p.getName()) && (!this.neeFocus() || chp.equals(this))) {
                UChat.get().getLogger().timings(timingType.START, "UCChannel#sendMessage()|Direct Message");
                p.sendMessage(message);
            }
        }
        sender.sendMessage(message);
    } else {
        UChat.get().getLogger().timings(timingType.START, "UCChannel#sendMessage()|Fire MessageChannelEvent");
        UCMessages.sendFancyMessage(new String[0], message, this, sender, null);
    }
}
 
Example 2
Source File: BlockprotectionListener.java    From UltimateCore with MIT License 6 votes vote down vote up
@Listener
public void onInteractSecondary(InteractBlockEvent.Secondary event, @First Player p) {
    ModuleConfig config = Modules.BLOCKPROTECTION.get().getConfig().get();
    if (!config.get().getNode("protections", "allow-interact-secondary").getBoolean()) return;
    if (!event.getTargetBlock().getLocation().isPresent()) return;

    for (Protection prot : GlobalData.get(BlockprotectionKeys.PROTECTIONS).get()) {
        if (prot.getPlayers().contains(p.getUniqueId())) continue;
        if (!prot.getLocations().contains(event.getTargetBlock().getLocation().get())) continue;

        //Check if it should be cancelled
        if (prot.getLocktype().shouldBeCancelled()) {
            event.setCancelled(true);
            p.sendMessage(prot.getLocktype().getErrorMessage(p, prot));
        }
    }
}
 
Example 3
Source File: ClaimCommand.java    From EagleFactions with MIT License 6 votes vote down vote up
private CommandResult preformAdminClaim(final Player player, final Faction faction, final Vector3i chunk) throws CommandException
{
    final World world = player.getWorld();
    final boolean safeZoneWorld = this.protectionConfig.getSafeZoneWorldNames().contains(world.getName());
    final boolean warZoneWorld = this.protectionConfig.getWarZoneWorldNames().contains(world.getName());

    //Even admin cannot claim territories in safezone nor warzone world.
    if (safeZoneWorld || warZoneWorld)
        throw new CommandException(PluginInfo.ERROR_PREFIX.concat(Text.of(TextColors.RED, Messages.YOU_CANNOT_CLAIM_TERRITORIES_IN_THIS_WORLD)));

    boolean isCancelled = EventRunner.runFactionClaimEvent(player, faction, player.getWorld(), chunk);
    if (isCancelled)
        return CommandResult.empty();

    super.getPlugin().getFactionLogic().addClaim(faction, new Claim(player.getWorld().getUniqueId(), chunk));
    player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, Messages.LAND + " ", TextColors.GOLD, chunk.toString(), TextColors.WHITE, " " + Messages.HAS_BEEN_SUCCESSFULLY + " ", TextColors.GOLD, Messages.CLAIMED, TextColors.WHITE, "!"));
    return CommandResult.success();
}
 
Example 4
Source File: PlayerDamageListener.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Listener
public void onPlayerDamaged(DamageEntityEvent event)
{
	if (event.getTargetEntity() instanceof Player)
	{
		Player player = (Player) event.getTargetEntity();

		if (Utils.isTeleportCooldownEnabled() && EssentialCmds.teleportingPlayers.contains(player.getUniqueId()))
		{
			EssentialCmds.teleportingPlayers.remove(player.getUniqueId());
			player.sendMessage(Text.of(TextColors.RED, "Teleportation canceled due to damage."));
		}

		if (EssentialCmds.godPlayers.contains(player.getUniqueId()))
		{
			event.setBaseDamage(0);
			event.setCancelled(true);
		}
	}
}
 
Example 5
Source File: EagleFactionsPlugin.java    From EagleFactions with MIT License 5 votes vote down vote up
@Listener
public void onReload(final GameReloadEvent event)
{
    this.configuration.reloadConfiguration();
    this.storageManager.reloadStorage();

    if(event.getSource() instanceof Player)
    {
        Player player = (Player)event.getSource();
        player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, Messages.CONFIG_HAS_BEEN_RELOADED));
    }
}
 
Example 6
Source File: UnclaimAllCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(final CommandSource source, final CommandContext context) throws CommandException
{
    if (!(source instanceof Player))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.ONLY_IN_GAME_PLAYERS_CAN_USE_THIS_COMMAND));

    final Player player = (Player)source;
    final Optional<Faction> optionalPlayerFaction = super.getPlugin().getFactionLogic().getFactionByPlayerUUID(player.getUniqueId());

    //Check if player is in the faction.
    if (!optionalPlayerFaction.isPresent())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_IN_FACTION_IN_ORDER_TO_USE_THIS_COMMAND));

    final Faction playerFaction = optionalPlayerFaction.get();
    if (!playerFaction.getLeader().equals(player.getUniqueId()) && !playerFaction.getOfficers().contains(player.getUniqueId()) && !super.getPlugin().getPlayerManager().hasAdminMode(player))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_THE_FACTIONS_LEADER_OR_OFFICER_TO_DO_THIS));

    final boolean isCancelled = EventRunner.runFactionUnclaimEvent(player, playerFaction, player.getWorld(), null);
    if (isCancelled)
        return CommandResult.success();

    if(!this.factionsConfig.canPlaceHomeOutsideFactionClaim() && playerFaction.getHome() != null)
    {
        super.getPlugin().getFactionLogic().setHome(playerFaction, null);
    }

    final Faction faction = super.getPlugin().getFactionLogic().getFactionByPlayerUUID(player.getUniqueId()).get();
    super.getPlugin().getFactionLogic().removeAllClaims(faction);
    player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.GREEN, Messages.SUCCESSFULLY_REMOVED_ALL_CLAIMS));
    return CommandResult.success();
}
 
Example 7
Source File: TruceCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
private void acceptInvite(final Player player, final Faction playerFaction, final Faction senderFaction)
{
	super.getPlugin().getFactionLogic().addTruce(playerFaction.getName(), senderFaction.getName());
	player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, MessageLoader.parseMessage(Messages.YOU_HAVE_ACCEPTED_AN_INVITATION_FROM_FACTION, TextColors.GREEN, ImmutableMap.of(Placeholders.FACTION_NAME, Text.of(TextColors.GOLD, senderFaction.getName())))));

	final Optional<Player> optionalSenderFactionLeader = super.getPlugin().getPlayerManager().getPlayer(senderFaction.getLeader());
	optionalSenderFactionLeader.ifPresent(x-> optionalSenderFactionLeader.get().sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, MessageLoader.parseMessage(Messages.FACTION_ACCEPTED_YOUR_INVITE_TO_THE_TRUCE, TextColors.GREEN, ImmutableMap.of(Placeholders.FACTION_NAME, Text.of(TextColors.GOLD, playerFaction.getName()))))));
	senderFaction.getOfficers().forEach(x-> super.getPlugin().getPlayerManager().getPlayer(x).ifPresent(y-> Text.of(PluginInfo.PLUGIN_PREFIX, MessageLoader.parseMessage(Messages.FACTION_ACCEPTED_YOUR_INVITE_TO_THE_TRUCE, TextColors.GREEN, ImmutableMap.of(Placeholders.FACTION_NAME, Text.of(TextColors.GOLD, playerFaction.getName()))))));
}
 
Example 8
Source File: ServerlistListener.java    From UltimateCore with MIT License 5 votes vote down vote up
@Listener(order = Order.LATE)
public void onJoin(ClientConnectionEvent.Join event) {
    try {
        Player p = event.getTargetEntity();
        ModuleConfig config = Modules.SERVERLIST.get().getConfig().get();
        //Join motd
        if (config.get().getNode("joinmessage", "enable").getBoolean()) {
            List<String> joinmsgs = config.get().getNode("joinmessage", "joinmessages").getList(TypeToken.of(String.class));
            Text joinmsg = VariableUtil.replaceVariables(Messages.toText(joinmsgs.get(random.nextInt(joinmsgs.size()))), p);
            p.sendMessage(joinmsg);
        }
    } catch (ObjectMappingException e) {
        ErrorLogger.log(e, "Failed to construct join message.");
    }
}
 
Example 9
Source File: TagCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(final CommandSource source, final CommandContext context) throws CommandException
{
    final String newFactionTag = context.requireOne("tag");

    if (!(source instanceof Player))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.ONLY_IN_GAME_PLAYERS_CAN_USE_THIS_COMMAND));

    final Player player = (Player) source;
    final Optional<Faction> optionalPlayerFaction = getPlugin().getFactionLogic().getFactionByPlayerUUID(player.getUniqueId());
    if (!optionalPlayerFaction.isPresent())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_IN_FACTION_IN_ORDER_TO_USE_THIS_COMMAND));

    //Check if player is leader
    if (!optionalPlayerFaction.get().getLeader().equals(player.getUniqueId()))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_THE_FACTIONS_LEADER_TO_DO_THIS));

    //Check if faction with such tag already exists
    if(super.getPlugin().getFactionLogic().getFactionsTags().stream().anyMatch(x -> x.equalsIgnoreCase(newFactionTag)))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.PROVIDED_FACTION_TAG_IS_ALREADY_TAKEN));

    //Check tag length
    if(newFactionTag.length() > this.factionsConfig.getMaxTagLength())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.PROVIDED_FACTION_TAG_IS_TOO_LONG + " (" + Messages.MAX + " " + this.factionsConfig.getMaxTagLength() + " " + Messages.CHARS + ")"));
    else if(newFactionTag.length() < this.factionsConfig.getMinTagLength())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.PROVIDED_FACTION_TAG_IS_TOO_SHORT + " (" + Messages.MIN + " " + this.factionsConfig.getMinTagLength() + " " + Messages.CHARS + ")"));

    //Change tag function
    super.getPlugin().getFactionLogic().changeTag(optionalPlayerFaction.get(), newFactionTag);
    player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, MessageLoader.parseMessage(Messages.FACTION_TAG_HAS_BEEN_SUCCESSFULLY_CHANGED_TO, TextColors.GREEN, Collections.singletonMap(Placeholders.FACTION_TAG, Text.of(TextColors.GOLD, newFactionTag)))));
    return CommandResult.success();
}
 
Example 10
Source File: MailReadExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
@Override
public void executeAsync(CommandSource src, CommandContext ctx)
{
	int number = ctx.<Integer> getOne("mail no").get();
	if (src instanceof Player)
	{
		Player player = (Player) src;
		List<Mail> mail = Utils.getMail(player);

		if (mail.isEmpty())
		{
			player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You have no new mail!"));
			return;
		}

		try
		{
			Mail m = mail.get(number);
			Utils.removeMail(m);
			player.sendMessage(Text.of(TextColors.GOLD, "[Mail]: Message from ", TextColors.WHITE, m.getSenderName() + ": ", TextColors.GRAY, m.getMessage()));
		}
		catch (Exception e)
		{
			player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "That mail does not exist!"));
		}

	}
	else if (src instanceof ConsoleSource)
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Must be an in-game player to use /readmail!"));
	}
	else if (src instanceof CommandBlockSource)
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Must be an in-game player to use /readmail!"));
	}
}
 
Example 11
Source File: MotdCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(final CommandSource source, final CommandContext context) throws CommandException
{
    final String motd = context.requireOne("motd");

    if (!(source instanceof Player))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.ONLY_IN_GAME_PLAYERS_CAN_USE_THIS_COMMAND));

    final Player player = (Player) source;
    final Optional<Faction> optionalPlayerFaction = super.getPlugin().getFactionLogic().getFactionByPlayerUUID(player.getUniqueId());
    if (!optionalPlayerFaction.isPresent())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_IN_FACTION_IN_ORDER_TO_USE_THIS_COMMAND));

    //Check if player is leader
    if (!optionalPlayerFaction.get().getLeader().equals(player.getUniqueId()) && !optionalPlayerFaction.get().getOfficers().contains(player.getUniqueId()))
    {
        source.sendMessage(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_THE_FACTIONS_LEADER_OR_OFFICER_TO_DO_THIS));
        return CommandResult.success();
    }

    //Check motd length
    if(motd.length() > 255)
    {
        player.sendMessage(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, "Motd is too long " + " (" + Messages.MAX + " " + 255 + " " + Messages.CHARS + ")"));
        return CommandResult.success();
    }

    super.getPlugin().getFactionLogic().setMessageOfTheDay(optionalPlayerFaction.get(), motd);
    player.sendMessage(PluginInfo.PLUGIN_PREFIX.concat(Text.of(TextColors.GREEN, Messages.FACTION_MESSAGE_OF_THE_DAY_HAS_BEEN_UPDATED)));
    return CommandResult.success();
}
 
Example 12
Source File: AutoClaimCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource source, CommandContext context) throws CommandException
{
    if (!(source instanceof Player))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.ONLY_IN_GAME_PLAYERS_CAN_USE_THIS_COMMAND));

    final Player player = (Player)source;
    final Optional<Faction> optionalPlayerFaction = getPlugin().getFactionLogic().getFactionByPlayerUUID(player.getUniqueId());

    if (!optionalPlayerFaction.isPresent())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_IN_FACTION_IN_ORDER_TO_USE_THIS_COMMAND));

    final Faction playerFaction = optionalPlayerFaction.get();
    if (!playerFaction.getLeader().equals(player.getUniqueId()) && !playerFaction.getOfficers().contains(player.getUniqueId()) && !super.getPlugin().getPlayerManager().hasAdminMode(player))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_THE_FACTIONS_LEADER_OR_OFFICER_TO_DO_THIS));

    if(EagleFactionsPlugin.AUTO_CLAIM_LIST.contains(player.getUniqueId()))
    {
        EagleFactionsPlugin.AUTO_CLAIM_LIST.remove(player.getUniqueId());
        player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.GREEN, Messages.AUTO_CLAIM_HAS_BEEN_TURNED_OFF));
    }
    else
    {
        EagleFactionsPlugin.AUTO_CLAIM_LIST.add(player.getUniqueId());
        player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.GREEN, Messages.AUTO_CLAIM_HAS_BEEN_TURNED_ON));
    }

    return CommandResult.success();
}
 
Example 13
Source File: SocialSpyExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
@Override
public void executeAsync(CommandSource src, CommandContext ctx)
{
	if (src instanceof Player)
	{
		Player player = (Player) src;

		if (EssentialCmds.socialSpies.contains(player.getUniqueId()))
		{
			EssentialCmds.socialSpies.remove(player.getUniqueId());
			player.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.RED, "Toggled social spy off!"));
		}
		else
		{
			EssentialCmds.socialSpies.add(player.getUniqueId());
			player.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.GOLD, "Toggled social spy on!"));
		}
	}
	else if (src instanceof ConsoleSource)
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Must be an in-game player to use /socialspy!"));
	}
	else if (src instanceof CommandBlockSource)
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Must be an in-game player to use /socialspy!"));
	}
}
 
Example 14
Source File: JoinCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
private CommandResult joinFactionAndNotify(final Player player, final Faction faction)
{
    final boolean isCancelled = EventRunner.runFactionJoinEvent(player, faction);
    if (isCancelled)
        return CommandResult.success();

    super.getPlugin().getFactionLogic().joinFaction(player.getUniqueId(), faction.getName());
    EagleFactionsPlugin.INVITE_LIST.remove(new Invite(faction.getName(), player.getUniqueId()));
    player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, MessageLoader.parseMessage(Messages.SUCCESSFULLY_JOINED_FACTION, TextColors.GREEN, Collections.singletonMap(Placeholders.FACTION_NAME, Text.of(TextColors.GOLD, faction.getName())))));
    return CommandResult.success();
}
 
Example 15
Source File: PlayerMoveListener.java    From Nations with MIT License 4 votes vote down vote up
@Listener
public void onPlayerMove(MoveEntityEvent event, @First Player player)
{
	if (event.getFromTransform().getLocation().getBlockX() == event.getToTransform().getLocation().getBlockX() && 
			event.getFromTransform().getLocation().getBlockZ() == event.getToTransform().getLocation().getBlockZ())
	{
		return;
	}
	if (!ConfigHandler.getNode("worlds").getNode(event.getToTransform().getExtent().getName()).getNode("enabled").getBoolean())
	{
		return;
	}

	Location<World> loc = event.getToTransform().getLocation();
	Nation nation = DataHandler.getNation(loc);
	Nation lastNationWalkedOn = DataHandler.getLastNationWalkedOn(player.getUniqueId());
	Zone zone = null;
	if (nation != null)
	{
		zone = nation.getZone(loc);
	}
	Zone lastZoneWalkedOn = DataHandler.getLastZoneWalkedOn(player.getUniqueId());
	if ((nation == null && lastNationWalkedOn == null) || (nation != null && lastNationWalkedOn != null && nation.getUUID().equals(lastNationWalkedOn.getUUID())))
	{
		if ((zone == null && lastZoneWalkedOn == null) || (zone != null && lastZoneWalkedOn != null && zone.getUUID().equals(lastZoneWalkedOn.getUUID())))
		{
			return;
		}
	}
	DataHandler.setLastNationWalkedOn(player.getUniqueId(), nation);
	DataHandler.setLastZoneWalkedOn(player.getUniqueId(), zone);

	String toast;

	if (nation == null) {
		toast = ConfigHandler.getNode("toast", "wild").getString();
	} else {
		toast = (zone == null ? ConfigHandler.getNode("toast", "nation").getString() : ConfigHandler.getNode("toast", "zone").getString());
	}
	
	String formatPresident = "";
	
	if (nation != null && !nation.isAdmin()) {
		formatPresident = ConfigHandler.getNode("toast", "formatPresident").getString()
				.replaceAll("\\{TITLE\\}", DataHandler.getCitizenTitle(nation.getPresident()))
				.replaceAll("\\{NAME\\}", DataHandler.getPlayerName(nation.getPresident()));
	}
	
	String formatZoneName = "";
	String formatZoneOwner = "";
	String formatZonePrice = "";
	
	if (zone != null) {
		if (zone.isNamed())
			formatZoneName = ConfigHandler.getNode("toast", "formatZoneName").getString().replaceAll("\\{ARG\\}", zone.getName()) + " ";
		if (zone.isOwned())
			formatZoneOwner = ConfigHandler.getNode("toast", "formatZoneOwner").getString().replaceAll("\\{ARG\\}", DataHandler.getPlayerName(zone.getOwner())) + " ";
		if (zone.isForSale())
			formatZonePrice = ConfigHandler.getNode("toast", "formatZonePrice").getString().replaceAll("\\{ARG\\}", Utils.formatPricePlain(zone.getPrice())) + " ";
	}
	
	String formatPvp;
	
	if (DataHandler.getFlag("pvp", loc)) {
		formatPvp = ConfigHandler.getNode("toast", "formatPvp").getString().replaceAll("\\{ARG\\}", LanguageHandler.TOAST_PVP);
	} else {
		formatPvp = ConfigHandler.getNode("toast", "formatNoPvp").getString().replaceAll("\\{ARG\\}", LanguageHandler.TOAST_NOPVP);
	}
	
	if (nation != null) {
		toast = toast.replaceAll("\\{NATION\\}", nation.getName());
	} else {
		toast = toast.replaceAll("\\{WILD\\}", LanguageHandler.TOAST_WILDNAME);
	}


	Text finalToast = TextSerializers.FORMATTING_CODE.deserialize(toast
			.replaceAll("\\{FORMATPRESIDENT\\}", formatPresident)
			.replaceAll("\\{FORMATZONENAME\\}", formatZoneName)
			.replaceAll("\\{FORMATZONEOWNER\\}", formatZoneOwner)
			.replaceAll("\\{FORMATZONEPRICE\\}", formatZonePrice)
			.replaceAll("\\{FORMATPVP\\}", formatPvp));

	player.sendMessage(ChatTypes.ACTION_BAR, finalToast);
	MessageChannel.TO_CONSOLE.send(Text.of(player.getName(), " entered area ", finalToast));
}
 
Example 16
Source File: CommandHelper.java    From GriefPrevention with MIT License 4 votes vote down vote up
private static Consumer<CommandSource> createBuyConsumerConfirmed(CommandSource src, Claim claim) {
    return confirm -> {
        final Player player = (Player) src;
        final Player ownerPlayer = Sponge.getServer().getPlayer(claim.getOwnerUniqueId()).orElse(null);
        final Account ownerAccount = GriefPreventionPlugin.instance.economyService.get().getOrCreateAccount(claim.getOwnerUniqueId()).orElse(null);
        if (ownerAccount == null) {
            src.sendMessage(Text.of(TextColors.RED, "Buy cancelled! Could not locate an economy account for owner."));
            return;
        }

        final ClaimResult result = claim.transferOwner(player.getUniqueId());
        if (!result.successful()) {
            final Text defaultMessage = Text.of(TextColors.RED, "Buy cancelled! Could not transfer owner. Result was ", result.getResultType().name());
            src.sendMessage(result.getMessage().orElse(defaultMessage));
            return;
        }

        try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
            final Currency defaultCurrency = GriefPreventionPlugin.instance.economyService.get().getDefaultCurrency();
            final double salePrice = claim.getEconomyData().getSalePrice();
            Sponge.getCauseStackManager().pushCause(src);
            final TransactionResult ownerResult = ownerAccount.deposit(defaultCurrency, BigDecimal.valueOf(salePrice), Sponge.getCauseStackManager().getCurrentCause());
            Account playerAccount = GriefPreventionPlugin.instance.economyService.get().getOrCreateAccount(player.getUniqueId()).orElse(null);
            final TransactionResult
                transactionResult =
                playerAccount.withdraw(defaultCurrency, BigDecimal.valueOf(salePrice), Sponge.getCauseStackManager().getCurrentCause());
            final Text message = GriefPreventionPlugin.instance.messageData.economyClaimBuyConfirmed
                .apply(ImmutableMap.of(
                    "sale_price", salePrice)).build();
            final Text saleMessage = GriefPreventionPlugin.instance.messageData.economyClaimSold
                .apply(ImmutableMap.of(
                    "amount", salePrice,
                    "balance", ownerAccount.getBalance(defaultCurrency))).build();
            if (ownerPlayer != null) {
                ownerPlayer.sendMessage(saleMessage);
            }
            claim.getEconomyData().setForSale(false);
            claim.getEconomyData().setSalePrice(0);
            claim.getData().save();
            GriefPreventionPlugin.sendMessage(src, message);
        }
    };
}
 
Example 17
Source File: RequiredInteractListener.java    From Prism with MIT License 4 votes vote down vote up
/**
 * Listens for interactions by Players with active inspection wands.
 * <br>
 * This listener is required and does not track any events.
 *
 * @param event  InteractBlockEvent
 * @param player Player
 */
@Listener(order = Order.EARLY)
public void onInteractBlock(InteractBlockEvent event, @First Player player) {
    // Wand support
    if (!Prism.getInstance().getActiveWands().contains(player.getUniqueId())) {
        return;
    }

    event.setCancelled(true);

    // Ignore OffHand events
    if (event instanceof InteractBlockEvent.Primary.OffHand || event instanceof InteractBlockEvent.Secondary.OffHand) {
        return;
    }

    // Verify target block is valid
    if (event.getTargetBlock() == BlockSnapshot.NONE || !event.getTargetBlock().getLocation().isPresent()) {
        return;
    }

    // Location of block
    Location<World> location = event.getTargetBlock().getLocation().get();

    // Secondary click gets location relative to side clicked
    if (event instanceof InteractBlockEvent.Secondary) {
        location = location.getRelative(event.getTargetSide());
    }

    QuerySession session = new QuerySession(player);
    // session.addFlag(Flag.EXTENDED);
    session.addFlag(Flag.NO_GROUP);
    session.newQuery().addCondition(ConditionGroup.from(location));

    player.sendMessage(Text.of(
            Format.prefix(), TextColors.GOLD,
            "--- Inspecting ", Format.item(location.getBlockType().getId(), true),
            " at ", location.getBlockX(), " ", location.getBlockY(), " ", location.getBlockZ(), " ---"));

    // Pass off to an async lookup helper
    AsyncUtil.lookup(session);
}
 
Example 18
Source File: InviteCommand.java    From EagleFactions with MIT License 4 votes vote down vote up
@Override
public CommandResult execute(final CommandSource source, final CommandContext context) throws CommandException
{
    final Player invitedPlayer = context.requireOne("player");

    if(!(source instanceof Player))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.ONLY_IN_GAME_PLAYERS_CAN_USE_THIS_COMMAND));

    final Player senderPlayer = (Player)source;
    final Optional<Faction> optionalSenderFaction = getPlugin().getFactionLogic().getFactionByPlayerUUID(senderPlayer.getUniqueId());

    if(!optionalSenderFaction.isPresent())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_IN_FACTION_IN_ORDER_TO_USE_THIS_COMMAND));

    final Faction senderFaction = optionalSenderFaction.get();

    if (!super.getPlugin().getPermsManager().canInvite(senderPlayer.getUniqueId(), senderFaction))
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.PLAYERS_WITH_YOUR_RANK_CANT_INVITE_PLAYERS_TO_FACTION));

    if(this.factionsConfig.isPlayerLimit())
    {
        int playerCount = 0;
        playerCount += senderFaction.getLeader().toString().equals("") ? 0 : 1;
        playerCount += senderFaction.getOfficers().isEmpty() ? 0 : senderFaction.getOfficers().size();
        playerCount += senderFaction.getMembers().isEmpty() ? 0 : senderFaction.getMembers().size();
        playerCount += senderFaction.getRecruits().isEmpty() ? 0 : senderFaction.getRecruits().size();

        if(playerCount >= this.factionsConfig.getPlayerLimit())
        {
            senderPlayer.sendMessage(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_CANT_INVITE_MORE_PLAYERS_TO_YOUR_FACTION + " " + Messages.FACTIONS_PLAYER_LIMIT_HAS_BEEN_REACHED));
            return CommandResult.success();
        }
    }

    if(super.getPlugin().getFactionLogic().getFactionByPlayerUUID(invitedPlayer.getUniqueId()).isPresent())
        throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.PLAYER_IS_ALREADY_IN_A_FACTION));

    final Invite invite = new Invite(senderFaction.getName(), invitedPlayer.getUniqueId());
    EagleFactionsPlugin.INVITE_LIST.add(invite);

    invitedPlayer.sendMessage(getInviteGetMessage(senderFaction));
    senderPlayer.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX,TextColors.GREEN, Messages.YOU_INVITED + " ", TextColors.GOLD, invitedPlayer.getName(), TextColors.GREEN, " " + Messages.TO_YOUR_FACTION));

    final Task.Builder taskBuilder = Sponge.getScheduler().createTaskBuilder();

    taskBuilder.execute(() -> EagleFactionsPlugin.INVITE_LIST.remove(invite)).delay(2, TimeUnit.MINUTES).name("EagleFaction - Remove Invite").submit(EagleFactionsPlugin.getPlugin());
    return CommandResult.success();
}
 
Example 19
Source File: TruceCommand.java    From EagleFactions with MIT License 4 votes vote down vote up
@Override
public CommandResult execute(final CommandSource source, final CommandContext context) throws CommandException
{
	final Faction selectedFaction = context.requireOne(Text.of("faction"));

	if(!(source instanceof Player))
		throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.ONLY_IN_GAME_PLAYERS_CAN_USE_THIS_COMMAND));

	final Player player = (Player) source;
	final Optional<Faction> optionalPlayerFaction = getPlugin().getFactionLogic().getFactionByPlayerUUID(player.getUniqueId());

	if(!optionalPlayerFaction.isPresent())
		throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_IN_FACTION_IN_ORDER_TO_USE_THIS_COMMAND));

	final Faction playerFaction = optionalPlayerFaction.get();
	if(playerFaction.getName().equals(selectedFaction.getName()))
		throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_CANNOT_INVITE_YOURSELF_TO_THE_TRUCE));

	if(super.getPlugin().getPlayerManager().hasAdminMode(player))
	{
		if(playerFaction.getEnemies().contains(selectedFaction.getName()))
			throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_ARE_IN_WAR_WITH_THIS_FACTION + " " + Messages.SEND_THIS_FACTION_A_PEACE_REQUEST_FIRST_BEFORE_INVITING_THEM_TO_ALLIES));

		if(playerFaction.getAlliances().contains(selectedFaction.getName()))
		{
			super.getPlugin().getFactionLogic().removeAlly(playerFaction.getName(), selectedFaction.getName());
			//Add truce
			super.getPlugin().getFactionLogic().addTruce(playerFaction.getName(), selectedFaction.getName());
			player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.GREEN, Messages.FACTION_HAS_BEEN_ADDED_TO_THE_TRUCE));
		}

		if(playerFaction.getTruces().contains(selectedFaction.getName()))
		{
			//Remove truce
			super.getPlugin().getFactionLogic().removeTruce(playerFaction.getName(), selectedFaction.getName());
			player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, MessageLoader.parseMessage(Messages.YOU_DISBANDED_YOUR_TRUCE_WITH_FACTION, TextColors.GREEN, ImmutableMap.of(Placeholders.FACTION_NAME, Text.of(TextColors.GOLD, selectedFaction.getName())))));
		}
		else
		{
			//Add truce
			super.getPlugin().getFactionLogic().addTruce(playerFaction.getName(), selectedFaction.getName());
			player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.GREEN, Messages.FACTION_HAS_BEEN_ADDED_TO_THE_TRUCE));
		}
		return CommandResult.success();
	}

	if(!playerFaction.getLeader().equals(player.getUniqueId()) && !playerFaction.getOfficers().contains(player.getUniqueId()))
		throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_MUST_BE_THE_FACTIONS_LEADER_OR_OFFICER_TO_DO_THIS));

	if(playerFaction.getEnemies().contains(selectedFaction.getName()))
		throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_ARE_IN_WAR_WITH_THIS_FACTION + " " + Messages.SEND_THIS_FACTION_A_PEACE_REQUEST_FIRST_BEFORE_INVITING_THEM_TO_ALLIES));

	if(playerFaction.getAlliances().contains(selectedFaction.getName()))
		throw new CommandException(Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.GREEN, Messages.DISBAND_ALLIANCE_FIRST_TO_INVITE_FACTION_TO_THE_TRUCE));

	if(playerFaction.getTruces().contains(selectedFaction.getName()))
	{
		//Remove truce
		super.getPlugin().getFactionLogic().removeTruce(playerFaction.getName(), selectedFaction.getName());
		player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, MessageLoader.parseMessage(Messages.YOU_DISBANDED_YOUR_TRUCE_WITH_FACTION, TextColors.GREEN, ImmutableMap.of(Placeholders.FACTION_NAME, Text.of(TextColors.GOLD, selectedFaction.getName())))));
	}
	else
	{
		AllyRequest checkInvite = new AllyRequest(selectedFaction.getName(), playerFaction.getName());

		if(EagleFactionsPlugin.TRUCE_INVITE_LIST.contains(checkInvite))
		{
			acceptInvite(player, playerFaction, selectedFaction);
			EagleFactionsPlugin.TRUCE_INVITE_LIST.remove(checkInvite);
		}
		else if(!EagleFactionsPlugin.TRUCE_INVITE_LIST.contains(checkInvite))
		{
			sendInvite(player, playerFaction, selectedFaction);
		}
	}
	return CommandResult.success();
}
 
Example 20
Source File: CommandHelper.java    From GriefPrevention with MIT License 4 votes vote down vote up
public static Consumer<CommandSource> createTeleportConsumer(CommandSource src, Location<World> location, Claim claim) {
    return teleport -> {
        if (!(src instanceof Player)) {
            // ignore
            return;
        }
        Player player = (Player) src;
        GPClaim gpClaim = (GPClaim) claim;
        GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getPlayerData(player.getWorld(), player.getUniqueId());
        if (!playerData.canIgnoreClaim(gpClaim) && !playerData.canManageAdminClaims) {
            // if not owner of claim, validate perms
            if (!player.getUniqueId().equals(claim.getOwnerUniqueId())) {
                if (!player.hasPermission(GPPermissions.COMMAND_CLAIM_INFO_TELEPORT_OTHERS)) {
                    player.sendMessage(Text.of(TextColors.RED, "You do not have permission to use the teleport feature in this claim.")); 
                    return;
                }
                if (!gpClaim.isUserTrusted(player, TrustType.ACCESSOR)) {
                    if (GriefPreventionPlugin.instance.economyService.isPresent()) {
                        // Allow non-trusted to TP to claims for sale
                        if (!gpClaim.getEconomyData().isForSale()) {
                            player.sendMessage(Text.of(TextColors.RED, "You are not trusted to use the teleport feature in this claim.")); 
                            return;
                        }
                    } else {
                        player.sendMessage(Text.of(TextColors.RED, "You are not trusted to use the teleport feature in this claim.")); 
                        return;
                    }
                }
            } else if (!player.hasPermission(GPPermissions.COMMAND_CLAIM_INFO_TELEPORT_BASE)) {
                player.sendMessage(Text.of(TextColors.RED, "You do not have permission to use the teleport feature in your claim.")); 
                return;
            }
        }

        Location<World> safeLocation = Sponge.getGame().getTeleportHelper().getSafeLocation(location, 64, 16).orElse(null);
        if (safeLocation == null) {
            player.sendMessage(
                    Text.builder().append(Text.of(TextColors.RED, "Location is not safe. "), 
                    Text.builder().append(Text.of(TextColors.GREEN, "Are you sure you want to teleport here?")).onClick(TextActions.executeCallback(createForceTeleportConsumer(player, location))).style(TextStyles.UNDERLINE).build()).build());
        } else {
            player.setLocation(safeLocation);
        }
    };
}