org.bukkit.command.CommandSender Java Examples
The following examples show how to use
org.bukkit.command.CommandSender.
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: PaginationCommand.java From LagMonitor with MIT License | 6 votes |
private void onPageNumber(String subCommand, CommandSender sender, Pages pagination) { Integer page = Ints.tryParse(subCommand); if (page == null) { sendError(sender, "Unknown subcommand or not a valid page number"); } else { if (page < 1) { sendError(sender, "Page number too small"); return; } else if (page > pagination.getTotalPages(sender instanceof Player)) { sendError(sender, "Page number too high"); return; } pagination.send(sender, page); } }
Example #2
Source File: PurgeCommandTest.java From AuthMeReloaded with GNU General Public License v3.0 | 6 votes |
@Test public void shouldForwardToService() { // given String interval = "45"; CommandSender sender = mock(CommandSender.class); // when command.executeCommand(sender, Collections.singletonList(interval)); // then ArgumentCaptor<Long> captor = ArgumentCaptor.forClass(Long.class); verify(purgeService).runPurge(eq(sender), captor.capture()); // Check the timestamp with a certain tolerance int toleranceMillis = 100; Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, -Integer.valueOf(interval)); assertIsCloseTo(captor.getValue(), calendar.getTimeInMillis(), toleranceMillis); }
Example #3
Source File: CommandHandler.java From NyaaUtils with MIT License | 6 votes |
@SubCommand(value = "addlore", permission = "nu.setlore") public void addlore(CommandSender sender, Arguments args) { if (!(args.length() > 1)) { msg(sender, "manual.addlore.usage"); return; } String lore = args.next().replace("ยง", ""); Player p = asPlayer(sender); lore = ChatColor.translateAlternateColorCodes('&', lore); ItemStack item = p.getInventory().getItemInMainHand(); if (item == null || item.getType().equals(Material.AIR)) { msg(sender, "user.info.no_item_hand"); return; } String[] line = lore.split("/n"); List<String> lines = item.getItemMeta().getLore() == null ? new ArrayList<>() : item.getItemMeta().getLore(); for (String s : line) { lines.add(ChatColor.translateAlternateColorCodes('&', s)); } ItemMeta itemStackMeta = item.getItemMeta(); itemStackMeta.setLore(lines); item.setItemMeta(itemStackMeta); msg(sender, "user.setlore.success", lore); }
Example #4
Source File: MinepacksCommand.java From Minepacks with GNU General Public License v3.0 | 6 votes |
/** * Executes some basic checks and runs the command afterwards. * * @param sender Source of the command. * @param mainCommandAlias Alias of the plugins main command which was used. * @param alias Alias of the command which has been used. * @param args Passed command arguments. */ @Override public void doExecute(@NotNull CommandSender sender, @NotNull String mainCommandAlias, @NotNull String alias, @NotNull String... args) { if(playerOnly && !(sender instanceof Player)) { messageNotFromConsole.send(sender); } else if(getPermission() != null && !sender.hasPermission(getPermission())) { messageNoPermission.send(sender); } else { execute(sender, mainCommandAlias, alias, args); } }
Example #5
Source File: SentinelTargetCommands.java From Sentinel with MIT License | 6 votes |
public static boolean testLabel(CommandSender sender, SentinelTargetLabel label) { if (!label.isValidTarget()) { sender.sendMessage(SentinelCommand.prefixBad + "Invalid target! See the readme for a list of valid targets."); return false; } if (!label.isValidRegex()) { sender.sendMessage(SentinelCommand.prefixBad + "Bad regular expression!"); return false; } if (!label.isValidPrefix()) { sender.sendMessage(SentinelCommand.prefixBad + "The target prefix '" + label.prefix + "' is unknown!"); return false; } if (!label.isValidMulti()) { sender.sendMessage(SentinelCommand.prefixBad + "The multi-target '" + label.value + "' is invalid (targets within don't exist?)!"); return false; } return true; }
Example #6
Source File: CommandGuildPvpToggle.java From NovaGuilds with GNU General Public License v3.0 | 6 votes |
@Override public void execute(CommandSender sender, String[] args) throws Exception { NovaPlayer nPlayer = PlayerManager.getPlayer(sender); if(!nPlayer.hasGuild()) { Message.CHAT_GUILD_NOTINGUILD.send(sender); return; } if(!nPlayer.hasPermission(GuildPermission.PVPTOGGLE)) { Message.CHAT_GUILD_NOGUILDPERM.send(sender); return; } nPlayer.getGuild().setFriendlyPvp(!nPlayer.getGuild().getFriendlyPvp()); TabUtils.refresh(nPlayer.getGuild()); Message.CHAT_GUILD_FPVPTOGGLED.clone().setVar(VarKey.GUILD_PVP, Message.getOnOff(nPlayer.getGuild().getFriendlyPvp())).send(sender); }
Example #7
Source File: CommandHandlerTest.java From AuthMeReloaded with GNU General Public License v3.0 | 6 votes |
@Test public void shouldNotCallExecutableForFailedParsing() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; CommandSender sender = mock(CommandSender.class); CommandDescription command = mock(CommandDescription.class); given(commandMapper.mapPartsToCommand(any(CommandSender.class), anyList())).willReturn( new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, MISSING_BASE_COMMAND)); // when handler.processCommand(sender, bukkitLabel, bukkitArgs); // then verify(commandMapper).mapPartsToCommand(sender, asList("unreg", "testPlayer")); verify(command, never()).getExecutableCommand(); verify(sender).sendMessage(argThat(containsString("Failed to parse"))); }
Example #8
Source File: NickCommands.java From NickNamer with MIT License | 6 votes |
@Command(name = "refreshNick", aliases = { "nickrefresh", "refreshskin", "reloadskin", "reloadnick" }, usage = "[Player]", description = "Refresh the displayed skin", min = 0, max = 1) @Permission("nick.command.refresh") public void refreshNick(final CommandSender sender, @OptionalArg String targetName) { boolean otherTarget = targetName != null && !targetName.isEmpty(); final CommandUtil.TargetInfo target = CommandUtil.findTargetInfo(sender, targetName, otherTarget, plugin.allowOfflineTargets); if (target == null) { return; } if (otherTarget && !sender.hasPermission("nick.other")) { throw new PermissionException("nick.other"); } NickNamerAPI.getNickManager().refreshPlayer(target.uuid); }
Example #9
Source File: HelpCommandTest.java From AuthMeReloaded with GNU General Public License v3.0 | 6 votes |
@Test public void shouldShowDetailedHelpForChildCommand() { List<String> arguments = asList("authme", "getpos"); CommandSender sender = mock(CommandSender.class); CommandDescription commandDescription = mock(CommandDescription.class); given(commandDescription.getLabelCount()).willReturn(2); FoundCommandResult foundCommandResult = new FoundCommandResult(commandDescription, asList("authme", "getpos"), Collections.emptyList(), 0.0, INCORRECT_ARGUMENTS); given(commandMapper.mapPartsToCommand(sender, arguments)).willReturn(foundCommandResult); // when command.executeCommand(sender, arguments); // then verify(sender, never()).sendMessage(anyString()); verify(helpProvider).outputHelp(sender, foundCommandResult, HelpProvider.ALL_OPTIONS); }
Example #10
Source File: SentinelTargetCommands.java From Sentinel with MIT License | 6 votes |
@Command(aliases = {"sentinel"}, usage = "removeignore TYPE", desc = "Allows targeting a target.", modifiers = {"removeignore"}, permission = "sentinel.removeignore", min = 2, max = 2) @Requirements(livingEntity = true, ownership = true, traits = {SentinelTrait.class}) public void removeIgnore(CommandContext args, CommandSender sender, SentinelTrait sentinel) { SentinelTargetLabel targetLabel = new SentinelTargetLabel(args.getString(1)); if (!testLabel(sender, targetLabel)) { return; } if (targetLabel.removeFromList(sentinel.allIgnores)) { sender.sendMessage(SentinelCommand.prefixGood + "No longer ignoring that target!"); } else { sender.sendMessage(SentinelCommand.prefixBad + "Was already not ignoring that target!"); } }
Example #11
Source File: ResourcePackCommand.java From DungeonsXL with GNU General Public License v3.0 | 6 votes |
@Override public void onExecute(String[] args, CommandSender sender) { Player player = (Player) sender; if (args[1].equalsIgnoreCase("reset")) { // Placeholder to reset to default player.setResourcePack("http://google.com"); return; } String url = (String) config.getResourcePacks().get(args[1]); if (url == null) { MessageUtil.sendMessage(sender, DMessage.ERROR_NO_SUCH_RESOURCE_PACK.getMessage(args[1])); return; } player.setResourcePack(url); }
Example #12
Source File: CommandAdminGuildPurge.java From NovaGuilds with GNU General Public License v3.0 | 6 votes |
@Override public void execute(CommandSender sender, String[] args) throws Exception { if(plugin.getGuildManager().getGuilds().isEmpty()) { Message.CHAT_GUILD_NOGUILDS.send(sender); return; } for(NovaGuild guild : new ArrayList<>(plugin.getGuildManager().getGuilds())) { //fire event GuildAbandonEvent guildAbandonEvent = new GuildAbandonEvent(guild, AbandonCause.ADMIN_ALL); ListenerManager.getLoggedPluginManager().callEvent(guildAbandonEvent); //if event is not cancelled if(!guildAbandonEvent.isCancelled()) { //delete guild plugin.getGuildManager().delete(guildAbandonEvent); Map<VarKey, String> vars = new HashMap<>(); vars.put(VarKey.PLAYER_NAME, sender.getName()); vars.put(VarKey.GUILD_NAME, guild.getName()); Message.BROADCAST_ADMIN_GUILD_ABANDON.clone().vars(vars).broadcast(); } } }
Example #13
Source File: CommandCombatLogX.java From CombatLogX with GNU General Public License v3.0 | 6 votes |
private boolean reloadConfigCommand(CommandSender sender) { if(checkNoPermission(sender, "combatlogx.command.combatlogx.reload")) return true; try { this.plugin.reloadConfig("config.yml"); this.plugin.reloadConfig("language.yml"); ExpansionManager expansionManager = this.plugin.getExpansionManager(); expansionManager.reloadExpansionConfigs(); } catch(Exception ex) { String message1 = MessageUtil.color("&f&l[&6CombatLogX&f&l] &cAn error has occurred while loading your configurations. &cPlease check console for further details."); String message2 = MessageUtil.color("&f&l[&6CombatLogX&f&l[ &c&lError Message: &7" + ex.getMessage()); this.plugin.sendMessage(sender, message1, message2); ex.printStackTrace(); return true; } String message = this.plugin.getLanguageMessageColoredWithPrefix("commands.combatlogx.reloaded"); this.plugin.sendMessage(sender, message); return true; }
Example #14
Source File: MapPoolAdjustEvent.java From PGM with GNU Affero General Public License v3.0 | 6 votes |
public MapPoolAdjustEvent( MapPool oldMapPool, MapPool newMapPool, Match match, boolean forced, @Nullable CommandSender sender, @Nullable Duration timeLimit, int matchLimit) { this.oldPool = oldMapPool; this.newPool = newMapPool; this.match = match; this.forced = forced; this.sender = sender; this.timeLimit = timeLimit; this.matchLimit = matchLimit; }
Example #15
Source File: SentinelTargetCommands.java From Sentinel with MIT License | 6 votes |
@Command(aliases = {"sentinel"}, usage = "removetarget TYPE", desc = "Removes a target.", modifiers = {"removetarget"}, permission = "sentinel.removetarget", min = 2, max = 2) @Requirements(livingEntity = true, ownership = true, traits = {SentinelTrait.class}) public void removeTarget(CommandContext args, CommandSender sender, SentinelTrait sentinel) { SentinelTargetLabel targetLabel = new SentinelTargetLabel(args.getString(1)); if (!testLabel(sender, targetLabel)) { return; } if (targetLabel.removeFromList(sentinel.allTargets)) { sender.sendMessage(SentinelCommand.prefixGood + "No longer tracking that target!"); } else { sender.sendMessage(SentinelCommand.prefixBad + "Was already not tracking that target!"); } }
Example #16
Source File: AsynchronousUnregisterTest.java From AuthMeReloaded with GNU General Public License v3.0 | 6 votes |
@Test public void shouldPerformAdminUnregister() { // given Player player = mock(Player.class); String name = "Frank21"; given(player.isOnline()).willReturn(true); given(dataSource.removeAuth(name)).willReturn(true); given(service.getProperty(RegistrationSettings.FORCE)).willReturn(true); given(service.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)).willReturn(false); CommandSender initiator = mock(CommandSender.class); setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); // when asynchronousUnregister.adminUnregister(initiator, name, player); // then verify(service).send(player, MessageKey.UNREGISTERED_SUCCESS); verify(service).send(initiator, MessageKey.UNREGISTERED_SUCCESS); verify(dataSource).removeAuth(name); verify(playerCache).removePlayer(name); verify(teleportationService).teleportOnJoin(player); verifyCalledUnregisterEventFor(player); verify(commandManager).runCommandsOnUnregister(player); verify(bungeeSender).sendAuthMeBungeecordMessage(MessageType.UNREGISTER, name); }
Example #17
Source File: RandomTeleportCommand.java From RandomTeleport with GNU General Public License v3.0 | 5 votes |
private static Location getLocation(CommandSender sender) { if (sender instanceof Entity) { return ((Entity) sender).getLocation(); } else if (sender instanceof BlockCommandSender) { return ((BlockCommandSender) sender).getBlock().getLocation(); } return new Location(Bukkit.getWorlds().get(0), 0, 0, 0); }
Example #18
Source File: TimingCommand.java From LagMonitor with MIT License | 5 votes |
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!canExecute(sender, command)) { return true; } if (isTimingsEnabled()) { sendError(sender,"The server deactivated timing reports"); sendError(sender,"Go to paper.yml or spigot.yml and activate timings"); return true; } return true; }
Example #19
Source File: SpigotMapperTest.java From Chimera with MIT License | 5 votes |
@Test void requirement() { assertSame(SpigotMapper.TRUE, mapper.requirement(Literal.of("a").requires(null).build())); Predicate<CommandSender> predicate = mock(Predicate.class); mapper.requirement(Literal.of("a").requires(predicate).build()).test(listener); verify(predicate).test(sender); }
Example #20
Source File: CrackedCommand.java From FastLogin with MIT License | 5 votes |
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length == 0) { onCrackedSelf(sender, command, args); } else { onCrackedOther(sender, command, args); } return true; }
Example #21
Source File: SwitchAntiBotCommandTest.java From AuthMeReloaded with GNU General Public License v3.0 | 5 votes |
@Test public void shouldReturnAntiBotState() { // given given(antiBot.getAntiBotStatus()).willReturn(AntiBotService.AntiBotStatus.ACTIVE); CommandSender sender = mock(CommandSender.class); // when command.executeCommand(sender, Collections.emptyList()); // then verify(sender).sendMessage(argThat(containsString("status: ACTIVE"))); }
Example #22
Source File: PunishmentCommands.java From ProjectAres with GNU Affero General Public License v3.0 | 5 votes |
@Command( aliases = { "w", "warn" }, flags = "aso", usage = "<player> <reason>", desc = "Warn a player for a reason.", min = 2 ) public void warn(CommandContext args, CommandSender sender) throws CommandException { create(args, sender, WARN, null); }
Example #23
Source File: StartCommands.java From ProjectAres with GNU Affero General Public License v3.0 | 5 votes |
@Command( aliases = {"start", "begin"}, desc = "Queues the start of the match in a certain amount of seconds", usage = "[countdown time] [huddle time]", min = 0, max = 2 ) @CommandPermissions("pgm.start") public static void start(CommandContext args, CommandSender sender) throws CommandException { Match match = CommandUtils.getMatch(sender); StartMatchModule smm = CommandUtils.getMatchModule(StartMatchModule.class, sender); switch(match.matchState()) { case Idle: case Starting: case Huddle: if(smm.canStart(true)) { smm.forceStartCountdown(getDuration(args, 0), getDuration(args, 1)); } else { ComponentRenderers.send(sender, new Component(new TranslatableComponent("command.admin.start.unknownState"), ChatColor.RED)); for(UnreadyReason reason : smm.getUnreadyReasons(true)) { ComponentRenderers.send(sender, new Component(ChatColor.RED).text(" * ").extra(reason.getReason())); } } break; case Running: throw new CommandException(PGMTranslations.get().t("command.admin.start.matchRunning", sender)); case Finished: throw new CommandException(PGMTranslations.get().t("command.admin.start.matchFinished", sender)); default: throw new CommandException(PGMTranslations.get().t("command.admin.start.unknownState", sender)); } }
Example #24
Source File: PerworldInventoryCommandHandlingTest.java From PerWorldInventory with GNU General Public License v3.0 | 5 votes |
@Test public void shouldRunMainCommand() { // given CommandSender sender = mock(CommandSender.class); Command command = newCommandWithName("pwi"); // when boolean result = plugin.onCommand(sender, command, "pwi"); // then assertThat(result, equalTo(true)); verify(pwiCommand).executeCommand(sender, Collections.emptyList()); }
Example #25
Source File: NMS_1_16_R1.java From 1.13-Command-API with Apache License 2.0 | 5 votes |
@Override public Location getLocation(CommandContext cmdCtx, String str, LocationType locationType, CommandSender sender) throws CommandSyntaxException { switch (locationType) { case BLOCK_POSITION: BlockPosition blockPos = ArgumentPosition.a(cmdCtx, str); return new Location(getCommandSenderWorld(sender), blockPos.getX(), blockPos.getY(), blockPos.getZ()); case PRECISE_POSITION: Vec3D vecPos = ArgumentVec3.a(cmdCtx, str); return new Location(getCommandSenderWorld(sender), vecPos.x, vecPos.y, vecPos.z); } return null; }
Example #26
Source File: HubBasicsCommand.java From HubBasics with GNU Lesser General Public License v3.0 | 5 votes |
@Override protected void execute(CommandSender sender, String[] args) { if (args.length == 0) { HubBasics.getMessenger().send(sender, getHelp()); } else if (args.length == 1) { if (args[0].equalsIgnoreCase("reload")) { // Disable HubBasics.getConfigManager().onDisable(); HubBasics.getModuleManager().onDisable(); HubBasics.getItemManager().onDisable(); HubBasics.getMenuManager().onDisable(); // Enable HubBasics.getModuleManager().onEnable(); HubBasics.getItemManager().onEnable(); HubBasics.getMenuManager().onEnable(); // Message HubBasics.getMessenger().send(sender, Messages.get(sender, "PLUGIN_RELOADED")); } else if (args[0].equalsIgnoreCase("version")) { HubBasics.getMessenger().send(sender, Messages.get(sender, "PLUGIN_VERSION", HubBasics.getDescription().getVersion())); } else { HubBasics.getMessenger().send(sender, Messages.get(sender, "UNKNOWN_SUBCOMMAND")); } } else if (args.length == 2) { if (args[0].equalsIgnoreCase("item") && (sender instanceof Player)) { Player player = (Player) sender; String name = args[1]; CustomItem item = HubBasics.getItemManager().get(name); if (item == null) { HubBasics.getMessenger().send(player, Messages.get(player, "ITEM_NOT_FOUND")); return; } player.getInventory().addItem(item.toItemStack(player)); } else { HubBasics.getMessenger().send(sender, Messages.get(sender, "UNKNOWN_SUBCOMMAND")); } } }
Example #27
Source File: MutableTest.java From Chimera with MIT License | 5 votes |
@ParameterizedTest @MethodSource("mutables") void setRedirect(Mutable<CommandSender> mutable) { var destination = Literal.of("child").build(); mutable.setRedirect(destination); assertEquals(destination, ((CommandNode<?>) mutable).getRedirect()); if (mutable instanceof Aliasable<?>) { assertEquals(destination, ((Aliasable<CommandSender>) mutable).aliases().get(0).getRedirect()); } }
Example #28
Source File: VaultManager.java From PlayerVaults with GNU General Public License v3.0 | 5 votes |
/** * Deletes a players vault. * * @param sender The sender of whom to send messages to. * @param holder The vault holder. * @param number The vault number. * @throws IOException Uh oh! */ public void deleteVault(CommandSender sender, final String holder, final int number) { new BukkitRunnable() { @Override public void run() { File file = new File(directory, holder + ".yml"); if (!file.exists()) { return; } YamlConfiguration playerFile = YamlConfiguration.loadConfiguration(file); if (file.exists()) { playerFile.set(String.format(VAULTKEY, number), null); if (cachedVaultFiles.containsKey(holder)) { cachedVaultFiles.put(holder, playerFile); } try { playerFile.save(file); } catch (IOException ignored) { } } } }.runTaskAsynchronously(PlayerVaults.getInstance()); OfflinePlayer player = Bukkit.getPlayer(holder); if (player != null) { if (sender.getName().equalsIgnoreCase(player.getName())) { sender.sendMessage(Lang.TITLE.toString() + Lang.DELETE_VAULT.toString().replace("%v", String.valueOf(number))); } else { sender.sendMessage(Lang.TITLE.toString() + Lang.DELETE_OTHER_VAULT.toString().replace("%v", String.valueOf(number)).replaceAll("%p", player.getName())); } } String vaultName = sender instanceof Player ? ((Player) sender).getUniqueId().toString() : holder; PlayerVaults.getInstance().getOpenInventories().remove(new VaultViewInfo(vaultName, number).toString()); }
Example #29
Source File: WrappedCommand.java From mcspring-boot with MIT License | 5 votes |
@Override public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { if (args.length == 0) return Collections.emptyList(); return context.runWithSender(sender, () -> { Stream<String> possibleSubcommands = CommandUtils.getPossibleSubcommands(commandSpec, args); Stream<String> possibleArguments = CommandUtils.getPossibleArguments(commandSpec, args); return Stream.concat(possibleSubcommands, possibleArguments).collect(Collectors.toList()); }); }
Example #30
Source File: CivChatCommand.java From civcraft with GNU General Public License v2.0 | 5 votes |
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { //TODO let non players use this command if ((sender instanceof Player) == false) { return false; } Player player = (Player)sender; Resident resident = CivGlobal.getResident(player); if (resident == null) { CivMessage.sendError(sender, "You are not a resident? Relogin please.."); return false; } if (args.length == 0) { resident.setCivChat(!resident.isCivChat()); resident.setTownChat(false); CivMessage.sendSuccess(sender, "Civ chat mode set to "+resident.isCivChat()); return true; } String fullArgs = ""; for (String arg : args) { fullArgs += arg + " "; } if (resident.getTown() == null) { player.sendMessage(CivColor.Rose+"You are not part of a civ, nobody hears you."); return false; } CivMessage.sendCivChat(resident.getTown().getCiv(), resident, "<%s> %s", fullArgs); return true; }