Skip to content

Advanced Custom Command Example

Jens Møller edited this page Jun 4, 2019 · 17 revisions

How to create an advanced custom command

You can create a .java file, and run it as a command. This allows for more advanced commands, that could do all sorts of stuff.

Look at this repo for more examples


Randomcat.java

This example command asks the api on random.cat for a random cat picture. Downloads it, makes sure its not past the 8MB reqiurement for uploading to Discord, if it passes that 8MB reqiurement then posts it to the server.

Permissions

You can choose who can use the command, currently KajBot supports both the booster role, and the admin role.

Add this.adminCommand = true; to make the command only avalibe to admins. The role can be edited in the config file.

Add this.boosterCommand = true; to make the command only avalible to those withe the booster role

If you remove the line, everyone can use the command.

import org.json.JSONObject;
import dk.jensbot.kajbot4discord.command.Command;
import dk.jensbot.kajbot4discord.command.CommandEvent;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Randomcat extends Command {
    public Randomcat() {
        this.name = "catto";
        this.guildOnly = false;
    }


    @Override
    public void execute(CommandEvent e) {
        try (Stream<String> stream = new BufferedReader(new InputStreamReader(new URL("http://aws.random.cat/meow").openStream(), StandardCharsets.UTF_8)).lines()) {
            URL url = new URL(new JSONObject(stream.collect(Collectors.joining(System.lineSeparator()))).getString("file"));
            int lastIndexOf = url.toString().lastIndexOf(".");
            if (lastIndexOf == -1) {
                return;
            }
            InputStream in = url.openStream();
            if(!Files.exists(Paths.get(System.getProperty("user.dir") + "/downloads"))) Files.createDirectories(Paths.get(System.getProperty("user.dir") + "/downloads"));
            Files.copy(in, Paths.get(System.getProperty("user.dir") + "/downloads/catto" + url.toString().substring(lastIndexOf)), StandardCopyOption.REPLACE_EXISTING);
            File file = new File(System.getProperty("user.dir") + "/downloads/catto" + url.toString().substring(lastIndexOf));
            if (((double) file.length() / (1024 * 1024)) > 7.99) {
                execute(e);
                return;
            }
            e.getChannel().sendFile(file).queue();
        } catch (IOException ignored) {
        }
    }
}