Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
a0fb71e
Copy paste of old command rework from #382
Tais993 Sep 3, 2022
e3aa80b
Removed ReloadCommand.java and added automatic reloading on bot launch
Tais993 Sep 3, 2022
4332c74
Applied Spotless, and reworked CommandProvider
Tais993 Sep 7, 2022
154a24d
I like SpotlasSS!!!!!!!!
Tais993 Sep 7, 2022
2d837b1
Removed unused method
Tais993 Sep 7, 2022
8ded6d3
homicide
Tais993 Sep 7, 2022
e10afcc
I just commited homicide
Tais993 Sep 7, 2022
acfecbc
It's over, but not for me
Tais993 Sep 7, 2022
d5dbaee
okay this one was my fault ngl
Tais993 Sep 7, 2022
fe10a3c
now it should work pepepls
Tais993 Sep 8, 2022
7ddf0e0
i should find out how i can make spotless run automatically so i dont…
Tais993 Sep 8, 2022
dc6367f
Removed `@NotNull` annotations and other minor improvements
Tais993 Sep 15, 2022
a594621
Optimized imports
Tais993 Sep 15, 2022
51bbcc2
homicide.
Tais993 Sep 15, 2022
0979e53
Implemented UserInteractorPrefix and some other review fixes
Tais993 Sep 23, 2022
24597aa
CR changes
Tais993 Sep 27, 2022
63c4496
⠀
Tais993 Sep 27, 2022
282e06b
⠀pleaase sonarlint get yourself working ur actually the most useless…
Tais993 Sep 27, 2022
04b56b1
i hate this shit so fucking much
Tais993 Sep 27, 2022
3af6108
CR fixes
Tais993 Sep 27, 2022
5df1f0a
CR fixes
Tais993 Sep 29, 2022
aa4e098
Minor changes to command reloading
Tais993 Sep 29, 2022
c4749b4
Removed onReady listener from BotCore
Tais993 Sep 29, 2022
bebccc5
Improved documentation surrounding prefixed and unprefixed names
Tais993 Sep 29, 2022
41a5009
spotless
Tais993 Sep 29, 2022
775a0b2
Added documentation to scheduleRoutines
Tais993 Sep 29, 2022
c52a4ad
spotless
Tais993 Sep 29, 2022
edc1158
Fixed bugs
Tais993 Sep 29, 2022
d8a1fdb
spotless runs automatically yes mhmhhm
Tais993 Sep 29, 2022
8a93265
CR
Tais993 Sep 30, 2022
f71e4fe
Removed useless extra lines (CR)
Tais993 Sep 30, 2022
befa3a8
Added missing empty lines between methods
Tais993 Sep 30, 2022
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 @@ -82,13 +82,10 @@ public static void runBot(Config config) {
.enableIntents(GatewayIntent.GUILD_MEMBERS)
.build();

jda.awaitReady();
BotCore core = new BotCore(jda, database, config);
jda.addEventListener(core);
jda.awaitReady();

// We fire the event manually, since the core might be added too late to receive the
// actual event fired from JDA
core.onReady(jda);
logger.info("Bot is ready");
} catch (LoginException e) {
logger.error("Failed to login", e);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package org.togetherjava.tjbot;

import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction;
import org.jetbrains.annotations.Contract;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.commands.BotCommand;
import org.togetherjava.tjbot.commands.CommandVisibility;
import org.togetherjava.tjbot.commands.system.CommandProvider;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
* Offers utility functions for reloading all commands.
*/
public class CommandReloading {
private static final Logger logger = LoggerFactory.getLogger(CommandReloading.class);

/**
* According to <a href=
* "https://discord.com/developers/docs/interactions/application-commands#registering-a-command">Discord
* docs</a>, there can be a maximum of 110 commands, 100 slash, and 5 context each.
* <p>
* Because this bot most of the time operates in only 1 server, chances of exceeding this limit
* is low.
*/
public static final int MAX_COMMAND_COUNT = 110;

private CommandReloading() {
throw new UnsupportedOperationException("Utility class");
}

/**
* Reloads all commands based on the given {@link CommandProvider}.
*
* @param jda the JDA to update commands on
* @param commandProvider the {@link CommandProvider} to grab commands from
*/
public static void reloadCommands(final JDA jda, final CommandProvider commandProvider) {
logger.info("Reloading commands...");
List<CommandListUpdateAction> actions =
Collections.synchronizedList(new ArrayList<>(MAX_COMMAND_COUNT));

// Reload global commands
actions.add(updateCommandsIf(command -> CommandVisibility.GLOBAL == command.getVisibility(),
getGlobalUpdateAction(jda), commandProvider));

// Reload guild commands (potentially many guilds)
// NOTE Storing the guild actions in a list is potentially dangerous since the
// bot might theoretically be part of so many guilds that it exceeds the max size of
// list. However, correctly reducing RestActions in a stream is not trivial.
getGuildUpdateActions(jda)
.map(updateAction -> updateCommandsIf(
command -> CommandVisibility.GUILD == command.getVisibility(), updateAction,
commandProvider))
.forEach(actions::add);
logger.debug("Reloading commands over {} action-upstreams", actions.size());

// Send message when all are done
RestAction.allOf(actions).queue(a -> logger.debug("Commands successfully reloaded!"));
}

/**
* Updates all commands given by the command provider which pass the given filter by pushing
* through the given action upstream.
*
* @param commandFilter filter that matches commands that should be uploaded
* @param updateAction the upstream to update commands
* @return the given upstream for chaining
*/
@Contract("_, _, _ -> param2")
private static CommandListUpdateAction updateCommandsIf(
final Predicate<? super BotCommand> commandFilter,
final CommandListUpdateAction updateAction, final CommandProvider commandProvider) {
commandProvider.getInteractors()
.stream()
.filter(BotCommand.class::isInstance)
.map(BotCommand.class::cast)
.filter(commandFilter)
.map(BotCommand::getData)
.forEach(updateAction::addCommands);
Comment thread
Zabuzard marked this conversation as resolved.
Resolved

return updateAction;
}

private static CommandListUpdateAction getGlobalUpdateAction(final JDA jda) {
return jda.updateCommands();
}

private static Stream<CommandListUpdateAction> getGuildUpdateActions(final JDA jda) {
return jda.getGuildCache().stream().map(Guild::updateCommands);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package org.togetherjava.tjbot.commands;

import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.Command;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.Commands;

import java.util.List;

/**
* Represents a Discord command.
* <p>
* All commands have to implement this interface. For convenience, there is a
* {@link BotCommandAdapter} available that implemented most methods already. A new command can then
* be registered by adding it to {@link Features}.
* <p>
* Commands can either be visible globally in Discord or just to specific guilds. Some
* configurations can be made via {@link CommandData}, which is then to be returned by
* {@link #getData()} where the system will then pick it up from.
* <p>
* After registration, the system will notify a command whenever one of its corresponding command
* method, buttons ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus
* ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered.
* <p>
* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}.
*/
public interface BotCommand extends UserInteractor {

/**
* {@inheritDoc}
* <p>
* Requirements for this are documented in
* {@link net.dv8tion.jda.api.interactions.commands.build.Commands Commands}. If your command is
* a slash-command, take a look at
* {@link net.dv8tion.jda.api.interactions.commands.build.Commands#slash(String, String)
* Commands#slash(String, String)}. For context commands, use
* {@link Commands#context(Command.Type, String) Commands#context(Command.Type, String)}.
*
* @return the name of the interactor
*/
String getName();

/**
* Gets the type of this command.
* <p>
* After registration of the command, the type must not change anymore.
*
* @return the type of the command
*/
Command.Type getType();

/**
* Gets the visibility of this command.
* <p>
* After registration of the command, the visibility must not change anymore.
*
* @return the visibility of the command
*/
CommandVisibility getVisibility();

/**
* Gets the command data belonging to this command.
* <p>
* See {@link net.dv8tion.jda.api.interactions.commands.build.Commands Commands} for details on
* how to create and configure instances of it.
* <p>
* This method may be called multiple times, implementations must not create new data each time
* but instead configure it once beforehand. The core system will automatically call this method
* to register the command to Discord.
*
* @return the command data of this command
*/
CommandData getData();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package org.togetherjava.tjbot.commands;

import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.Command;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import org.jetbrains.annotations.Contract;
import org.togetherjava.tjbot.commands.componentids.ComponentId;
import org.togetherjava.tjbot.commands.componentids.ComponentIdGenerator;
import org.togetherjava.tjbot.commands.componentids.Lifespan;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
* Adapter implementation of a {@link BotCommand}. The minimal setup only requires implementation of
* their respective command method. A new command can then be registered by adding it to
* {@link Features}.
* <p>
* Further, {@link #onButtonClick(ButtonInteractionEvent, List)} and
* {@link #onSelectionMenu(SelectMenuInteractionEvent, List)} can be overridden if desired. The
* default implementation is empty, the adapter will not react to such events.
* <p>
* <p>
* The adapter manages some getters for you, you've to create the {@link CommandData} yourself. See
* {@link #BotCommandAdapter(CommandData, CommandVisibility)}} for more info on that. Minimal
* modifications can be done on the {@link CommandData} returned by {@link #getData()}.
* <p>
* <p>
* If implementations want to add buttons or selection menus, it is highly advised to use component
* IDs generated by {@link #generateComponentId(String...)}, which will automatically create IDs
* that are valid per {@link SlashCommand#onSlashCommand(SlashCommandInteractionEvent)}.
* <p>
* <p>
* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}.
* Registration of commands can be done in {@link Features}.
*/
public abstract class BotCommandAdapter implements BotCommand {
private final String name;
private final Command.Type type;
private final CommandVisibility visibility;
private final CommandData data;
private ComponentIdGenerator componentIdGenerator;

/**
* Creates a new adapter with the given data.
*
* @param data the data for this command
* @param visibility the visibility of the command
*/
protected BotCommandAdapter(CommandData data, CommandVisibility visibility) {
this.data = Objects.requireNonNull(data, "The data shouldn't be null");
this.visibility = Objects.requireNonNull(visibility, "The visibility shouldn't be null");

this.name = data.getName();
this.type = data.getType();
}

@Override
public final String getName() {
return name;
}

@Override
public Command.Type getType() {
return type;
}

@Override
public final CommandVisibility getVisibility() {
return visibility;
}

@Override
public CommandData getData() {
return data;
}

@Override
@Contract(mutates = "this")
public final void acceptComponentIdGenerator(ComponentIdGenerator generator) {
componentIdGenerator =
Objects.requireNonNull(generator, "The given generator cannot be null");
}

@SuppressWarnings("NoopMethodInAbstractClass")
@Override
public void onButtonClick(ButtonInteractionEvent event, List<String> args) {
// Adapter does not react by default, subclasses may change this behavior
}

@SuppressWarnings("NoopMethodInAbstractClass")
@Override
public void onSelectionMenu(SelectMenuInteractionEvent event, List<String> args) {
// Adapter does not react by default, subclasses may change this behavior
}

/**
* Helper method to generate component IDs that are considered valid per
* {@link #acceptComponentIdGenerator(ComponentIdGenerator)}.
* <p>
* They can be used to create buttons or selection menus and transport additional data
* throughout the event (e.g. the user id who created the button dialog).
* <p>
* IDs generated by this method have a regular lifespan, meaning that they might get evicted and
* expire after not being used for a long time. Use
* {@link #generateComponentId(Lifespan, String...)} to set other lifespans, if desired.
*
* @param args the extra arguments that should be part of the ID
* @return the generated component ID
*/
@SuppressWarnings("OverloadedVarargsMethod")
protected final String generateComponentId(String... args) {
return generateComponentId(Lifespan.REGULAR, args);
}

/**
* Helper method to generate component IDs that are considered valid per
* {@link #acceptComponentIdGenerator(ComponentIdGenerator)}.
* <p>
* They can be used to create buttons or selection menus and transport additional data
* throughout the event (e.g. the user id who created the button dialog).
*
* @param lifespan the lifespan of the component id, controls when an id that was not used for a
* long time might be evicted and expire
* @param args the extra arguments that should be part of the ID
* @return the generated component ID
*/
@SuppressWarnings({"OverloadedVarargsMethod", "WeakerAccess"})
protected final String generateComponentId(Lifespan lifespan, String... args) {
return componentIdGenerator.generate(new ComponentId(getName(), Arrays.asList(args)),
lifespan);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/**
* Visibility of a slash command, i.e. in which context it can be used by users.
*/
public enum SlashCommandVisibility {
public enum CommandVisibility {
/**
* The command can be used within the context of a guild.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
features.add(new RejoinModerationRoleListener(actionsStore, config));
features.add(new OnGuildLeaveCloseThreadListener(database));

// Message context commands

// User context commands

// Slash commands
features.add(new LogLevelCommand());
features.add(new PingCommand());
Expand Down
Loading