org.spongepowered.api.text.action.TextActions Java Examples

The following examples show how to use org.spongepowered.api.text.action.TextActions. 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: Format.java    From Prism with MIT License 6 votes vote down vote up
/**
 * Return content formatted with location information.
 * Optionally a click action can be added to teleport
 * the message recipients to the provided location.
 * @param x X Coordinate
 * @param y Y Coordinate
 * @param z Z Coordinate
 * @param world World
 * @param clickAction Click Action
 * @return Text Formatted content.
 */
public static Text location(int x, int y, int z, World world, boolean clickAction) {
    Text.Builder textBuilder = Text.builder();
    textBuilder.append(Text.of("(x:", x, " y:", y, " z:", z));
    if (world != null) {
        textBuilder.append(Text.of(" world:", world.getName()));

        if (clickAction) {
            textBuilder.onClick(TextActions.executeCallback(commandSource -> {
                if (!(commandSource instanceof Player)) {
                    return;
                }

                ((Player) commandSource).setLocation(world.getLocation(x, y, z));
            }));
        }
    }

    return textBuilder.append(Text.of(")")).build();
}
 
Example #2
Source File: UCCommands.java    From UltimateChat with GNU General Public License v3.0 6 votes vote down vote up
private void sendPreTell(CommandSource sender, CommandSource receiver, Text msg) {
    CommandSource src = sender;
    if (sender instanceof ConsoleSource) {
        src = receiver;
    }

    UChat.get().getLogger().timings(UCLogger.timingType.START, "UCListener#sendPreTell()|Fire AsyncPlayerChatEvent");

    MessageChannelEvent.Chat event = SpongeEventFactory.createMessageChannelEventChat(
            UChat.get().getVHelper().getCause(src),
            src.getMessageChannel(),
            Optional.of(src.getMessageChannel()),
            new MessageEvent.MessageFormatter(Text.builder("<" + src.getName() + "> ")
                    .onShiftClick(TextActions.insertText(src.getName()))
                    .onClick(TextActions.suggestCommand("/msg " + src.getName()))
                    .build(), msg),
            msg,
            false);
    Sponge.getEventManager().post(event);
}
 
Example #3
Source File: WorldsBase.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Override
public void executeAsync(CommandSource src, CommandContext ctx)
{
	ArrayList<String> worlds = EssentialCmds.getEssentialCmds().getGame().getServer().getWorlds().stream().filter(world -> world.getProperties().isEnabled()).map(World::getName).collect(Collectors.toCollection(ArrayList::new));

	PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
	ArrayList<Text> worldText = Lists.newArrayList();

	for (String name : worlds)
	{
		Text item = Text.builder(name)
			.onClick(TextActions.runCommand("/tpworld " + name))
			.onHover(TextActions.showText(Text.of(TextColors.WHITE, "Teleport to world ", TextColors.GOLD, name)))
			.color(TextColors.DARK_AQUA)
			.style(TextStyles.UNDERLINE)
			.build();

		worldText.add(item);
	}

	PaginationList.Builder paginationBuilder = paginationService.builder().contents(worldText).title(Text.of(TextColors.GREEN, "Showing Worlds")).padding(Text.of("-"));
	paginationBuilder.sendTo(src);
}
 
Example #4
Source File: SubjectListPane.java    From ChatUI with MIT License 6 votes vote down vote up
Text renderSubject(Subject subject) {
    HoverAction<?> hover = null;
    if (this.collection.getIdentifier().equals(PermissionService.SUBJECTS_USER)) {
        try {
            UUID uuid = UUID.fromString(subject.getIdentifier());
            Optional<User> user = Sponge.getServiceManager().provideUnchecked(UserStorageService.class).get(uuid);
            if (user.isPresent()) {
                hover = TextActions.showText(Text.of(user.get().getName()));
            }
        } catch (Exception e) {
        }
    }
    return Text.builder(subject.getIdentifier())
            .onHover(hover)
            .onClick(ExtraUtils.clickAction(() -> {
                this.tab.getSubjViewer().setActive(subject, true);
                this.tab.setRoot(this.tab.getSubjViewer());
            }, SubjectListPane.this.tab)).build();
}
 
Example #5
Source File: CommandClaimInfo.java    From GriefPrevention with MIT License 6 votes vote down vote up
public static Text getClickableInfoText(CommandSource src, Claim claim, String title, Text infoText) {
    Text onClickText = Text.of("Click here to toggle value.");
    boolean hasPermission = true;
    if (src instanceof Player) {
        Text denyReason = ((GPClaim) claim).allowEdit((Player) src);
        if (denyReason != null) {
            onClickText = denyReason;
            hasPermission = false;
        }
    }

    Text.Builder textBuilder = Text.builder()
            .append(infoText)
            .onHover(TextActions.showText(Text.of(onClickText)));
    if (hasPermission) {
        textBuilder.onClick(TextActions.executeCallback(createClaimInfoConsumer(src, claim, title)));
    }
    return textBuilder.build();
}
 
Example #6
Source File: PrivateMessageFeature.java    From ChatUI with MIT License 6 votes vote down vote up
private void installMessageButton(ActivePlayerChatView view) {
    UUID playerId = view.getPlayer().getUniqueId();
    view.getPlayerList().addAddon(player -> {
        UUID otherId = player.getUniqueId();
        Text.Builder builder = Text.builder("Message");
        if (!otherId.equals(playerId)) {
            if (this.privateView.containsKey(otherId)) {
                builder.onClick(Utils.execClick(() -> newPrivateMessage(playerId, otherId)))
                        .onHover(TextActions.showText(Text.of("Send a private message")))
                        .color(TextColors.BLUE).style(TextStyles.UNDERLINE);
            } else {
                builder.color(TextColors.GRAY)
                        .onHover(TextActions.showText(Text.of("This player doesn't have Chat UI enabled")));
            }

        } else {
            builder.color(TextColors.GRAY)
                    .onHover(TextActions.showText(Text.of("Cannot send message to yourself")));
        }
        return builder.build();
    });
}
 
Example #7
Source File: GroupListRenderer.java    From ChatUI with MIT License 6 votes vote down vote up
@Override
public List<Text> renderCell(Object value, int row, int tableWidth, PlayerContext ctx) {
    ChatGroup group = (ChatGroup) value;
    Text.Builder builder = Text.builder("X");
    builder.onHover(TextActions.showText(Text.of("Delete Group")));
    if (this.feature.canDeleteGroup(group, this.view.getPlayer())) {
        builder.color(TextColors.RED);
        builder.onClick(Utils.execClick(view -> {
            this.feature.removeGroup(group);
            view.update();
        }));
    } else {
        builder.color(TextColors.GRAY);
    }
    return Collections.singletonList(builder.build());
}
 
Example #8
Source File: ChatGroupTab.java    From ChatUI with MIT License 6 votes vote down vote up
@Override
public void draw(PlayerContext ctx, LineFactory lineFactory) {
    Text.Builder builder = Text.builder();
    LiteralText.Builder createButton = Text.builder("[Create Group]");
    if (ChatGroupTab.this.feature.canCreateGroup(ctx.getPlayer())) {
        createButton.onClick(Utils.execClick(view -> {
            ChatGroupTab.this.createGroup = !ChatGroupTab.this.createGroup;
            view.update();
        }));
        createButton.color(TextColors.GREEN);
        if (ChatGroupTab.this.createGroup) {
            lineFactory.appendNewLine(Text.of("Type group name in chat:"), ctx);
            createButton.content("[Cancel]");
            createButton.color(TextColors.RED);
        }
    } else {
        createButton.onHover(TextActions.showText(Text.of("You do not have permission to create groups")));
        createButton.color(TextColors.GRAY);
    }
    builder.append(createButton.build());
    lineFactory.appendNewLine(builder.build(), ctx);
}
 
Example #9
Source File: JaillistCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkPermission(sender, JailPermissions.UC_JAIL_JAILLIST_BASE);
    List<Jail> jails = GlobalData.get(JailKeys.JAILS).get();
    List<Text> texts = new ArrayList<>();

    //Add entry to texts for every jail
    for (Jail jail : jails) {
        texts.add(Messages.getFormatted("jail.command.jaillist.entry", "%jail%", jail.getName(), "%description%", jail.getDescription()).toBuilder().onHover(TextActions.showText(Messages.getFormatted("jail.command.jaillist.hoverentry", "%jail%", jail.getName()))).onClick(TextActions.runCommand("/jailtp " + jail.getName())).build());
    }

    //If empty send message
    if (texts.isEmpty()) {
        throw new ErrorMessageException(Messages.getFormatted(sender, "jail.command.jaillist.empty"));
    }

    //Sort alphabetically
    Collections.sort(texts);

    //Send page
    PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
    PaginationList paginationList = paginationService.builder().contents(texts).title(Messages.getFormatted("jail.command.jaillist.header").toBuilder().color(TextColors.DARK_GREEN).build()).build();
    paginationList.sendTo(sender);
    return CommandResult.success();
}
 
Example #10
Source File: CommandHelper.java    From GriefPrevention with MIT License 6 votes vote down vote up
public static Text getClickableText(CommandSource src, Subject subject, String subjectName, Set<Context> contexts, GPClaim claim, String flagPermission, Tristate flagValue, String source, FlagType type) {
    Text onClickText = Text.of("Click here to toggle flag value.");
    boolean hasPermission = true;
    if (type == FlagType.INHERIT) {
        onClickText = Text.of("This flag is inherited from parent claim ", claim.getName().orElse(claim.getFriendlyNameType()), " and ", TextStyles.UNDERLINE, "cannot", TextStyles.RESET, " be changed.");
        hasPermission = false;
    } else if (src instanceof Player) {
        Text denyReason = claim.allowEdit((Player) src);
        if (denyReason != null) {
            onClickText = denyReason;
            hasPermission = false;
        }
    }

    Text.Builder textBuilder = Text.builder()
    .append(Text.of(flagValue.toString().toLowerCase()))
    .onHover(TextActions.showText(Text.of(onClickText, "\n", getFlagTypeHoverText(type))));
    if (hasPermission) {
        textBuilder.onClick(TextActions.executeCallback(createFlagConsumer(src, subject, subjectName, contexts, claim, flagPermission, flagValue, source)));
    }
    return textBuilder.build();
}
 
Example #11
Source File: WarplistCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkPermission(sender, WarpPermissions.UC_WARP_WARPLIST_BASE);
    //Send the player a paginated list of all warps
    List<Warp> warps = GlobalData.get(WarpKeys.WARPS).get();
    List<Text> texts = new ArrayList<>();
    //Add entry to texts for every warp
    for (Warp warp : warps) {
        if (!sender.hasPermission("uc.warp.warp." + warp.getName().toLowerCase())) {
            continue;
        }
        texts.add(Messages.getFormatted("warp.command.warplist.entry", "%warp%", warp.getName(), "%description%", warp.getDescription()).toBuilder().onHover(TextActions.showText(Messages.getFormatted("warp.command.warplist.hoverentry", "%warp%", warp.getName()))).onClick(TextActions.runCommand("/warp " + warp.getName())).build());
    }
    //If empty send message
    if (texts.isEmpty()) {
        throw new ErrorMessageException(Messages.getFormatted(sender, "warp.command.warplist.empty"));
    }
    //Sort alphabetically
    Collections.sort(texts);
    //Send page
    PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
    PaginationList paginationList = paginationService.builder().contents(texts).title(Messages.getFormatted("warp.command.warplist.header").toBuilder().color(TextColors.DARK_GREEN).build()).build();
    paginationList.sendTo(sender);
    return CommandResult.success();
}
 
Example #12
Source File: VariableUtil.java    From UltimateCore with MIT License 6 votes vote down vote up
public static Text getNameSource(CommandSource player) {
    //TODO nickname
    if (player instanceof Player) {
        Player p = (Player) player;
        Text name = ((Player) player).getDisplayNameData().displayName().get();
        if (Modules.NICK.isPresent()) {
            UltimateUser up = UltimateCore.get().getUserService().getUser(p);
            if (up.get(NickKeys.NICKNAME).isPresent() && !up.get(NickKeys.NICKNAME).get().isEmpty()) {
                name = up.get(NickKeys.NICKNAME).get();
            }
        }
        return name.toBuilder().onHover(TextActions.showText(Messages.getFormatted("core.variable.player.hover", "%name%", name, "%rawname%", player.getName(), "%uuid%", ((Player) player).getUniqueId(), "%language%", player.getLocale().getDisplayName(Locale.ENGLISH)))).onClick(TextActions.suggestCommand(Messages.getFormatted("core.variable.player.click", "%player%", player.getName()).toPlain())).build();
    } else {
        return Text.builder(player.getName()).onHover(TextActions.showText(Messages.getFormatted("core.variable.player.hover", "%name%", player.getName(), "%rawname%", player.getName(), "%uuid%", player.getIdentifier(), "%language%", player.getLocale().getDisplayName(Locale.ENGLISH)))).onClick(TextActions.suggestCommand(Messages.getFormatted("core.variable.player.click", "%player%", player.getName()).toPlain())).build();
    }
}
 
Example #13
Source File: CmdUserList.java    From Web-API with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    Collection<UserPermissionStruct> users = WebAPI.getUserService().getUsers();
    PaginationList.builder()
            .title(Text.of("Web-API users"))
            .contents(users.stream().map(u -> {
                Text editUser = Text.builder("[Change pw]")
                        .color(TextColors.YELLOW)
                        .onClick(TextActions.suggestCommand("/webapi users changepw " + u.getName() + " "))
                        .build();

                Text rmvUser = Text.builder(" [Remove]")
                        .color(TextColors.RED)
                        .onClick(TextActions.suggestCommand("/webapi users remove " + u.getName()))
                        .build();

                return Text.builder(u.getName() + " ").append(editUser, rmvUser).build();
            }).collect(Collectors.toList()))
            .sendTo(src);
    return CommandResult.success();
}
 
Example #14
Source File: VersionCommand.java    From EagleFactions with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(final CommandSource source, final CommandContext context) throws CommandException
{
    try
    {
        source.sendMessage(Text.of(
                TextActions.showText(Text.of(TextColors.BLUE, "Click to view Github")),
                TextActions.openUrl(new URL("https://github.com/Aquerr/EagleFactions")),
                PluginInfo.PLUGIN_PREFIX, TextColors.AQUA, PluginInfo.NAME, TextColors.WHITE, " - ", TextColors.GOLD, Messages.VERSION + " ", PluginInfo.VERSION, TextColors.WHITE, " made by ", TextColors.GOLD, PluginInfo.AUTHOR));
    }
    catch(final MalformedURLException e)
    {
        e.printStackTrace();
    }
    return CommandResult.success();
}
 
Example #15
Source File: Format.java    From Prism with MIT License 6 votes vote down vote up
/**
 * Returns content formatted with an Item name.
 * Optionally a hover action can be added to display
 * the full Item id.
 * @param id Item Id
 * @param hoverAction Hover Action
 * @return Text Formatted content.
 */
public static Text item(String id, boolean hoverAction) {
    checkNotNull(id);

    Text.Builder textBuilder = Text.builder();
    if (StringUtils.contains(id, ":")) {
        textBuilder.append(Text.of(StringUtils.substringAfter(id, ":")));
    } else {
        textBuilder.append(Text.of(id));
    }

    if (hoverAction) {
        textBuilder.onHover(TextActions.showText(Text.of(id)));
    }

    return textBuilder.build();
}
 
Example #16
Source File: CommandHelper.java    From GriefPrevention with MIT License 5 votes vote down vote up
public static Consumer<CommandSource> createReturnClaimListConsumer(CommandSource src, Consumer<CommandSource> returnCommand) {
    return consumer -> {
        Text claimListReturnCommand = Text.builder().append(Text.of(
                TextColors.WHITE, "\n[", TextColors.AQUA, "Return to claimslist", TextColors.WHITE, "]\n"))
            .onClick(TextActions.executeCallback(returnCommand)).build();
        src.sendMessage(claimListReturnCommand);
    };
}
 
Example #17
Source File: InfoWorldCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    WorldProperties world;
    if (!args.hasAny("world")) {
        checkIfPlayer(src);
        Player p = (Player) src;
        world = p.getWorld().getProperties();
    } else {
        world = args.<WorldProperties>getOne("world").get();
    }
    Messages.send(src, "world.command.world.info.single.title", "%world%", world.getWorldName());
    Messages.send(src, "world.command.world.info.single.id-uuid", "%id%", world.getUniqueId().toString());
    String numeric;
    try {
        numeric = world.getAdditionalProperties().getView(DataQuery.of("SpongeData")).get().get(DataQuery.of("dimensionId")).get().toString();
    } catch (Exception ex) {
        numeric = "?";
    }
    Messages.send(src, "world.command.world.info.single.id-numeric", "%id%", numeric);
    Messages.send(src, "world.command.world.info.single.enabled", "%enabled%", world.loadOnStartup() ? Messages.getFormatted(src, "world.enabled") : Messages.getFormatted(src, "world.disabled"));
    Messages.send(src, "world.command.world.info.single.difficulty", "%difficulty%", world.getDifficulty().getName());
    Messages.send(src, "world.command.world.info.single.gamemode", "%gamemode%", world.getGameMode().getName());
    Messages.send(src, "world.command.world.info.single.hardcore", "%hardcore%", world.isHardcore() ? Messages.getFormatted(src, "world.enabled") : Messages.getFormatted(src, "world.disabled"));
    Messages.send(src, "world.command.world.info.single.pvp", "%pvp%", world.isPVPEnabled() ? Messages.getFormatted(src, "world.enabled") : Messages.getFormatted(src, "world.disabled"));
    src.sendMessage(Messages.getFormatted(src, "world.command.world.info.single.gamerules").toBuilder().onClick(TextActions.runCommand("/world gamerule " + world.getWorldName())).build());
    return CommandResult.success();
}
 
Example #18
Source File: SendMailCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    //Get sender
    checkIfPlayer(src);
    Player p = (Player) src;
    UltimateUser up = UltimateCore.get().getUserService().getUser(p);

    //Get target & construct mail
    GameProfile t = args.<GameProfile>getOne("player").get();
    UltimateUser ut = UltimateCore.get().getUserService().getUser(t.getUniqueId()).get();
    String message = args.<String>getOne("message").get();
    Mail mail = new Mail(p.getUniqueId(), Arrays.asList(t.getUniqueId()), System.currentTimeMillis(), message);

    //Offer to data api
    List<Mail> sentMail = up.get(MailKeys.MAILS_SENT).get();
    sentMail.add(mail);
    up.offer(MailKeys.MAILS_SENT, sentMail);
    List<Mail> receivedMail = ut.get(MailKeys.MAILS_RECEIVED).get();
    receivedMail.add(mail);
    ut.offer(MailKeys.MAILS_RECEIVED, receivedMail);

    //Increase unread count
    up.offer(MailKeys.UNREAD_MAIL, up.get(MailKeys.UNREAD_MAIL).get() + 1);

    Messages.send(src, "mail.command.mail.send", "%player%", t.getName().orElse(""));
    if (ut.getPlayer().isPresent()) {
        ut.getPlayer().get().sendMessage(Messages.getFormatted(ut.getPlayer().get(), "mail.command.mail.newmail", "%count%", up.get(MailKeys.UNREAD_MAIL).get()).toBuilder().onHover(TextActions.showText(Messages.getFormatted(ut.getPlayer().get(), "mail.command.mail.newmail.hover"))).onClick(TextActions.runCommand("/mail read")).build());
    }
    return CommandResult.success();
}
 
Example #19
Source File: KitlistCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    //Permissions
    checkPermission(sender, KitPermissions.UC_KIT_KITLIST_BASE);
    //Get all kits
    List<Kit> kits = GlobalData.get(KitKeys.KITS).get();
    List<Text> texts = new ArrayList<>();
    //Add entry to texts for every kit
    for (Kit kit : kits) {
        if (!sender.hasPermission("uc.kit.kit." + kit.getId().toLowerCase())) {
            continue;
        }
        texts.add(Messages.getFormatted("kit.command.kitlist.entry", "%kit%", kit.getId(), "%description%", kit.getDescription()).toBuilder().onHover(TextActions.showText(Messages.getFormatted("kit.command.kitlist.hoverentry", "%kit%", kit))).onClick(TextActions.runCommand("/kit " + kit)).build());
    }
    //If empty send message
    if (texts.isEmpty()) {
        Messages.send(sender, "kit.command.kitlist.empty");
        return CommandResult.empty();
    }
    //Sort alphabetically
    Collections.sort(texts);

    PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
    PaginationList paginationList = paginationService.builder().contents(texts).title(Messages.getFormatted("kit.command.kitlist.header").toBuilder().format(Messages.getFormatted("kit.command.kitlist.char").getFormat()).build()).padding(Messages.getFormatted("kit.command.kitlist.char")).build();
    paginationList.sendTo(sender);
    return CommandResult.success();
}
 
Example #20
Source File: HomelistCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkIfPlayer(sender);
    checkPermission(sender, HomePermissions.UC_HOME_HOME_BASE);
    Player p = (Player) sender;

    UltimateUser user = UltimateCore.get().getUserService().getUser(p);
    List<Home> homes = user.get(HomeKeys.HOMES).orElse(new ArrayList<>());
    if (homes.isEmpty()) {
        throw new ErrorMessageException(Messages.getFormatted(sender, "home.command.homelist.empty"));
    }
    List<Text> entries = new ArrayList<>();
    for (Home home : homes) {
        entries.add(Messages.getFormatted("home.command.homelist.entry", "%home%", home.getName()).toBuilder().onHover(TextActions.showText(Messages.getFormatted("home.command.homelist.hoverentry", "%home%", home.getName()))).onClick(TextActions.runCommand("/home " + home.getName())).build());
    }
    Collections.sort(entries);

    Text footer;
    if (!p.hasPermission(HomePermissions.UC_HOME_SETHOME_UNLIMITED.get())) {
        String shomecount = HomePermissions.UC_HOME_HOMECOUNT.getFor(sender);
        if (!ArgumentUtil.isInteger(shomecount)) {
            throw new ErrorMessageException(Messages.getFormatted(sender, "home.command.sethome.invalidhomecount", "%homecount%", shomecount));
        }
        Integer homecount = Integer.parseInt(shomecount);
        footer = Messages.getFormatted("home.command.homelist.footer", "%current%", homes.size(), "%max%", homecount);
    } else {
        footer = Messages.getFormatted("home.command.homelist.footer.unlimited");
    }

    PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
    PaginationList paginationList = paginationService.builder().contents(entries).title(Messages.getFormatted("home.command.homelist.header").toBuilder().format(Messages.getFormatted("home.command.homelist.char").getFormat()).build()).footer(footer).padding(Messages.getFormatted("home.command.homelist.char")).build();
    paginationList.sendTo(sender);
    return CommandResult.success();
}
 
Example #21
Source File: MailListener.java    From UltimateCore with MIT License 5 votes vote down vote up
@Listener
public void onJoin(ClientConnectionEvent.Join event) {
    UltimateUser up = UltimateCore.get().getUserService().getUser(event.getTargetEntity());
    int unreadCount = up.get(MailKeys.UNREAD_MAIL).get();
    if (unreadCount == 0) return;
    event.getTargetEntity().sendMessage(Messages.getFormatted(event.getTargetEntity(), "mail.command.mail.newmail", "%count%", unreadCount).toBuilder().onHover(TextActions.showText(Messages.getFormatted(event.getTargetEntity(), "mail.command.mail.newmail.hover"))).onClick(TextActions.runCommand("/mail read")).build());
}
 
Example #22
Source File: MailListExecutor.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;
		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;
		}

		PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
		List<Text> mailText = Lists.newArrayList();

		for (Mail newM : mail)
		{
			String name = "New mail from " + newM.getSenderName();
			Text item = Text.builder(name).onClick(TextActions.runCommand("/readmail " + (mail.indexOf(newM)))).onHover(TextActions.showText(Text.of(TextColors.WHITE, "Read mail from ", TextColors.GOLD, newM.getSenderName()))).color(TextColors.DARK_AQUA).style(TextStyles.UNDERLINE).build();

			mailText.add(item);
		}

		PaginationList.Builder paginationBuilder = paginationService.builder().contents(mailText).title(Text.of(TextColors.GREEN, "Showing Mail")).padding(Text.of("-"));
		paginationBuilder.sendTo(src);
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Must be an in-game player to use /mailist!"));
	}
}
 
Example #23
Source File: ListCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(final CommandSource source, final CommandContext context) throws CommandException
{
    CompletableFuture.runAsync(() ->{
        Set<Faction> factionsList = new HashSet<>(super.getPlugin().getFactionLogic().getFactions().values());
        List<Text> helpList = new ArrayList<>();

        Text tagPrefix = getPlugin().getConfiguration().getChatConfig().getFactionStartPrefix();
        Text tagSuffix = getPlugin().getConfiguration().getChatConfig().getFactionEndPrefix();

        for(final Faction faction : factionsList)
        {
            Text tag = Text.builder().append(tagPrefix).append(faction.getTag()).append(tagSuffix, Text.of(" ")).build();

            Text factionHelp = Text.builder()
                    .append(Text.builder()
                            .append(Text.of(TextColors.AQUA, "- ")).append(tag).append(Text.of(faction.getName(), " (", getPlugin().getPowerManager().getFactionPower(faction), "/", getPlugin().getPowerManager().getFactionMaxPower(faction), ")"))
                            .build())
                    .onClick(TextActions.runCommand("/f info " + faction.getName()))
                    .onHover(TextActions.showText(Text.of(TextStyles.ITALIC, TextColors.BLUE, "Click", TextColors.RESET, " for more info...")))
                    .build();

            helpList.add(factionHelp);
        }

        PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
        PaginationList.Builder paginationBuilder = paginationService.builder().title(Text.of(TextColors.GREEN, Messages.FACTIONS_LIST)).padding(Text.of("-")).contents(helpList);
        paginationBuilder.sendTo(source);
    });
    return CommandResult.success();
}
 
Example #24
Source File: ListHomeExecutor.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;

		Set<Object> homes = Utils.getHomes(player.getUniqueId());

		if (homes.size() == 0)
		{
			player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must first set a home to list your homes!"));
			return;
		}

		PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
		List<Text> homeText = Lists.newArrayList();

		for (Object home : homes)
		{
			String name = String.valueOf(home);

			Text item = Text.builder(name)
				.onClick(TextActions.runCommand("/home " + name))
				.onHover(TextActions.showText(Text.of(TextColors.WHITE, "Teleport to home ", TextColors.GOLD, name)))
				.color(TextColors.DARK_AQUA)
				.style(TextStyles.UNDERLINE)
				.build();

			homeText.add(item);
		}

		PaginationList.Builder paginationBuilder = paginationService.builder().contents(homeText).title(Text.of(TextColors.GREEN, "Showing Homes")).padding(Text.of("-"));
		paginationBuilder.sendTo(src);
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Must be an in-game player to use /homes!"));
	}
}
 
Example #25
Source File: Utils.java    From EssentialCmds with MIT License 5 votes vote down vote up
public static Text getURL(String message)
{
	List<String> extractedUrls = extractUrls(message);
	for (String url : extractedUrls)
	{
		List<String> extractmb = extractmbefore(message);
		for (String preurl : extractmb)
		{
			List<String> extractma = extractmafter(message);
			for (String posturl : extractma)
			{
				try
				{
					String preurlline = preurl.replaceAll("(((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*).*?)(?=\\w).*", "");
					String posturlline = posturl.replaceAll("((https?|ftp|gopher|telnet|file|Unsure|http):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)", "");
					Text preMessage = TextSerializers.FORMATTING_CODE.deserialize(preurlline);
					Text postMessage = TextSerializers.FORMATTING_CODE.deserialize(posturlline);
					Text linkmessage = Text.builder(url).onClick(TextActions.openUrl(new URL(url))).build();
					Text newmessage = Text.builder().append(preMessage).append(linkmessage).append(postMessage).build();
					return newmessage;
				}
				catch (MalformedURLException e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	return TextSerializers.FORMATTING_CODE.deserialize(message);
}
 
Example #26
Source File: CommandHelper.java    From GriefPrevention with MIT License 5 votes vote down vote up
public static Consumer<CommandSource> createReturnClaimListConsumer(CommandSource src, String arguments) {
    return consumer -> {
        Text claimListReturnCommand = Text.builder().append(Text.of(
                TextColors.WHITE, "\n[", TextColors.AQUA, "Return to claimslist", TextColors.WHITE, "]\n"))
            .onClick(TextActions.executeCallback(CommandHelper.createCommandConsumer(src, "claimslist", arguments))).build();
        src.sendMessage(claimListReturnCommand);
    };
}
 
Example #27
Source File: CommandHelper.java    From GriefPrevention with MIT License 5 votes vote down vote up
public static Text getClickableText(CommandSource src, Subject subject, String subjectName, Set<Context> contexts, String flagPermission, Tristate flagValue, FlagType type) {
    String onClickText = "Click here to toggle " + type.name().toLowerCase() + " value.";
    Text.Builder textBuilder = Text.builder()
            .append(Text.of(flagValue.toString().toLowerCase()))
            .onHover(TextActions.showText(Text.of(onClickText, "\n", getFlagTypeHoverText(type))))
            .onClick(TextActions.executeCallback(createFlagConsumer(src, subject, subjectName, contexts, flagPermission, flagValue, type)));
    return textBuilder.build();
}
 
Example #28
Source File: CommandClaimInfo.java    From GriefPrevention with MIT License 5 votes vote down vote up
private static List<Text> generateAdminSettings(CommandSource src, GPClaim claim) {
    List<Text> textList = new ArrayList<>();
    Text returnToClaimInfo = Text.builder().append(Text.of(
            TextColors.WHITE, "\n[", TextColors.AQUA, "Return to standard settings", TextColors.WHITE, "]\n"))
        .onClick(TextActions.executeCallback(CommandHelper.createCommandConsumer(src, "claiminfo", claim.getUniqueId().toString()))).build();
    Text claimDenyMessages = Text.of(TextColors.YELLOW, DENY_MESSAGES, TextColors.WHITE, " : ", getClickableInfoText(src, claim, DENY_MESSAGES, claim.getInternalClaimData().allowDenyMessages() ? Text.of(TextColors.GREEN, "ON") : Text.of(TextColors.RED, "OFF")), TextColors.RESET);
    Text claimResizable = Text.of(TextColors.YELLOW, RESIZABLE, TextColors.WHITE, " : ", getClickableInfoText(src, claim, RESIZABLE, claim.getInternalClaimData().isResizable() ? Text.of(TextColors.GREEN, "ON") : Text.of(TextColors.RED, "OFF")), TextColors.RESET);
    Text claimRequiresClaimBlocks = Text.of(TextColors.YELLOW, REQUIRES_CLAIM_BLOCKS, TextColors.WHITE, " : ", getClickableInfoText(src, claim, REQUIRES_CLAIM_BLOCKS, claim.getInternalClaimData().requiresClaimBlocks() ? Text.of(TextColors.GREEN, "ON") : Text.of(TextColors.RED, "OFF")), TextColors.RESET);
    Text claimSizeRestrictions = Text.of(TextColors.YELLOW, SIZE_RESTRICTIONS, TextColors.WHITE, " : ", getClickableInfoText(src, claim, SIZE_RESTRICTIONS, claim.getInternalClaimData().hasSizeRestrictions() ? Text.of(TextColors.GREEN, "ON") : Text.of(TextColors.RED, "OFF")), TextColors.RESET);
    Text claimExpiration = Text.of(TextColors.YELLOW, CLAIM_EXPIRATION, TextColors.WHITE, " : ", getClickableInfoText(src, claim, CLAIM_EXPIRATION, claim.getInternalClaimData().allowExpiration() ? Text.of(TextColors.GREEN, "ON") : Text.of(TextColors.RED, "OFF")), TextColors.RESET);
    Text claimFlagOverrides = Text.of(TextColors.YELLOW, FLAG_OVERRIDES, TextColors.WHITE, " : ", getClickableInfoText(src, claim, FLAG_OVERRIDES, claim.getInternalClaimData().allowFlagOverrides() ? Text.of(TextColors.GREEN, "ON") : Text.of(TextColors.RED, "OFF")), TextColors.RESET);
    Text pvp = Text.of(TextColors.YELLOW, "PvP", TextColors.WHITE, " : ", getClickableInfoText(src, claim, PVP_OVERRIDE, claim.getInternalClaimData().getPvpOverride() == Tristate.TRUE ? Text.of(TextColors.GREEN, "ON") : Text.of(TextColors.RED, claim.getInternalClaimData().getPvpOverride().name())), TextColors.RESET);
    textList.add(returnToClaimInfo);
    textList.add(claimDenyMessages);
    if (!claim.isAdminClaim() && !claim.isWilderness()) {
        textList.add(claimRequiresClaimBlocks);
        textList.add(claimExpiration);
        textList.add(claimResizable);
        textList.add(claimSizeRestrictions);
    }
    textList.add(claimFlagOverrides);
    textList.add(pvp);
    int fillSize = 20 - (textList.size() + 4);
    for (int i = 0; i < fillSize; i++) {
        textList.add(Text.of(" "));
    }
    return textList;
}
 
Example #29
Source File: ClaimFlagBase.java    From GriefPrevention with MIT License 5 votes vote down vote up
private static Text getFlagText(String flagPermission, String baseFlag) {
    final String flagSource = GPPermissionHandler.getSourcePermission(flagPermission);
    final String flagTarget = GPPermissionHandler.getTargetPermission(flagPermission);
    Text sourceText = flagSource == null ? null : Text.of(TextColors.WHITE, "source=",TextColors.GREEN, flagSource);
    Text targetText = flagTarget == null ? null : Text.of(TextColors.WHITE, "target=",TextColors.GREEN, flagTarget);
    if (sourceText != null) {
       /* if (targetText != null) {
            sourceText = Text.of(sourceText, "  ");
        } else {*/
            sourceText = Text.of(sourceText, "\n");
        //}
    } else {
        sourceText = Text.of();
    }
    if (targetText != null) {
        targetText = Text.of(targetText);
    } else {
        targetText = Text.of();
    }
    Text baseFlagText = Text.of();
    if (flagSource == null && flagTarget == null) {
        baseFlagText = Text.builder().append(Text.of(TextColors.GREEN, baseFlag.toString(), " "))
            .onHover(TextActions.showText(Text.of(sourceText, targetText))).build();
    } else {
        baseFlagText = Text.builder().append(Text.of(TextStyles.ITALIC, TextColors.YELLOW, baseFlag.toString(), " ", TextStyles.RESET))
                .onHover(TextActions.showText(Text.of(sourceText, targetText))).build();
    }
    final Text baseText = Text.builder().append(Text.of(
            baseFlagText)).build();
            //sourceText,
            //targetText)).build();
    return baseText;
}
 
Example #30
Source File: CommandHelper.java    From GriefPrevention with MIT License 5 votes vote down vote up
public static Consumer<CommandSource> createBankTransactionsConsumer(CommandSource src, GPClaim claim, boolean checkTown, boolean returnToClaimInfo) {
    return settings -> {
        final String name = "Bank Transactions";
        List<String> bankTransactions = new ArrayList<>(claim.getData().getEconomyData().getBankTransactionLog());
        Collections.reverse(bankTransactions);
        List<Text> textList = new ArrayList<>();
        textList.add(Text.builder().append(Text.of(
                TextColors.WHITE, "\n[", TextColors.AQUA, "Return to bank info", TextColors.WHITE, "]\n"))
            .onClick(TextActions.executeCallback(consumer -> { displayClaimBankInfo(src, claim, checkTown, returnToClaimInfo); })).build());
        Gson gson = new Gson();
        for (String transaction : bankTransactions) {
            GPBankTransaction bankTransaction = gson.fromJson(transaction, GPBankTransaction.class);
            final Duration duration = Duration.between(bankTransaction.timestamp, Instant.now().truncatedTo(ChronoUnit.SECONDS)) ;
            final long s = duration.getSeconds();
            final User user = GriefPreventionPlugin.getOrCreateUser(bankTransaction.source);
            final String timeLeft = String.format("%dh %02dm %02ds", s / 3600, (s % 3600) / 60, (s % 60)) + " ago";
            textList.add(Text.of(getTransactionColor(bankTransaction.type), bankTransaction.type.name(), 
                    TextColors.BLUE, " | ", TextColors.WHITE, bankTransaction.amount, 
                    TextColors.BLUE, " | ", TextColors.GRAY, timeLeft,
                    user == null ? "" : Text.of(TextColors.BLUE, " | ", TextColors.LIGHT_PURPLE, user.getName())));
        }
        textList.add(Text.builder().append(Text.of(
                TextColors.WHITE, "\n[", TextColors.AQUA, "Return to bank info", TextColors.WHITE, "]\n"))
            .onClick(TextActions.executeCallback(CommandHelper.createCommandConsumer(src, "claimbank", ""))).build());
        PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
        PaginationList.Builder paginationBuilder = paginationService.builder()
                .title(Text.of(TextColors.AQUA, name)).padding(Text.of(TextStyles.STRIKETHROUGH, "-")).contents(textList);
        paginationBuilder.sendTo(src);
    };
}