Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import net.dv8tion.jda.api.JDABuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.commands.CommandHandler;
import org.togetherjava.tjbot.db.Database;

import javax.security.auth.login.LoginException;
Expand Down Expand Up @@ -53,6 +54,7 @@ public static void runBot(String token, Path databasePath) {
JDA jda = JDABuilder.createDefault(token)
.addEventListeners(new PingPongListener())
.addEventListeners(new DatabaseListener(database))
.addEventListeners(new CommandHandler())
.build();
jda.awaitReady();
logger.info("Bot is ready");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package org.togetherjava.tjbot.commands;

import net.dv8tion.jda.api.events.interaction.ButtonClickEvent;
import net.dv8tion.jda.api.events.interaction.SelectionMenuEvent;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.components.Component;
import org.jetbrains.annotations.NotNull;
import org.togetherjava.tjbot.commands.example.CommandExample;
import org.togetherjava.tjbot.commands.example.SubCommandExample;

import java.time.Instant;
import java.util.Collection;
import java.util.List;

/**
* The class all commands have to abstract. <br>
* Instead of implementing this interface, you can also extend
* {@link org.togetherjava.tjbot.commands.example.AbstractCommand}.
*
* Look at {@link CommandExample} for an example. <br>
* Or look at {@link SubCommandExample} for an example with subcommands.
*
* <br>
* <b> All commands that implement this interface need to be added command to the
* {@link CommandHandler} class!</b>
*/
public interface Command {

/**
* <p>
* The command's name.
*
* <p>
* <b>Requirements!</b>
* <ul>
* <li>Lowercase</li>
* <li>Alphanumeric (with dash)</li>
* <li>1 to 32 characters long</li>
* </ul>
*
* @return The commands name as a {@link String}
*/
@NotNull
String getCommandName();

/**
* <p>
* The command's description.
*
* <p>
* <b>Requirements!</b>
* <ul>
* <li>1 to 100 characters long</li>
* </ul>
*
* @return The command's description as a {@link String}
*/
@NotNull
String getDescription();

/**
* Whenever the command is only for guilds, optional method.
*
* @return Whenever the command is only for guilds as a {@link Boolean}
*/
default boolean isGuildOnly() {
return false;
}

/**
* This command will add all the options to the slash-command. <br>
* Look at {@link CommandExample#addOptions(CommandData)} for an example.
*
* @param commandData The {@link CommandData} where the options need to be added.
* @return The changed {@link CommandData}
*/
default @NotNull CommandData addOptions(@NotNull CommandData commandData) {
return commandData;
}

/**
* The execute method for when the command gets executed. <br>
* Check <a href="https://github.com/DV8FromTheWorld/JDA/wiki/Interactions#slash-commands">JDA's
* slash-commands Wiki article</a> for more information.
*
* @param event The relating {@link SlashCommandEvent}
*/
default void onSlashCommand(SlashCommandEvent event) {}

/**
* The execute method for when a button related to this command gets clicked. <br>
* Check <a href="https://github.com/DV8FromTheWorld/JDA/wiki/Interactions#buttons">JDA's
* buttons Wiki article</a> for more information.
*
* @param event The relating {@link ButtonClickEvent}
* @param idArgs All the arguments stored in the ID ({@link Component#getId()
* Component#getId()}) have been converted to a {@link List} The commands name and
* current time in MS have been removed from this, example:
* "examplecommand-7272727272-userId", this will be converted to a {@link List}
* containing "userId", the rest has been removed.
*/
default void onButtonClick(ButtonClickEvent event, List<String> idArgs) {}

/**
* The execute method for when a selection menu related to this command gets clicked. <br>
* JDA has no dedicated guide for selection menu's, they work the same as buttons. <br>
* Check <a href="https://github.com/DV8FromTheWorld/JDA/wiki/Interactions#buttons">JDA's
* buttons Wiki article</a> for more information.
*
* @param event The relating {@link ButtonClickEvent}
* @param idArgs All the arguments stored in the ID ({@link Component#getId()
* Component#getId()}) have been converted to a {@link List} The commands name and
* current time in MS have been removed from this, example:
* "examplecommand-7272727272-userId", this will be converted to a {@link List}
* containing "userId", the rest has been removed.
*/
default void onSelectionMenu(SelectionMenuEvent event, List<String> idArgs) {}


/**
* Generates a {@link net.dv8tion.jda.api.interactions.components.Component Component} ID based
* on the command name, current time and given arguments, <br>
* {@link net.dv8tion.jda.api.interactions.components.Component Component} examples are
* {@link net.dv8tion.jda.api.interactions.components.Button Buttons} and or
* {@link net.dv8tion.jda.api.interactions.components.selections.SelectionMenu SelectionMenu's}
*
* <br>
* An ID can be maximum of
* {@link net.dv8tion.jda.api.interactions.components.Button#ID_MAX_LENGTH} chars. <br>
* Between every argument an `{@code -}` is added, and by default the command name + current
* time in MS gets added.
*
* @param args A {@link String} array of the arguments
* @return A {@link String} generated ID in the format of
* `{@code commandName-timeInMs-arg1-arg2}`
*/
default @NotNull String generateComponentId(@NotNull String... args) {
Comment thread
d3vel0per marked this conversation as resolved.
Resolved
StringBuilder stringBuilder = new StringBuilder(getCommandName());

stringBuilder.append("-").append(Instant.now().getNano());

for (String arg : args) {
stringBuilder.append("-").append(arg);
}

return stringBuilder.toString();
}

/**
* /** Generates a {@link net.dv8tion.jda.api.interactions.components.Component Component} ID
* based on the command name, current time and given arguments, <br>
* {@link net.dv8tion.jda.api.interactions.components.Component Component} examples are
* {@link net.dv8tion.jda.api.interactions.components.Button Buttons} and or
* {@link net.dv8tion.jda.api.interactions.components.selections.SelectionMenu SelectionMenu's}
*
* <br>
* An ID can be maximum of
* {@link net.dv8tion.jda.api.interactions.components.Button#ID_MAX_LENGTH} chars. <br>
* Between every argument an `{@code -}` is added, and by default the command name + current
* time in MS gets added.
*
* @param args A {@link Collection<String>} of {@link String}'s of the arguments
* @return A {@link String} generated ID in the format of
* `{@code commandName-timeInMs-arg1-arg2}`
*/
default @NotNull String generateComponentId(@NotNull Collection<String> args) {
return generateComponentId(args.toArray(new String[] {}));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package org.togetherjava.tjbot.commands;

import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.events.interaction.ButtonClickEvent;
import net.dv8tion.jda.api.events.interaction.GenericComponentInteractionCreateEvent;
import net.dv8tion.jda.api.events.interaction.SelectionMenuEvent;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

/**
* The command handler
*
* Commands need to be added to the commandList
*/
public class CommandHandler extends ListenerAdapter {
private final static Logger logger = LoggerFactory.getLogger(CommandHandler.class);

private final List<Command> commandList = new ArrayList<>();
private final Map<String, Command> commandMap;

public CommandHandler() {
commandList.addAll(List.of(new ReloadCommand(this)
// add your command here
));

commandMap = commandList.stream()
.collect(Collectors.toMap(Command::getCommandName, command -> command));
}

@Override
public void onReady(@NotNull ReadyEvent event) {
event.getJDA().getGuildCache().forEach(guild -> {
guild.retrieveCommands().queue(commands -> {
boolean hasReloadCommand =
commands.stream().anyMatch(command -> command.getName().equals("reload"));

if (!hasReloadCommand) {
Command command = commandMap.get("reload");
guild.upsertCommand(command.addOptions(
new CommandData(command.getCommandName(), command.getDescription())))
.queue();
}
});
});
}

@Override
public void onSlashCommand(@NotNull SlashCommandEvent event) {
Command command = commandMap.get(event.getName());

if (command != null) {
command.onSlashCommand(event);
} else {
logger.error("Command '{}' doesn't exist?", event.getName());
}
}

@Override
Comment thread
illuminator3 marked this conversation as resolved.
Resolved
public void onButtonClick(@NotNull ButtonClickEvent event) {
getArgumentsAndCommandByEvent(event, (command, args) -> command.onButtonClick(event, args));
}

@Override
public void onSelectionMenu(@NotNull SelectionMenuEvent event) {
getArgumentsAndCommandByEvent(event,
(command, args) -> command.onSelectionMenu(event, args));
}

/**
* Gets the arguments as a {@link List} and gets the {@link Command} by the event.
*
* @param event a {@link GenericComponentInteractionCreateEvent}
* @param onSucceed a {@link BiConsumer} that takes the command and the arguments
*/
private void getArgumentsAndCommandByEvent(GenericComponentInteractionCreateEvent event,
BiConsumer<Command, List<String>> onSucceed) {
String[] argsArray = event.getComponentId().split("-");
Command command = commandMap.get(argsArray[0]);

if (command != null) {
List<String> args = new ArrayList<>(Arrays.asList(argsArray));
args = args.subList(2, args.size());
onSucceed.accept(command, args);
}
}

public List<Command> getCommandList() {
return commandList;
}
}
Loading