use of net.robinfriedli.aiode.command.AbstractCommand in project aiode by robinfriedli.
the class GuildPropertyInterceptor method updatePresets.
private void updatePresets(AbstractGuildProperty argumentPrefixProperty, Character oldArgumentPrefix, char newArgumentPrefix, Session session) {
List<Preset> presets = queryBuilderFactory.find(Preset.class).build(session).getResultList();
String defaultValue = argumentPrefixProperty.getDefaultValue();
char[] chars = defaultValue.toCharArray();
char defaultArgPrefix;
if (chars.length == 1) {
defaultArgPrefix = chars[0];
} else {
defaultArgPrefix = ArgumentPrefixProperty.DEFAULT_FALLBACK;
}
char argPrefix = oldArgumentPrefix != null ? oldArgumentPrefix : defaultArgPrefix;
ArgumentPrefixProperty.Config argumentPrefixConfig = new ArgumentPrefixProperty.Config(argPrefix, defaultArgPrefix);
for (Preset preset : presets) {
Aiode aiode = Aiode.get();
AbstractCommand command = preset.instantiateCommand(aiode.getCommandManager(), commandContext, preset.getName());
String oldPreset = preset.getPreset();
StringBuilder newPresetBuilder = new StringBuilder(oldPreset);
List<Integer> oldPrefixOccurrences = Lists.newArrayList();
CommandParser commandParser = new CommandParser(command, argumentPrefixConfig, new CommandParseListener() {
@Override
public void onModeSwitch(CommandParser.Mode previousMode, CommandParser.Mode newMode, int index, char character) {
// they are in fact argument prefixes
if (newMode instanceof ArgumentBuildingMode) {
oldPrefixOccurrences.add(index);
}
}
});
commandParser.parse(oldPreset);
for (int oldPrefixOccurrence : oldPrefixOccurrences) {
newPresetBuilder.setCharAt(oldPrefixOccurrence, newArgumentPrefix);
}
String newPreset = newPresetBuilder.toString();
if (!oldPreset.equals(newPreset)) {
preset.setPreset(newPreset);
}
}
}
use of net.robinfriedli.aiode.command.AbstractCommand in project aiode by robinfriedli.
the class CommandListener method startCommandExecution.
private void startCommandExecution(String namePrefix, Message message, Guild guild, GuildContext guildContext, Session session, GuildMessageReceivedEvent event) {
ThreadExecutionQueue queue = executionQueueManager.getForGuild(guild);
String commandBody = message.getContentDisplay().substring(namePrefix.length()).trim();
CommandContext commandContext = new CommandContext(event, guildContext, hibernateComponent.getSessionFactory(), spotifyApiBuilder, commandBody);
ExecutionContext.Current.set(commandContext.fork());
try {
Optional<AbstractCommand> commandInstance = commandManager.instantiateCommandForContext(commandContext, session);
commandInstance.ifPresent(command -> commandManager.runCommand(command, queue));
} catch (UserException e) {
EmbedBuilder embedBuilder = e.buildEmbed();
messageService.sendTemporary(embedBuilder.build(), commandContext.getChannel());
}
}
use of net.robinfriedli.aiode.command.AbstractCommand in project aiode by robinfriedli.
the class PresetCommand method doRun.
@Override
public void doRun() {
Session session = getContext().getSession();
if (argumentSet("delete")) {
Preset preset = SearchEngine.searchPreset(session, getCommandInput());
if (preset == null) {
throw new InvalidCommandException(String.format("No preset found for '%s'", getCommandInput()));
}
invoke(() -> session.delete(preset));
} else if (getCommandInput().isBlank()) {
List<Preset> presets = getQueryBuilderFactory().find(Preset.class).build(session).getResultList();
EmbedBuilder embedBuilder = new EmbedBuilder();
if (presets.isEmpty()) {
embedBuilder.setDescription("No presets saved");
} else {
EmbedTable table = new EmbedTable(embedBuilder);
table.addColumn("Name", presets, Preset::getName);
table.addColumn("Preset", presets, Preset::getPreset);
table.build();
}
sendMessage(embedBuilder);
} else {
String presetString = getCommandInput();
String name = getArgumentValue("as");
Preset existingPreset = SearchEngine.searchPreset(getContext().getSession(), name);
if (existingPreset != null) {
throw new InvalidCommandException("Preset " + name + " already exists");
}
Preset preset = new Preset(name, presetString, getContext().getGuild(), getContext().getUser());
String testString = presetString.contains("%s") ? name + " test" : name;
AbstractCommand abstractCommand = preset.instantiateCommand(getManager(), getContext(), testString);
CommandParser commandParser = new CommandParser(abstractCommand, ArgumentPrefixProperty.getForCurrentContext());
commandParser.parse();
abstractCommand.verify();
invoke(() -> session.persist(preset));
}
}
use of net.robinfriedli.aiode.command.AbstractCommand in project aiode by robinfriedli.
the class ScriptCommandInterceptor method performChained.
@Override
public void performChained(Command command) {
if (command instanceof AbstractCommand) {
AbstractCommand abstractCommand = (AbstractCommand) command;
if (abstractCommand.getArgumentController().argumentSet("skipInterceptors") || abstractCommand.getCommandContribution().isDisableScriptInterceptors()) {
return;
}
} else {
return;
}
CommandContext context = command.getContext();
Session session = context.getSession();
GuildSpecification specification = context.getGuildContext().getSpecification(session);
boolean enableScripting = guildPropertyManager.getPropertyValueOptional("enableScripting", Boolean.class, specification).orElse(true);
if (!enableScripting) {
return;
}
String usageId = getUsageId();
List<StoredScript> scriptInterceptors = queryBuilderFactory.find(StoredScript.class).where((cb, root, subQueryFactory) -> cb.and(cb.isTrue(root.get("active")), cb.equal(root.get("scriptUsage"), subQueryFactory.createUncorrelatedSubQuery(StoredScript.ScriptUsage.class, "pk").where((cb1, root1) -> cb1.equal(root1.get("uniqueId"), usageId)).build(session)))).build(session).getResultList();
if (scriptInterceptors.isEmpty()) {
return;
}
Aiode aiode = Aiode.get();
SafeGroovyScriptRunner scriptRunner = new SafeGroovyScriptRunner(context, groovySandboxComponent, aiode.getGroovyVariableManager(), aiode.getSecurityManager(), false);
AtomicReference<StoredScript> currentScriptReference = new AtomicReference<>();
try {
scriptRunner.runScripts(scriptInterceptors, currentScriptReference, 5, TimeUnit.SECONDS);
} catch (ExecutionException e) {
Throwable error = e.getCause() != null ? e.getCause() : e;
if (error instanceof CommandFailure) {
messageService.sendError(String.format("Executing command %1$ss failed due to an error in %1$s '%2$s'", usageId, currentScriptReference.get().getIdentifier()), context.getChannel());
} else {
EmbedBuilder embedBuilder = ExceptionUtils.buildErrorEmbed(error);
StoredScript currentScript = currentScriptReference.get();
embedBuilder.setTitle(String.format("Error occurred while executing custom command %s%s", usageId, currentScript.getIdentifier() != null ? ": " + currentScript.getIdentifier() : ""));
messageService.sendTemporary(embedBuilder.build(), context.getChannel());
}
} catch (TimeoutException e) {
StoredScript currentScript = currentScriptReference.get();
messageService.sendError(String.format("Execution of script command %ss stopped because script%s has run into a timeout", usageId, currentScript != null ? String.format(" '%s'", currentScript.getIdentifier()) : ""), context.getChannel());
}
}
use of net.robinfriedli.aiode.command.AbstractCommand in project aiode by robinfriedli.
the class AnswerCommand method doRun.
@Override
public void doRun() {
getContext().getGuildContext().getClientQuestionEventManager().getQuestion(getContext()).ifPresentOrElse(question -> {
AbstractCommand sourceCommand = question.getSourceCommand();
String commandInput = getCommandInput();
Splitter commaSplitter = Splitter.on(",").trimResults().omitEmptyStrings();
List<String> options = commaSplitter.splitToList(commandInput);
Object option;
if (options.size() == 1) {
option = question.get(options.get(0));
} else {
Set<Object> chosenOptions = new LinkedHashSet<>();
for (String o : options) {
Object chosen = question.get(o);
if (chosen instanceof Collection) {
chosenOptions.addAll((Collection<?>) chosen);
} else {
chosenOptions.add(chosen);
}
}
option = chosenOptions;
}
try {
targetCommand = sourceCommand.fork(getContext());
targetCommand.withUserResponse(option);
question.destroy();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new CommandRuntimeException(e);
}
}, () -> {
throw new InvalidCommandException("I don't remember asking you anything " + getContext().getUser().getName());
});
}
Aggregations