Skip to content

Example 2

Gellért Dániel edited this page Apr 9, 2022 · 11 revisions

This example shows you how to work with concatenators and why they are useful. It makes a command with a year, month and a day input argument with number type and concatenates them with a custom concatenator into a date with a converter. It uses this converter, so it needs to be registered before using the command.

Code

// Create the command and arguments without any limitation for now
SlashCommand dateCommand = new SlashCommand("date", "Constructs a date");
NumberArgument yearArgument = new NumberArgument("year", "Year of the date");
NumberArgument monthArgument = new NumberArgument("month", "Month of the date");
NumberArgument dayArgument = new NumberArgument("day", "Day of the date");

// Make a concatenator that result's type is a Date and returns the arguments as a String
// formatted to be able to get parsed by date format in the converter
Concatenator dateConcatenator = new Concatenator(Date.class) {
    @Override
    public Object concatenate(ArgumentResult... results) {
        return Arrays.stream(results).map(result -> result.get().toString()).collect(Collectors.joining("-"));
    }
};

// Add arguments and concatenator and set action listener
dateCommand.addArgument(yearArgument, monthArgument, dayArgument);
dateCommand.addConcatenator(dateConcatenator, yearArgument, monthArgument, dayArgument);
dateCommand.setOnAction(event -> {
    // The argument's result is now a date
    Date date = event.getArguments()[0].get();

    event.getResponder().respondNow()
            .setContent(DateConverter.DATE_FORMAT.format(date))
            .respond();
});

CommandHandler.registerCommand(dateCommand, server);

Test

example