Java Code Examples for org.bukkit.Bukkit#dispatchCommand()

The following examples show how to use org.bukkit.Bukkit#dispatchCommand() . 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: PlayerEvents.java    From AntiVPN with MIT License 6 votes vote down vote up
private void tryRunCommands(List<String> commands, Player player, String ip) {
    Optional<PlaceholderAPIHook> placeholderapi;
    try {
        placeholderapi = ServiceLocator.getOptional(PlaceholderAPIHook.class);
    } catch (InstantiationException | IllegalAccessException ex) {
        logger.error(ex.getMessage(), ex);
        placeholderapi = Optional.empty();
    }

    for (String command : commands) {
        command = command.replace("%player%", player.getName()).replace("%uuid%", player.getUniqueId().toString()).replace("%ip%", ip);
        if (command.charAt(0) == '/') {
            command = command.substring(1);
        }

        if (placeholderapi.isPresent()) {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), placeholderapi.get().withPlaceholders(player, command));
        } else {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
        }
    }
}
 
Example 2
Source File: TitleEvent.java    From BetonQuest with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Void execute(String playerID) throws QuestRuntimeException {
    String lang = BetonQuest.getInstance().getPlayerData(playerID).getLanguage();
    String message = messages.get(lang);
    if (message == null) {
        message = messages.get(Config.getLanguage());
    }
    if (message == null) {
        message = messages.values().iterator().next();
    }
    for (String variable : variables) {
        message = message.replace(variable,
                BetonQuest.getInstance().getVariableValue(instruction.getPackage().getName(), variable, playerID));
    }
    String name = PlayerConverter.getName(playerID);
    if ((fadeIn != 20 || stay != 100 || fadeOut != 20) && (fadeIn != 0 || stay != 0 || fadeOut != 0)) {
        String times = String.format("title %s times %d %d %d", name, fadeIn, stay, fadeOut);
        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), times);
    }
    String title = String.format("title %s %s {\"text\":\"%s\"}",
            name, type.toString().toLowerCase(), message.replaceAll("&", "ยง"));
    Bukkit.dispatchCommand(Bukkit.getConsoleSender(), title);
    return null;
}
 
Example 3
Source File: GadgetHandler.java    From StaffPlus with GNU General Public License v3.0 6 votes vote down vote up
public void onCustom(Player player, Player targetPlayer, ModuleConfiguration moduleConfiguration)
{
	switch(moduleConfiguration.getType())
	{
		case COMMAND_STATIC:
			Bukkit.dispatchCommand(player, moduleConfiguration.getAction());
			break;
		case COMMAND_DYNAMIC:
			if(targetPlayer != null)
			{
				Bukkit.dispatchCommand(player, moduleConfiguration.getAction().replace("%clicker%", player.getName()).replace("%clicked%", targetPlayer.getName()));
			}
			break;
		case COMMAND_CONSOLE:
			if(targetPlayer != null)
			{
				Bukkit.dispatchCommand(Bukkit.getConsoleSender(), moduleConfiguration.getAction().replace("%clicker%", player.getName()).replace("%clicked%", targetPlayer.getName()));
			}else Bukkit.dispatchCommand(Bukkit.getConsoleSender(), moduleConfiguration.getAction().replace("%clicker%", player.getName()));
			break;
		default:
			break;
	}
}
 
Example 4
Source File: SnowflakesCommand.java    From CardinalPGM with MIT License 6 votes vote down vote up
@Command(aliases = {"snowflakes"}, desc = "View your own or another player's snowflake count.", usage = "[player]")
public static void settings(final CommandContext cmd, CommandSender sender) throws CommandException {
    if (cmd.argsLength() == 0) {
        Bukkit.dispatchCommand(sender, "snowflakes " + sender.getName());
    } else {
        Bukkit.getScheduler().runTaskAsynchronously(Cardinal.getInstance(), new AsyncCommand(cmd, sender) {
            @Override
            public void run() {
                OfflinePlayer player = Bukkit.getOfflinePlayer(cmd.getString(0));
                String snowflakes = Cardinal.getCardinalDatabase().get(player, "snowflakes");
                if (snowflakes.equals("")) snowflakes = "0";
                if (sender.equals(player)) {
                    sender.sendMessage(new UnlocalizedChatMessage(ChatColor.DARK_PURPLE + "{0} " + ChatColor.GOLD + "{1} {2}", ChatConstant.MISC_YOU_HAVE.asMessage(), new UnlocalizedChatMessage("{0}", snowflakes), snowflakes.equals("1") ? ChatConstant.SNOWFLAKES_SNOWFLAKE.asMessage() : ChatConstant.SNOWFLAKES_SNOWFLAKES.asMessage()).getMessage(ChatUtil.getLocale(sender)));
                } else {
                    sender.sendMessage(new UnlocalizedChatMessage(ChatColor.DARK_PURPLE + "{0} " + ChatColor.GOLD + "{1} {2}", new LocalizedChatMessage(ChatConstant.MISC_HAS, Players.getName(player) + ChatColor.DARK_PURPLE), new UnlocalizedChatMessage("{0}", snowflakes), snowflakes.equals("1") ? ChatConstant.SNOWFLAKES_SNOWFLAKE.asMessage() : ChatConstant.SNOWFLAKES_SNOWFLAKES.asMessage()).getMessage(ChatUtil.getLocale(sender)));
                }
            }
        });
    }
}
 
Example 5
Source File: Economy_Mixed.java    From QuickShop-Reremake with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean withdraw(@NotNull UUID name, double amount) {
    if (getBalance(name) > amount) {
        return false;
    }
    Bukkit.dispatchCommand(
            Bukkit.getConsoleSender(),
            MsgUtil.fillArgs(
                    plugin.getConfig().getString("mixedeconomy.withdraw"),
                    Bukkit.getOfflinePlayer(name).getName(),
                    String.valueOf(amount)));
    return true;
}
 
Example 6
Source File: AbstractGUIInventory.java    From NovaGuilds with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute() {
	Bukkit.dispatchCommand(getViewer().getPlayer(), command);

	if(close) {
		close();
	}
}
 
Example 7
Source File: ArmorStandCmd.java    From ArmorStandTools with MIT License 5 votes vote down vote up
boolean execute(Player p) {
    if(command == null) return true;
    if(isOnCooldown()) {
        p.sendMessage(ChatColor.RED + Config.cmdOnCooldown);
        return true;
    }
    setOnCooldown();
    String cmd = command.contains("%player%") ? command.replaceAll("%player%", p.getName()) : command;
    if(console) {
        return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd);
    } else {
        return p.performCommand(cmd);
    }
}
 
Example 8
Source File: Reward.java    From CombatLogX with GNU General Public License v3.0 5 votes vote down vote up
private void executeCommands(Player player, Entity enemy) {
    CommandSender console = Bukkit.getConsoleSender();
    List<String> commandList = (this.randomCommand ? getRandomCommand() : getCommands());
    for(String command : commandList) {
        String realCommand = replacePlaceholders(player, enemy, command);
        Bukkit.dispatchCommand(console, realCommand);
    }
}
 
Example 9
Source File: EndTutorial.java    From ServerTutorial with MIT License 5 votes vote down vote up
public void endTutorial(Player player) {
    Tutorial tutorial = TutorialManager.getManager().getCurrentTutorial(player.getName());
    endTutorialPlayer(player, tutorial.getEndMessage());
    EndTutorialEvent event = new EndTutorialEvent(player, tutorial);

    plugin.getServer().getPluginManager().callEvent(event);

    TutorialManager.getManager().setSeenTutorial(Caching.getCaching().getUUID(player), tutorial.getName());

    String command = tutorial.getCommand();
    CommandType type = tutorial.getCommandType();
    if (type == CommandType.NONE || command == null || command.isEmpty()) {
        return;
    }
    if (command.startsWith("/")) {
        command = command.replaceFirst("/", "");
    }
    command = command.replace("%player%", player.getName());

    switch (type) {
        case PLAYER:
            Bukkit.dispatchCommand(player, command);
            break;
        case CONSOLE:
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
            break;
    }
    TutorialPlayer tutorialPlayer = plugin.getTutorialPlayer(Caching.getCaching().getUUID(player));
    tutorialPlayer.restorePlayer(player);
    plugin.getTempPlayers().remove(player.getUniqueId());
    DataLoading.getDataLoading().getTempData().set("players." + player.getUniqueId(), null);
    DataLoading.getDataLoading().saveTempData();
}
 
Example 10
Source File: InfractionCoordinator.java    From StaffPlus with GNU General Public License v3.0 5 votes vote down vote up
public void sendWarning(CommandSender sender, Warning warning)
{
	User user = userManager.get(warning.getUuid());
	Player p = user.getPlayer();
	
	if(user == null || p == null)
	{
		message.send(sender, messages.playerOffline, messages.prefixGeneral);
		return;
	}
	
	if(permission.has(user.getPlayer(), options.permissionWarnBypass))
	{
		message.send(sender, messages.bypassed, messages.prefixGeneral);
		return;
	}
	
	user.addWarning(warning);
	message.send(sender, messages.warned.replace("%target%", warning.getName()).replace("%reason%", warning.getReason()), messages.prefixWarnings);
	message.send(p, messages.warn.replace("%reason%", warning.getReason()), messages.prefixWarnings);
	options.warningsSound.play(p);
	
	if(user.getWarnings().size() >= options.warningsMaximum && options.warningsMaximum > 0)
	{
		Bukkit.dispatchCommand(Bukkit.getConsoleSender(), options.warningsBanCommand.replace("%player%", p.getName()));
	}
}
 
Example 11
Source File: ModeCoordinator.java    From StaffPlus with GNU General Public License v3.0 5 votes vote down vote up
private void runModeCommands(String name, boolean isEnabled)
{
	for(String command : isEnabled ? options.modeEnableCommands : options.modeDisableCommands)
	{
		if(command.isEmpty())
		{
			continue;
		}
			
		Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.replace("%player%", name));
	}
}
 
Example 12
Source File: Updater.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
private void updatePlugin(boolean restart) throws Exception{
    HttpsURLConnection connection = (HttpsURLConnection) new URL(jarDownloadUrl).openConnection();
    connection.connect();

    File newPluginFile = new File("plugins/UhcCore-" + newestVersion + ".jar");
    File oldPluginFile = new File(plugin.getClass().getProtectionDomain().getCodeSource().getLocation().getFile());

    InputStream in = connection.getInputStream();
    FileOutputStream out = new FileOutputStream(newPluginFile);

    // Copy in to out
    int read;
    byte[] bytes = new byte[1024];

    while ((read = in.read(bytes)) != -1) {
        out.write(bytes, 0, read);
    }

    out.flush();
    out.close();
    in.close();
    connection.disconnect();

    Bukkit.getLogger().info("[UhcCore] New plugin version downloaded.");

    if (!newPluginFile.equals(oldPluginFile)){
        FileUtils.scheduleFileForDeletion(oldPluginFile);
        Bukkit.getLogger().info("[UhcCore] Old plugin version will be deleted on next startup.");
    }

    if (restart) {
        Bukkit.getLogger().info("[UhcCore] Restarting to finish plugin update.");
        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "restart");
        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "stop");
    }
}
 
Example 13
Source File: ConsoleCommandFactory.java    From Bukkit-SSHD with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Environment environment) throws IOException {
    try {
        SshdPlugin.instance.getLogger()
                .info("[U: " + environment.getEnv().get(Environment.ENV_USER) + "] " + command);
        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
    } catch (Exception e) {
        SshdPlugin.instance.getLogger().severe("Error processing command from SSH -" + e.getMessage());
    } finally {
        callback.onExit(0);
    }
}
 
Example 14
Source File: FancyMessage.java    From fanciful with MIT License 5 votes vote down vote up
private void send(CommandSender sender, String jsonString) {
	if (!(sender instanceof Player)) {
		sender.sendMessage(toOldMessageFormat());
		return;
	}
	Player player = (Player) sender;
	Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jsonString);
}
 
Example 15
Source File: BukkitService.java    From AuthMeReloaded with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Dispatches a command on this server, and executes it if found.
 *
 * @param sender the apparent sender of the command
 * @param commandLine the command + arguments. Example: <code>test abc 123</code>
 * @return returns false if no target is found
 */
public boolean dispatchCommand(CommandSender sender, String commandLine) {
    return Bukkit.dispatchCommand(sender, commandLine);
}
 
Example 16
Source File: RandomizedDropsListener.java    From UhcCore with GNU General Public License v3.0 4 votes vote down vote up
private void disableDataPack(){
	FileUtils.deleteFile(datapack);
	Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "minecraft:reload");
}
 
Example 17
Source File: TeamManagerModule.java    From CardinalPGM with MIT License 4 votes vote down vote up
@EventHandler
public void onPlayerChangeTeam(PlayerChangeTeamEvent event) {
    if (event.getNewTeam().isPresent() && !event.getNewTeam().get().isObserver() && GameHandler.getGameHandler().getMatch().isRunning()) {
        Bukkit.dispatchCommand(event.getPlayer(), "match");
    }
}
 
Example 18
Source File: ZPermissionsHandler.java    From AuthMeReloaded with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean addToGroup(OfflinePlayer player, String group) {
    return Bukkit.dispatchCommand(Bukkit.getConsoleSender(),
        "permissions player " + player.getName() + " addgroup " + group);
}
 
Example 19
Source File: SpectatorTools.java    From CardinalPGM with MIT License 4 votes vote down vote up
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
    ItemStack item = event.getCurrentItem();
    Player player = (Player) event.getWhoClicked();
    String locale = player.getLocale();
    if (item == null) return;
    if (event.getInventory().getName().equals(getSpectatorMenuTitle(event.getActor().getLocale()))) {
        if (item.isSimilar(getTeleportItem(locale))) {
            player.openInventory(getTeamsMenu(player));
        } else if (item.isSimilar(getVisibilityItem(locale))) {
            Bukkit.dispatchCommand(player, "toggle obs");
            player.closeInventory();
        } else if (item.isSimilar(getElytraItem(locale))) {
            Bukkit.dispatchCommand(player, "toggle elytra");
            player.closeInventory();
        } else if (item.isSimilar(getEffectsItem(locale))) {
            player.openInventory(getEffectsMenu(player));
        } else if (item.isSimilar(getGamemodeItem(locale))) {
            player.setGameMode(player.getGameMode().equals(GameMode.CREATIVE) ? GameMode.SPECTATOR : GameMode.CREATIVE);
            if (player.getGameMode().equals(GameMode.CREATIVE)) Bukkit.dispatchCommand(player, "!");
            player.closeInventory();
        }
    } else if (event.getInventory().getName().equals(getTeamsMenuTitle(locale))) {
        if (item.isSimilar(getGoBackItem(locale))) {
            player.openInventory(getSpectatorMenu(player));
        } else if (item.getType().equals(Material.LEATHER_HELMET) && item.getItemMeta().hasDisplayName() && !item.isSimilar(TeamPicker.getTeamPicker(locale))){
            TeamModule team = Teams.getTeamByName(ChatColor.stripColor(Strings.removeLastWord(item.getItemMeta().getDisplayName()))).orNull();
            if (team != null) {
                player.openInventory(getTeleportMenu(player, team));
            }
        }
    } else if (event.getInventory().getName().equals(getTeleportMenuTitle(locale))) {
        if (item.isSimilar(getGoBackItem(locale))) {
            player.openInventory(getTeamsMenu(player));
        } else if (item.getType().equals(Material.SKULL_ITEM) && item.getItemMeta().hasDisplayName()) {
            Player teleport = Bukkit.getPlayer(((SkullMeta) item.getItemMeta()).getOwner());
            if (teleport != null) {
                player.teleport(teleport);
                player.closeInventory();
            }
        }
    } else if (event.getInventory().getName().equals(getEffectsMenuTitle(locale))) {
        if (item.isSimilar(getGoBackItem(locale))) {
            player.openInventory(getSpectatorMenu(player));
        } else if (item.isSimilar(getNightVisionItem(player.getLocale()))) {
            if (player.hasPotionEffect(PotionEffectType.NIGHT_VISION)) {
                player.removePotionEffect(PotionEffectType.NIGHT_VISION);
            } else {
                player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 0, false, false));
            }
            player.closeInventory();
        } else if (item.getType().equals(Material.SUGAR) && item.getItemMeta().hasDisplayName()) {
            int value = event.getSlot();
            Setting setting = Settings.getSettingByName("Speed");
            Bukkit.dispatchCommand(player, "set speed " + setting.getValues().get(value).getValue());
            player.closeInventory();
        }
    }
}
 
Example 20
Source File: BukkitService.java    From AuthMeReloaded with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Dispatches a command to be run as console user on this server, and executes it if found.
 *
 * @param commandLine the command + arguments. Example: <code>test abc 123</code>
 * @return returns false if no target is found
 */
public boolean dispatchConsoleCommand(String commandLine) {
    return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), commandLine);
}