use of org.spongepowered.api.command.CommandSource in project Nucleus by NucleusPowered.
the class GameruleCommand method executeCommand.
@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
WorldProperties worldProperties = getWorldFromUserOrArgs(src, worldKey, args);
Map<String, String> gameRules = worldProperties.getGameRules();
String message = plugin.getMessageProvider().getMessageWithFormat("command.world.gamerule.key");
List<Text> text = gameRules.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).map(x -> Text.of(TextActions.suggestCommand(String.format("/world gamerule set %s %s ", worldProperties.getWorldName(), x.getKey())), TextSerializers.FORMATTING_CODE.deserialize(MessageFormat.format(message, x.getKey(), x.getValue())))).collect(Collectors.toList());
Util.getPaginationBuilder(src).title(plugin.getMessageProvider().getTextMessageWithFormat("command.world.gamerule.header", worldProperties.getWorldName())).contents(text).sendTo(src);
return CommandResult.success();
}
use of org.spongepowered.api.command.CommandSource in project Nucleus by NucleusPowered.
the class CheckWarningsCommand method executeCommand.
@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
User user = args.<User>getOne(playerKey).get();
handler.updateWarnings(user);
List<WarnData> warnings;
final List<WarnData> allWarnings = handler.getWarningsInternal(user);
if (args.hasAny("all")) {
warnings = allWarnings;
} else if (args.hasAny("expired")) {
warnings = allWarnings.stream().filter(WarnData::isExpired).collect(Collectors.toList());
} else {
warnings = allWarnings.stream().filter(x -> !x.isExpired()).collect(Collectors.toList());
}
if (warnings.isEmpty()) {
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.checkwarnings.none", user.getName()));
return CommandResult.success();
}
List<Text> messages = warnings.stream().sorted(Comparator.comparing(WarnData::getDate)).map(x -> createMessage(allWarnings, x, user)).collect(Collectors.toList());
messages.add(0, plugin.getMessageProvider().getTextMessageWithFormat("command.checkwarnings.info"));
PaginationService paginationService = Sponge.getGame().getServiceManager().provideUnchecked(PaginationService.class);
paginationService.builder().title(Text.builder().color(TextColors.GOLD).append(Text.of(plugin.getMessageProvider().getMessageWithFormat("command.checkwarnings.header", user.getName()))).build()).padding(Text.builder().color(TextColors.YELLOW).append(Text.of("=")).build()).contents(messages).sendTo(src);
return CommandResult.success();
}
use of org.spongepowered.api.command.CommandSource in project Nucleus by NucleusPowered.
the class WarnCommand method executeCommand.
@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
final User user = args.<User>getOne(playerKey).get();
Optional<Long> optDuration = args.getOne(durationKey);
String reason = args.<String>getOne(reasonKey).get();
if (permissions.testSuffix(user, "exempt.target", src, false)) {
throw ReturnMessageException.fromKey("command.warn.exempt", user.getName());
}
// Set default duration if no duration given
if (warnConfig.getDefaultLength() != -1 && !optDuration.isPresent()) {
optDuration = Optional.of(warnConfig.getDefaultLength());
}
UUID warner = Util.getUUID(src);
WarnData warnData = optDuration.map(aLong -> new WarnData(Instant.now(), warner, reason, Duration.ofSeconds(aLong))).orElseGet(() -> new WarnData(Instant.now(), warner, reason));
// Check if too long (No duration provided, it is infinite)
if (!optDuration.isPresent() && warnConfig.getMaximumWarnLength() != -1 && !permissions.testSuffix(src, "exempt.length")) {
throw ReturnMessageException.fromKey("command.warn.length.toolong", Util.getTimeStringFromSeconds(warnConfig.getMaximumWarnLength()));
}
// Check if too long
if (optDuration.orElse(Long.MAX_VALUE) > warnConfig.getMaximumWarnLength() && warnConfig.getMaximumWarnLength() != -1 && !permissions.testSuffix(src, "exempt.length")) {
throw ReturnMessageException.fromKey("command.warn.length.toolong", Util.getTimeStringFromSeconds(warnConfig.getMaximumWarnLength()));
}
// Check if too short
if (optDuration.orElse(Long.MAX_VALUE) < warnConfig.getMinimumWarnLength() && warnConfig.getMinimumWarnLength() != -1 && !permissions.testSuffix(src, "exempt.length")) {
throw ReturnMessageException.fromKey("command.warn.length.tooshort", Util.getTimeStringFromSeconds(warnConfig.getMinimumWarnLength()));
}
if (handler.addWarning(user, warnData)) {
MutableMessageChannel messageChannel = new PermissionMessageChannel(permissions.getPermissionWithSuffix("notify")).asMutable();
messageChannel.addMember(src);
if (optDuration.isPresent()) {
String time = Util.getTimeStringFromSeconds(optDuration.get());
messageChannel.send(plugin.getMessageProvider().getTextMessageWithFormat("command.warn.success.time", user.getName(), src.getName(), warnData.getReason(), time));
if (user.isOnline()) {
user.getPlayer().get().sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("warn.playernotify.time", warnData.getReason(), time));
}
} else {
messageChannel.send(plugin.getMessageProvider().getTextMessageWithFormat("command.warn.success.norm", user.getName(), src.getName(), warnData.getReason()));
if (user.isOnline()) {
user.getPlayer().get().sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("warn.playernotify.standard", warnData.getReason()));
}
}
// Check if the subject has action command should be executed
if (warnConfig.getWarningsBeforeAction() != -1) {
if (handler.getWarningsInternal(user, true, false).size() < warnConfig.getWarningsBeforeAction()) {
return CommandResult.success();
}
// Expire all active warnings
// The cause is the plugin, as this isn't directly the warning user.
CauseStackHelper.createFrameWithCausesWithConsumer(c -> handler.clearWarnings(user, false, false, c), src);
// Get and run the action command
String command = warnConfig.getActionCommand().replaceAll("\\{\\{name}}", user.getName());
Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command);
}
return CommandResult.success();
}
throw ReturnMessageException.fromKey("command.warn.fail", user.getName());
}
use of org.spongepowered.api.command.CommandSource in project Nucleus by NucleusPowered.
the class CommandBaseTests method testThatCommandSourcesCanExecuteStandardCommand.
/**
* Tests that if a {@link CommandSource} that is not a player is provided, they can execute a standard command.
*
* @throws CommandException
*/
@Test
public void testThatCommandSourcesCanExecuteStandardCommand() throws CommandException {
BasicCommand cmd = new BasicCommand();
getInjector().injectMembers(cmd);
cmd.postInit();
CommandSource mock = getMockCommandSource();
CommandResult result = cmd.process(mock, "");
Assert.assertTrue("There should have been one success!", result.getSuccessCount().orElse(0) == 1);
}
use of org.spongepowered.api.command.CommandSource in project Nucleus by NucleusPowered.
the class NucleusTokenServiceImpl method getTextFromToken.
private Optional<Text> getTextFromToken(String token, CommandSource source, Map<String, Object> variables) {
token = token.toLowerCase().trim().replace("{{", "").replace("}}", "");
Matcher m = suffixPattern.matcher(token);
boolean addSpace = false;
boolean prependSpace = false;
if (m.find(0)) {
String match = m.group(1).toLowerCase();
addSpace = match.contains("s");
prependSpace = match.contains("p");
token = token.replaceAll(":[sp]+$", "");
}
try {
Optional<Text> toReturn;
if (token.startsWith("pl:") || token.startsWith("p:")) {
// Plugin identifiers are of the form pl:<pluginid>:<identifier>
String[] tokSplit = token.split(":", 3);
if (tokSplit.length < 3) {
return EMPTY;
}
toReturn = applyToken(tokSplit[1], tokSplit[2], source, variables);
} else if (token.startsWith("o:")) {
// Option identifier.
toReturn = getTextFromOption(source, token.substring(2));
} else {
// Standard.
toReturn = applyPrimaryToken(token, source, variables);
}
if (addSpace) {
toReturn = toReturn.map(x -> x.isEmpty() ? x : Text.join(x, Util.SPACE));
}
if (prependSpace) {
toReturn = toReturn.map(x -> x.isEmpty() ? x : Text.join(Util.SPACE, x));
}
return toReturn;
} catch (Exception e) {
if (plugin.isDebugMode()) {
e.printStackTrace();
}
return EMPTY;
}
}
Aggregations