Search in sources :

Example 31 with CommandSender

use of org.bukkit.command.CommandSender in project Citizens2 by CitizensDev.

the class NPCCommandSelector method acceptValidatedInput.

@Override
protected Prompt acceptValidatedInput(ConversationContext context, Number input) {
    boolean found = false;
    for (NPC npc : choices) {
        if (input.intValue() == npc.getId()) {
            found = true;
            break;
        }
    }
    CommandSender sender = (CommandSender) context.getForWhom();
    if (!found) {
        Messaging.sendErrorTr(sender, Messages.SELECTION_PROMPT_INVALID_CHOICE, input);
        return this;
    }
    NPC toSelect = CitizensAPI.getNPCRegistry().getById(input.intValue());
    try {
        callback.run(toSelect);
    } catch (ServerCommandException ex) {
        Messaging.sendTr(sender, CommandMessages.MUST_BE_INGAME);
    } catch (CommandUsageException ex) {
        Messaging.sendError(sender, ex.getMessage());
        Messaging.sendError(sender, ex.getUsage());
    } catch (UnhandledCommandException ex) {
        ex.printStackTrace();
    } catch (WrappedCommandException ex) {
        ex.getCause().printStackTrace();
    } catch (CommandException ex) {
        Messaging.sendError(sender, ex.getMessage());
    } catch (NumberFormatException ex) {
        Messaging.sendErrorTr(sender, CommandMessages.INVALID_NUMBER);
    }
    return null;
}
Also used : NPC(net.citizensnpcs.api.npc.NPC) CommandUsageException(net.citizensnpcs.api.command.exception.CommandUsageException) ServerCommandException(net.citizensnpcs.api.command.exception.ServerCommandException) UnhandledCommandException(net.citizensnpcs.api.command.exception.UnhandledCommandException) WrappedCommandException(net.citizensnpcs.api.command.exception.WrappedCommandException) CommandSender(org.bukkit.command.CommandSender) UnhandledCommandException(net.citizensnpcs.api.command.exception.UnhandledCommandException) WrappedCommandException(net.citizensnpcs.api.command.exception.WrappedCommandException) ServerCommandException(net.citizensnpcs.api.command.exception.ServerCommandException) CommandException(net.citizensnpcs.api.command.exception.CommandException)

Example 32 with CommandSender

use of org.bukkit.command.CommandSender in project NoCheatPlus by NoCheatPlus.

the class NoCheatPlus method sendAdminNotifyMessageSubscriptions.

/**
 * Send notification to all CommandSenders found in permission subscriptions for the notify-permission as well as players that have stored permissions (those get re-checked here).
 * @param message
 * @return
 */
public int sendAdminNotifyMessageSubscriptions(final String message) {
    // TODO: Fetch from PlayerData - alt: update subscriptions on a regular basis - not every call!
    final String lcPerm = Permissions.NOTIFY.getLowerCaseStringRepresentation();
    final Permission bukkitPerm = Permissions.NOTIFY.getBukkitPermission();
    final Set<Permissible> permissibles = Bukkit.getPluginManager().getPermissionSubscriptions(lcPerm);
    final Set<String> done = new HashSet<String>(permissibles.size());
    for (final Permissible permissible : permissibles) {
        if (permissible instanceof CommandSender) {
            final CommandSender sender = (CommandSender) permissible;
            if (sender instanceof Player) {
                // Use the permission caching feature.
                final Player player = (Player) sender;
                final IPlayerData data = DataManager.getPlayerData(player);
                if (data.getNotifyOff() || !data.hasPermission(Permissions.NOTIFY, player)) {
                    continue;
                }
            } else if (!sender.hasPermission(bukkitPerm)) {
                // TODO: Add permission cache for non-player-things?
                continue;
            }
            // Finally send.
            sender.sendMessage(message);
            done.add(sender.getName());
        }
    }
    return done.size();
}
Also used : Player(org.bukkit.entity.Player) Permissible(org.bukkit.permissions.Permissible) RegisteredPermission(fr.neatmonster.nocheatplus.permissions.RegisteredPermission) Permission(org.bukkit.permissions.Permission) IPlayerData(fr.neatmonster.nocheatplus.players.IPlayerData) CommandSender(org.bukkit.command.CommandSender) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 33 with CommandSender

use of org.bukkit.command.CommandSender in project UltimateChat by FabioZumbi12.

the class UCMessages method sendMessage.

@SuppressWarnings("deprecation")
public static UltimateFancy sendMessage(CommandSender sender, Object receiver, String msg, UCChannel ch, boolean isSpy) {
    UltimateFancy fanci = new UltimateFancy();
    if (!ch.getName().equals("tell")) {
        String[] defaultBuilder = UChat.get().getUCConfig().getDefBuilder();
        if (ch.useOwnBuilder()) {
            defaultBuilder = ch.getBuilder();
        }
        for (String tag : defaultBuilder) {
            if (UChat.get().getUCConfig().getString("tags." + tag + ".format") == null) {
                fanci.text(tag).next();
                continue;
            }
            String perm = UChat.get().getUCConfig().getString("tags." + tag + ".permission");
            String format = UChat.get().getUCConfig().getString("tags." + tag + ".format");
            String execute = UChat.get().getUCConfig().getString("tags." + tag + ".click-cmd");
            String suggest = UChat.get().getUCConfig().getString("tags." + tag + ".suggest-cmd");
            String url = UChat.get().getUCConfig().getString("tags." + tag + ".click-url");
            List<String> messages = UChat.get().getUCConfig().getStringList("tags." + tag + ".hover-messages");
            List<String> showWorlds = UChat.get().getUCConfig().getStringList("tags." + tag + ".show-in-worlds");
            List<String> hideWorlds = UChat.get().getUCConfig().getStringList("tags." + tag + ".hide-in-worlds");
            // check perm
            if (perm != null && !perm.isEmpty() && !UCPerms.hasPermission(sender, perm)) {
                continue;
            }
            // check show or hide in world
            if (sender instanceof Player) {
                if (!showWorlds.isEmpty() && !showWorlds.contains(((Player) sender).getWorld().getName())) {
                    continue;
                }
                if (!hideWorlds.isEmpty() && hideWorlds.contains(((Player) sender).getWorld().getName())) {
                    continue;
                }
            }
            StringBuilder tooltip = new StringBuilder();
            for (String tp : messages) {
                tooltip.append("\n").append(tp);
            }
            if (tooltip.length() > 2) {
                tooltip = new StringBuilder(tooltip.substring(1));
            }
            if (execute != null && !execute.isEmpty()) {
                fanci.clickRunCmd(formatTags(tag, "/" + execute, sender, receiver, msg, ch));
            }
            if (suggest != null && !suggest.isEmpty()) {
                fanci.clickSuggestCmd(formatTags(tag, suggest, sender, receiver, msg, ch));
            }
            if (url != null && !url.isEmpty()) {
                try {
                    fanci.clickOpenURL(new URL(formatTags(tag, url, sender, receiver, msg, ch)));
                } catch (MalformedURLException ignored) {
                }
            }
            if (!tag.equals("message") || UCPerms.hasPerm(sender, "chat.click-urls")) {
                for (String arg : msg.split(" ")) {
                    try {
                        fanci.clickOpenURL(new URL(formatTags(tag, arg, sender, receiver, msg, ch)));
                        fanci.hoverShowText(UCUtil.colorize(formatTags(tag, UChat.get().getUCConfig().getString("general.URL-template").replace("{url}", arg), sender, receiver, msg, ch)));
                    } catch (MalformedURLException ignored) {
                    }
                }
            }
            if (tag.equals("message") && (!msg.equals(mention(sender, (CommandSender) receiver, msg)) || msg.contains(UChat.get().getUCConfig().getString("general.item-hand.placeholder")))) {
                tooltip = new StringBuilder(formatTags("", tooltip.toString(), sender, receiver, msg, ch));
                format = formatTags(tag, format, sender, receiver, msg, ch);
                if (UChat.get().getUCConfig().getBoolean("general.item-hand.enable") && msg.contains(UChat.get().getUCConfig().getString("general.item-hand.placeholder")) && sender instanceof Player) {
                    fanci.text(format).hoverShowItem(((Player) sender).getItemInHand()).next();
                } else if (!msg.equals(mention(sender, (CommandSender) receiver, msg)) && UChat.get().getUCConfig().getString("mention.hover-message").length() > 0 && StringUtils.containsIgnoreCase(msg, ((CommandSender) receiver).getName())) {
                    tooltip = new StringBuilder(formatTags("", UChat.get().getUCConfig().getString("mention.hover-message"), sender, receiver, msg, ch));
                    fanci.text(format).hoverShowText(tooltip.toString()).next();
                } else if (tooltip.length() > 0) {
                    fanci.text(format).hoverShowText(tooltip.toString()).next();
                } else {
                    fanci.text(format).next();
                }
            } else {
                format = formatTags(tag, format, sender, receiver, msg, ch);
                tooltip = new StringBuilder(formatTags("", tooltip.toString(), sender, receiver, msg, ch));
                if (tooltip.length() > 0) {
                    fanci.text(format).hoverShowText(tooltip.toString()).next();
                } else {
                    fanci.text(format).next();
                }
            }
        }
    } else {
        // if tell
        String prefix = UChat.get().getUCConfig().getString("tell.prefix");
        String format = UChat.get().getUCConfig().getString("tell.format");
        List<String> messages = UChat.get().getUCConfig().getStringList("tell.hover-messages");
        StringBuilder tooltip = new StringBuilder();
        for (String tp : messages) {
            tooltip.append("\n").append(tp);
        }
        if (tooltip.length() > 2) {
            tooltip = new StringBuilder(tooltip.substring(1));
        }
        prefix = formatTags("", prefix, sender, receiver, msg, ch);
        format = formatTags("tell", format, sender, receiver, msg, ch);
        tooltip = new StringBuilder(formatTags("", tooltip.toString(), sender, receiver, msg, ch));
        if (tooltip.length() > 0) {
            fanci.text(format).hoverShowText(tooltip.toString()).next();
        } else {
            fanci.text(prefix).next();
        }
        fanci.text(ChatColor.stripColor(format)).next();
    }
    return fanci;
}
Also used : ClanPlayer(net.sacredlabyrinth.phaed.simpleclans.ClanPlayer) Player(org.bukkit.entity.Player) MalformedURLException(java.net.MalformedURLException) CommandSender(org.bukkit.command.CommandSender) URL(java.net.URL)

Example 34 with CommandSender

use of org.bukkit.command.CommandSender in project UltimateChat by FabioZumbi12.

the class UCMessages method formatTags.

@SuppressWarnings("deprecation")
public static String formatTags(String tag, String text, Object cmdSender, Object receiver, String msg, UCChannel ch) {
    if (receiver instanceof CommandSender && tag.equals("message")) {
        text = text.replace("{message}", mention(cmdSender, (CommandSender) receiver, msg));
        if (UChat.get().getUCConfig().getBoolean("general.item-hand.enable")) {
            text = text.replace(UChat.get().getUCConfig().getString("general.item-hand.placeholder"), formatTags("", ChatColor.translateAlternateColorCodes('&', UChat.get().getUCConfig().getString("general.item-hand.format")), cmdSender, receiver, msg, ch));
        }
    } else {
        text = text.replace("{message}", msg);
    }
    if (tag.equals("message") && !UChat.get().getUCConfig().getBoolean("general.enable-tags-on-messages")) {
        return text;
    }
    text = text.replace("{ch-color}", ch.getColor()).replace("{ch-name}", ch.getName()).replace("{ch-alias}", ch.getAlias());
    if (UChat.get().getUCConfig().getBoolean("jedis.enable") && ch.useJedis()) {
        text = text.replace("{jedis-id}", UChat.get().getUCConfig().getString("jedis.server-id"));
    }
    if (ch.isBungee()) {
        text = text.replace("{bungee-id}", UChat.get().getUCConfig().getString("bungee.server-id"));
    }
    if (cmdSender instanceof CommandSender) {
        text = text.replace("{playername}", ((CommandSender) cmdSender).getName());
        if (receiver instanceof CommandSender)
            text = text.replace("{receivername}", ((CommandSender) receiver).getName());
        if (receiver instanceof String)
            text = text.replace("{receivername}", (String) receiver);
    } else {
        text = text.replace("{playername}", (String) cmdSender).replace("{receivername}", (String) receiver);
    }
    for (String repl : registeredReplacers.keySet()) {
        if (registeredReplacers.get(repl).equals(repl)) {
            text = text.replace(repl, "");
            continue;
        }
        text = text.replace(repl, registeredReplacers.get(repl));
    }
    StringBuilder def = new StringBuilder();
    for (int i = 0; i < defFormat.length; i++) {
        text = text.replace("{default-format-" + i + "}", defFormat[i]);
        def.append(" ").append(defFormat[i]);
    }
    if (def.length() > 0) {
        text = text.replace("{default-format-full}", def.substring(1));
    }
    if (text.contains("{time-now}")) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        text = text.replace("{time-now}", sdf.format(cal.getTime()));
    }
    if (cmdSender instanceof Player) {
        Player sender = (Player) cmdSender;
        if (text.contains("{world}")) {
            String world = UChat.get().getUCConfig().getString("general.world-names." + sender.getWorld().getName());
            text = text.replace("{world}", world != null ? world : sender.getWorld().getName());
        }
        text = text.replace("{nickname}", sender.getDisplayName());
        // replace item hand
        text = text.replace(UChat.get().getUCConfig().getString("general.item-hand.placeholder"), ChatColor.translateAlternateColorCodes('&', UChat.get().getUCConfig().getString("general.item-hand.format")));
        if (text.contains("{hand-") && !sender.getItemInHand().getType().equals(Material.AIR)) {
            ItemStack item = sender.getItemInHand();
            text = text.replace("{hand-durability}", String.valueOf(item.getDurability()));
            if (item.hasItemMeta()) {
                ItemMeta meta = item.getItemMeta();
                if (UCUtil.getBukkitVersion() >= 1112 && meta.hasLocalizedName()) {
                    text = text.replace("{hand-name}", item.getItemMeta().getLocalizedName());
                } else if (meta.hasDisplayName()) {
                    text = text.replace("{hand-name}", item.getItemMeta().getDisplayName());
                } else {
                    text = text.replace("{hand-name}", UCUtil.capitalize(item.getType().toString()));
                }
                if (meta.hasLore()) {
                    StringBuilder lorestr = new StringBuilder();
                    for (String lore : meta.getLore()) {
                        lorestr.append("\n ").append(lore);
                    }
                    if (lorestr.length() >= 2) {
                        text = text.replace("{hand-lore}", lorestr.toString().substring(0, lorestr.length() - 1));
                    }
                }
                if (meta.hasEnchants()) {
                    StringBuilder str = new StringBuilder();
                    for (Entry<Enchantment, Integer> enchant : meta.getEnchants().entrySet()) {
                        str.append("\n ").append(enchant.getKey().getName()).append(": ").append(enchant.getValue());
                    }
                    if (str.length() >= 2) {
                        text = text.replace("{hand-enchants}", str.toString().substring(0, str.length() - 1));
                    }
                }
            }
            text = text.replace("{hand-amount}", String.valueOf(item.getAmount()));
            text = text.replace("{hand-name}", UCUtil.capitalize(item.getType().toString()));
            text = text.replace("{hand-type}", UCUtil.capitalize(item.getType().toString()));
        } else {
            text = text.replace("{hand-name}", UChat.get().getLang().get("chat.emptyslot"));
            text = text.replace("{hand-type}", "Air");
        }
        if (UChat.get().getVaultChat() != null && (text.contains("-prefix") || text.contains("-suffix"))) {
            text = text.replace("{group-suffix}", UCVaultCache.getVaultChat(sender).getPlayerSuffix()).replace("{group-prefix}", UCVaultCache.getVaultChat(sender).getPlayerPrefix());
            String[] pgs = UCVaultCache.getVaultPerms(sender).getPlayerGroups();
            if (pgs.length > 0) {
                text = text.replace("{player-groups-prefixes}", UCVaultCache.getVaultChat(sender).getGroupPrefixes()).replace("{player-groups-suffixes}", UCVaultCache.getVaultChat(sender).getGroupSuffixes());
            }
        }
        if (UChat.get().getVaultEco() != null && text.contains("{balance}")) {
            text = text.replace("{balance}", "" + UChat.get().getVaultEco().getBalance(sender, sender.getWorld().getName()));
        }
        if (UChat.get().getVaultPerms() != null && (text.contains("-group}") || text.contains("-groups}"))) {
            String[] pgs = UCVaultCache.getVaultPerms(sender).getPlayerGroups();
            if (pgs.length > 0) {
                StringBuilder groups = new StringBuilder();
                for (String g : pgs) {
                    groups.append(g).append(",");
                }
                text = text.replace("{player-groups}", groups.toString().substring(0, groups.length() - 1));
            }
            String primGroup = UCVaultCache.getVaultPerms(sender).getPrimaryGroup();
            String group = UChat.get().getUCConfig().getString("general.group-names." + primGroup);
            text = text.replace("{prim-group}", group == null ? primGroup : group);
        }
        if (text.contains("{clan-") && UChat.SClans) {
            ClanPlayer cp = UChat.sc.getClanManager().getClanPlayer(sender.getUniqueId());
            SettingsManager scm = UChat.sc.getSettingsManager();
            if (cp != null) {
                String fulltag = scm.getTagBracketColor() + scm.getTagBracketLeft() + scm.getTagDefaultColor() + cp.getClan().getColorTag() + scm.getTagBracketColor() + scm.getTagBracketRight() + scm.getTagSeparatorColor() + scm.getTagSeparator();
                text = text.replace("{clan-tag}", cp.getTag()).replace("{clan-fulltag}", fulltag).replace("{clan-name}", checkEmpty(cp.getClan().getName())).replace("{clan-kdr}", "" + cp.getKDR()).replace("{clan-rank}", checkEmpty(cp.getRank())).replace("{clan-totalkdr}", "" + cp.getClan().getTotalKDR()).replace("{clan-deaths}", "" + cp.getDeaths()).replace("{clan-isleader}", "" + cp.isLeader()).replace("{clan-totalkdr}", "" + cp.getClan().getTotalKDR()).replace("{clan-ctag}", cp.getClan().getColorTag());
            }
        }
        if (UChat.Factions) {
            text = UCFactionsHook.formatFac(text, sender, receiver);
        }
        if (text.contains("{marry-")) {
            if (UChat.MarryReloded && sender.hasMetadata("marriedTo")) {
                String partner = sender.getMetadata("marriedTo").get(0).asString();
                String prefix = UChat.mapi.getBukkitConfig("config.yml").getString("chat.status-format");
                UChat.mapi.getMPlayer(sender.getUniqueId()).getGender().getChatPrefix();
                prefix = prefix.replace("{icon:male}", "♂").replace("{icon:female}", "♀").replace("{icon:genderless}", "⚤").replace("{icon:heart}", "❤");
                String gender = UChat.mapi.getMPlayer(sender.getUniqueId()).getGender().getChatPrefix();
                gender = gender.replace("{icon:male}", "♂").replace("{icon:female}", "♀").replace("{icon:genderless}", "⚤").replace("{icon:heart}", "❤");
                text = text.replace("{marry-partner}", partner).replace("{marry-prefix}", prefix).replace("{marry-suffix}", gender);
            }
            if (UChat.MarryMaster) {
                if (UChat.mm.HasPartner(sender)) {
                    text = text.replace("{marry-partner}", UChat.mm.DB.GetPartner(sender)).replace("{marry-prefix}", UChat.mm.config.GetPrefix().replace("<heart>", ChatColor.RED + "❤" + ChatColor.WHITE)).replace("{marry-suffix}", UChat.mm.config.GetSuffix().replace("<heart>", ChatColor.RED + "❤" + ChatColor.WHITE));
                }
            }
        }
        if (UChat.PlaceHolderAPI) {
            if (receiver instanceof Player && UChat.get().isRelation()) {
                while (text.contains("%rel_")) {
                    text = PlaceholderAPI.setRelationalPlaceholders(sender, (Player) receiver, text);
                }
            }
            text = PlaceholderAPI.setPlaceholders(sender, text);
            if (tag.equals("message")) {
                text = composeColor(sender, text);
            }
        }
    }
    if (cmdSender instanceof CommandSender) {
        text = text.replace("{nickname}", UChat.get().getUCConfig().getString("general.console-tag").replace("{console}", ((CommandSender) cmdSender).getName()));
    } else {
        text = text.replace("{nickname}", UChat.get().getUCConfig().getString("general.console-tag").replace("{console}", (String) cmdSender));
    }
    // colorize tags (not message)
    if (!tag.equals("message")) {
        text = ChatColor.translateAlternateColorCodes('&', text);
    }
    // remove blank items
    text = text.replaceAll("\\{.*\\}", "");
    // remove remain PlaceholderAPI
    if (UChat.get().getUCConfig().getBoolean("general.remove-unnused-placeholderapi")) {
        text = text.replaceAll("\\%.*\\%", "");
    }
    if (!tag.equals("message")) {
        for (String rpl : UChat.get().getUCConfig().getStringList("general.remove-from-chat")) {
            text = text.replace(ChatColor.translateAlternateColorCodes('&', rpl), "");
        }
    }
    if (text.equals(" ") || text.equals("  ")) {
        text = "";
    }
    return text;
}
Also used : ClanPlayer(net.sacredlabyrinth.phaed.simpleclans.ClanPlayer) Player(org.bukkit.entity.Player) SettingsManager(net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager) ClanPlayer(net.sacredlabyrinth.phaed.simpleclans.ClanPlayer) CommandSender(org.bukkit.command.CommandSender) ItemStack(org.bukkit.inventory.ItemStack) Enchantment(org.bukkit.enchantments.Enchantment) SimpleDateFormat(java.text.SimpleDateFormat) ItemMeta(org.bukkit.inventory.meta.ItemMeta)

Example 35 with CommandSender

use of org.bukkit.command.CommandSender in project Essentials by EssentialsX.

the class ToggleTest method runConsoleCommand.

private void runConsoleCommand(String command, String[] args) throws Exception {
    IEssentialsCommand cmd;
    CommandSender sender = server.getConsoleSender();
    try {
        cmd = (IEssentialsCommand) Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command).newInstance();
        cmd.setEssentials(ess);
        cmd.run(server, new CommandSource(sender), command, null, args);
    } catch (NoChargeException ex) {
    }
}
Also used : NoChargeException(com.earth2me.essentials.commands.NoChargeException) IEssentialsCommand(com.earth2me.essentials.commands.IEssentialsCommand) CommandSender(org.bukkit.command.CommandSender)

Aggregations

CommandSender (org.bukkit.command.CommandSender)295 Test (org.junit.Test)171 Player (org.bukkit.entity.Player)94 Matchers.containsString (org.hamcrest.Matchers.containsString)68 ConsoleCommandSender (org.bukkit.command.ConsoleCommandSender)50 CoreStateInitException (com.solinia.solinia.Exceptions.CoreStateInitException)43 PlayerAuth (fr.xephi.authme.data.auth.PlayerAuth)30 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)29 PermissionNode (fr.xephi.authme.permission.PermissionNode)17 BlockCommandSender (org.bukkit.command.BlockCommandSender)16 ValidationResult (fr.xephi.authme.service.ValidationService.ValidationResult)12 Location (org.bukkit.Location)10 HashedPassword (fr.xephi.authme.security.crypts.HashedPassword)9 ArrayList (java.util.ArrayList)9 List (java.util.List)9 FoundCommandResult (fr.xephi.authme.command.FoundCommandResult)8 IOException (java.io.IOException)7 Entity (org.bukkit.entity.Entity)7 IEssentialsCommand (com.earth2me.essentials.commands.IEssentialsCommand)6 NoChargeException (com.earth2me.essentials.commands.NoChargeException)6