use of org.spongepowered.api.command.args.CommandContext in project Nucleus by NucleusPowered.
the class AvailableBaseCommand method executeCommand.
@Override
protected CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
MessageProvider mp = Nucleus.getNucleus().getMessageProvider();
List<Text> types = Sponge.getRegistry().getAllOf(this.catalogType).stream().map(x -> mp.getTextMessageWithFormat("command.world.presets.item", x.getId(), x.getName())).collect(Collectors.toList());
Util.getPaginationBuilder(src).title(mp.getTextMessageWithTextFormat(this.titleKey)).contents(types).sendTo(src);
return CommandResult.success();
}
use of org.spongepowered.api.command.args.CommandContext in project Nucleus by NucleusPowered.
the class AFKCommandInterceptor method onPostCommand.
@Override
public void onPostCommand(Class<? extends AbstractCommand<?>> commandClass, CommandSource source, CommandContext context, CommandResult result) {
if (this.send && result.getSuccessCount().orElse(0) > 0 && commandClass.isAnnotationPresent(NotifyIfAFK.class)) {
NotifyIfAFK annotation = commandClass.getAnnotation(NotifyIfAFK.class);
Cause cause = CauseStackHelper.createCause(source);
for (String key : annotation.value()) {
context.getAll(key).stream().filter(x -> x instanceof User).map(x -> ((User) x).getPlayer().orElse(null)).filter(Objects::nonNull).filter(this.handler::isAFK).forEach(x -> {
Text messageToSend = this.message == null ? null : message.getForCommandSource(x);
AFKEvents.Notify event = new AFKEvents.Notify(x, messageToSend, cause);
Sponge.getEventManager().post(event);
event.getMessage().ifPresent(source::sendMessage);
});
}
}
}
use of org.spongepowered.api.command.args.CommandContext in project Nucleus by NucleusPowered.
the class AbstractCommand method process.
private CommandResult process(CommandSource source, String command, String arguments, CommandArgs args) throws CommandException {
// Phase one: child command processing. Keep track of all thrown arguments.
List<Tuple<String, CommandException>> thrown = Lists.newArrayList();
final CommandContext context = new CommandContext();
T castedSource;
try {
// If we have a child command to execute, then we execute it.
if (args.hasNext() && this.dispatcher.containsAlias(args.peek())) {
Object state = args.getState();
String next = args.next();
try {
// If this works, then we're A-OK.
CommandCallable callable = this.dispatcher.get(next.toLowerCase()).get().getCallable();
if (callable instanceof AbstractCommand) {
return ((AbstractCommand) callable).process(source, command + " " + next, arguments, args);
}
return callable.process(source, arguments);
} catch (NucleusCommandException e) {
// Didn't work out. Let's move on.
thrown.addAll(e.getExceptions());
if (!e.isAllowFallback()) {
throw e;
}
} catch (CommandException e) {
// If the Exception is _not_ of right type, wrap it and add it. This shouldn't happen though.
thrown.add(Tuple.of(command + " " + next, e));
} finally {
args.setState(state);
}
}
// Phase one: test for what is required
if (requiresEconomy && !plugin.getEconHelper().economyServiceExists()) {
source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("command.economyrequired"));
return CommandResult.empty();
}
// Phase two: source type - test to see if the person in question can execute this command.
castedSource = checkSourceType(source);
// Phase three - test the permission.
if (!testPermissionOnSubject(castedSource)) {
throw new CommandPermissionException();
}
if (!this.hasExecutor) {
if (thrown.isEmpty()) {
// OK, we just process the usage command instead.
return this.usageCommand.process(source, "", args.nextIfPresent().map(String::toLowerCase).orElse(null));
} else {
throw new NucleusCommandException(thrown);
}
}
// Phase four - create the context and parse the arguments.
this.argumentParser.parse(source, args, context);
if (args.hasNext()) {
thrown.add(Tuple.of(command, new NucleusArgumentParseException(Text.of(TextColors.RED, "Too many arguments"), args.getRaw(), args.getRawPosition(), Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null), true)));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
}
} catch (NucleusCommandException nce) {
throw nce;
} catch (ArgumentParseException ape) {
// get the command to get the usage/subs from.
thrown.add(Tuple.of(command, NucleusArgumentParseException.from(ape, Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null))));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
} catch (CommandException ex) {
// Errors at this point are expected, so we'll run with it - no need for debug mode checks.
thrown.add(Tuple.of(command, ex));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
} catch (Throwable throwable) {
String m;
if (throwable.getMessage() == null) {
m = "null";
} else {
m = throwable.getMessage();
}
thrown.add(Tuple.of(command, new CommandException(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.exception.unexpected", m), throwable)));
// this is on demand, so we should throw it.
throwable.printStackTrace();
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
}
try {
commandTimings.startTimingIfSync();
ContinueMode mode = preProcessChecks(castedSource, context);
if (!mode.cont) {
return mode.returnType;
}
if (castedSource instanceof Player) {
@SuppressWarnings("unchecked") ContinueMode cm = runChecks((Player) castedSource, context);
if (!cm.cont) {
return cm.returnType;
}
}
// If we're running async...
if (isAsync) {
// Create an executor that runs the command async.
plugin.getLogger().debug("Running " + this.getClass().getName() + " in async mode.");
Sponge.getScheduler().createAsyncExecutor(plugin).execute(() -> onExecute(castedSource, context));
// Tell Sponge we're done.
return CommandResult.success();
}
return onExecute(castedSource, context);
} finally {
commandTimings.stopTimingIfSync();
}
}
use of org.spongepowered.api.command.args.CommandContext in project Nucleus by NucleusPowered.
the class BroadcastCommand method executeCommand.
@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
String m = args.<String>getOne(message).get();
NucleusTextTemplate textTemplate = NucleusTextTemplateFactory.createFromAmpersandString(m);
Text p = bc.getPrefix().getForCommandSource(src);
Text s = bc.getSuffix().getForCommandSource(src);
new NucleusTextTemplateMessageSender(textTemplate, src, t -> TextParsingUtils.joinTextsWithColoursFlowing(p, t, s)).send();
return CommandResult.success();
}
use of org.spongepowered.api.command.args.CommandContext in project Nucleus by NucleusPowered.
the class EnchantCommand method executeCommand.
@Override
public CommandResult executeCommand(Player src, CommandContext args) throws Exception {
// Check for item in hand
if (!src.getItemInHand(HandTypes.MAIN_HAND).isPresent()) {
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.noitem"));
return CommandResult.empty();
}
// Get the arguments
ItemStack itemInHand = src.getItemInHand(HandTypes.MAIN_HAND).get();
EnchantmentType enchantment = args.<EnchantmentType>getOne(enchantmentKey).get();
int level = args.<Integer>getOne(levelKey).get();
boolean allowUnsafe = args.hasAny("u");
boolean allowOverwrite = args.hasAny("o");
// Can we apply the enchantment?
if (!allowUnsafe) {
if (!enchantment.canBeAppliedToStack(itemInHand)) {
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.nounsafe.enchant", itemInHand.getTranslation().get()));
return CommandResult.empty();
}
if (level > enchantment.getMaximumLevel()) {
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.nounsafe.level", itemInHand.getTranslation().get()));
return CommandResult.empty();
}
}
// We know this should exist.
EnchantmentData ed = itemInHand.getOrCreate(EnchantmentData.class).get();
// Get all the enchantments.
List<Enchantment> currentEnchants = ed.getListValue().get();
List<Enchantment> enchantmentsToRemove = currentEnchants.stream().filter(x -> !x.getType().isCompatibleWith(enchantment) || x.getType().equals(enchantment)).collect(Collectors.toList());
if (!allowOverwrite && !enchantmentsToRemove.isEmpty()) {
// Build the list of the enchantment names, and send it.
final StringBuilder sb = new StringBuilder();
enchantmentsToRemove.forEach(x -> {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(Util.getTranslatableIfPresent(x.getType()));
});
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.overwrite", sb.toString()));
return CommandResult.empty();
}
// Remove all enchants that cannot co-exist.
currentEnchants.removeIf(enchantmentsToRemove::contains);
// Create the enchantment
currentEnchants.add(Enchantment.of(enchantment, level));
ed.setElements(currentEnchants);
// Offer it to the item.
DataTransactionResult dtr = itemInHand.offer(ed);
if (dtr.isSuccessful()) {
// If successful, we need to put the item in the player's hand for it to actually take effect.
src.setItemInHand(HandTypes.MAIN_HAND, itemInHand);
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.success", Util.getTranslatableIfPresent(enchantment), String.valueOf(level)));
return CommandResult.success();
}
src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.error", Util.getTranslatableIfPresent(enchantment), String.valueOf(level)));
return CommandResult.empty();
}
Aggregations