Skip to content

Plugins_Variables

Lars Bärtschi edited this page Feb 5, 2018 · 1 revision

Variables

Variables are an easy way to preprocess any output of the bot. Variables get evaluated shortly before the output is written in the chat.

Format

The general format of an variable is: $variablename(param1,param2)

There is a shorter version without parameters: $variablename or $variablename()

Application Examples (using twasi-commands + common-variables):

> !add !random Random Number between 1 and 100: $rdm(1,100)
< The command was added successfully.
> !random
< Random Number between 1 and 100: 42

Program your own variables

First you need to have a basic TwasiPlugin with an TwasiPlugin and an TwasiUserPlugin.

In TwasiUserPlugin, override this method:

@Override
public List<TwasiVariable> getVariables() {
    return Arrays.asList(
            new MyCustomVar(this)
    );
}

The method getVariables() is used to register all available variables.

Next you need to create the class MyCustomVar we referenced earlier:

public class MyCustomVar extends TwasiVariable {
    public MyCustomVar(TwasiUserPlugin owner) {
        super(owner);
    }

    @Override
    public List<String> getNames() {
        // Insert all names that should be processed by this variable here
        return Arrays.asList("myrandom", "myrdm");
    }

    // This method will be called to replace the variable. You can just return the string that should replace the variable.
    @Override
    public String process(String name, TwasiInterface inf, String[] params, TwasiMessage message) {
        // Check length of arguments
        if (params.length != 2) {
            return "ERROR_NUMBER_OF_PARAMETERS";
        }

        int min, max;

        // Try to parse numbers
        try {
            min = Integer.valueOf(params[0]);
            max = Integer.valueOf(params[1]);
        } catch (NumberFormatException e) {
            return "ERROR_UNKNOWN_NUMBER";
        }

        // Generate random number
        int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

        return String.valueOf(randomNum);
    }
}

That's it! Add the plugin to twasi-core, install it and have fun!