Compare commits

27 Commits

Author SHA1 Message Date
a3c5eb62ac Merge pull request 'add option ranges' (#20) from feat/option-ranges into dev
All checks were successful
github-mirror / push-github (push) Successful in 4s
Build / Gradle-Build (push) Successful in 32s
Publish / Gradle-Publish (push) Successful in 43s
Test / Gradle-Test (push) Successful in 47s
Reviewed-on: #20
2025-03-22 18:42:28 +00:00
996f854ff7 feat(command): add wrapper implementations of option ranges
All checks were successful
github-mirror / push-github (push) Successful in 1m40s
Build / Gradle-Build (push) Successful in 33s
Test / Gradle-Test (push) Successful in 47s
2025-03-22 12:33:21 +01:00
d2eec8b07c feat(command): add option ranges to options 2025-03-22 12:31:25 +01:00
caa2ee7089 refactor(command): move both choices vars to different annotation
All checks were successful
github-mirror / push-github (push) Successful in 1m36s
Build / Gradle-Build (push) Successful in 31s
Publish / Gradle-Publish (push) Successful in 36s
Test / Gradle-Test (push) Successful in 47s
2025-03-18 09:33:53 +01:00
2e5979e6e4 Merge pull request 'migrate to slf4j' (#18) from migrate/slf4j into dev
All checks were successful
github-mirror / push-github (push) Successful in 4s
Build / Gradle-Build (push) Successful in 1m45s
Publish / Gradle-Publish (push) Successful in 1m32s
Test / Gradle-Test (push) Successful in 1m38s
Reviewed-on: #18
2025-03-17 19:34:26 +00:00
ab1eb74e85 fix(logging) implement getQualifiedCallerName
All checks were successful
github-mirror / push-github (push) Successful in 4s
Build / Gradle-Build (push) Successful in 35s
Test / Gradle-Test (push) Successful in 48s
2025-03-17 14:36:43 +01:00
a5737b9eaa feat(logging): add Fallback logging
All checks were successful
github-mirror / push-github (push) Successful in 4s
Build / Gradle-Build (push) Successful in 31s
Test / Gradle-Test (push) Successful in 47s
2025-03-17 14:13:21 +01:00
faca21724c fix(logging): fix wrong getClass method. 2025-03-17 14:13:00 +01:00
4c5e28b679 feat(logging): replace log4j dependency with slf4j and replace imports
All checks were successful
github-mirror / push-github (push) Successful in 3s
Build / Gradle-Build (push) Successful in 38s
Test / Gradle-Test (push) Successful in 51s
2025-03-17 10:52:24 +01:00
33f355e6ea Merge pull request 'improve wrapper and general structure' (#16) from improve/structure into dev
All checks were successful
github-mirror / push-github (push) Successful in 5s
Build / Gradle-Build (push) Successful in 36s
Publish / Gradle-Publish (push) Successful in 32s
Test / Gradle-Test (push) Successful in 48s
Reviewed-on: #16
No new features
2025-03-17 08:26:43 +00:00
d32ac62b4a fix(autocomplete): fix autocomplete using component context objects
All checks were successful
github-mirror / push-github (push) Successful in 1m46s
Build / Gradle-Build (push) Successful in 31s
Test / Gradle-Test (push) Successful in 59s
2025-03-17 08:37:11 +01:00
e7c35d9308 refactor(core): remove redundant distinct method and its uses
All checks were successful
github-mirror / push-github (push) Successful in 4s
Build / Gradle-Build (push) Successful in 32s
Test / Gradle-Test (push) Successful in 46s
2025-03-17 00:16:26 +01:00
d4a91f3251 fix(core): fix wrong equality method and refactor a bit 2025-03-17 00:15:10 +01:00
bce4ce7812 fix(wrapper): add condition for CommandRegisterer if api is null 2025-03-16 23:35:39 +01:00
bae077654e refactor(Discord4J): implement CommandRegisterer refactor
Some checks failed
github-mirror / push-github (push) Successful in 1m44s
Build / Gradle-Build (push) Successful in 55s
Test / Gradle-Test (push) Failing after 41s
2025-03-16 17:16:26 +01:00
203498de68 refactor(javacord): implement CommandRegisterer refactor 2025-03-16 17:07:14 +01:00
24df1731da refactor(command): add CommandRegisterer 2025-03-16 17:06:37 +01:00
e3fc10a1ce fix(util): ObjectListAggregator syntax 2025-03-16 02:48:24 +01:00
78cacb7eb6 feat(util): add ObjectListAggregator 2025-03-16 02:47:16 +01:00
7287d44645 refactor(util): add multiple key support to ObjectAggregator 2025-03-16 02:46:55 +01:00
630c8ddee5 feat(register): add convenience getter 2025-03-16 01:49:24 +01:00
4e27e6ce56 feat(struct): introduce ObjectAggregator 2025-03-16 01:36:23 +01:00
432cf78a2e add IdentifierProvider and wrapper implementations
All checks were successful
github-mirror / push-github (push) Successful in 4s
Build / Gradle-Build (push) Successful in 33s
Test / Gradle-Test (push) Successful in 48s
2025-03-05 21:44:12 +01:00
f940f48566 move CommandConverter to wrapper package
All checks were successful
github-mirror / push-github (push) Successful in 3s
Build / Gradle-Build (push) Successful in 31s
Test / Gradle-Test (push) Successful in 46s
2025-03-04 11:16:44 +01:00
f4ee258eb1 remove missing parent() call in SlashCommandDefinition#getSubCommands()
All checks were successful
github-mirror / push-github (push) Successful in 4s
Build / Gradle-Build (push) Successful in 53s
Test / Gradle-Test (push) Successful in 52s
2025-03-03 23:40:06 +01:00
56b668851b add CommandConverter logic and wrapper implementations
All checks were successful
github-mirror / push-github (push) Successful in 3s
Build / Gradle-Build (push) Successful in 37s
Test / Gradle-Test (push) Successful in 48s
2025-03-03 23:32:25 +01:00
823402e0cd fix base getSubCommands method 2025-03-03 23:32:07 +01:00
46 changed files with 878 additions and 454 deletions

View File

@@ -3,7 +3,7 @@
[versions]
junit-jupiter = "5.10.2"
log4j = "2.24.1"
slf4j = "2.0.17"
javacord = "3.8.0"
discord4j = "3.2.7"
geantyref = "2.0.0"
@@ -11,7 +11,7 @@ mockito = "5.15.2"
[libraries]
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit-jupiter" }
log4j = { module = "org.apache.logging.log4j:log4j-api", version.ref = "log4j"}
slf4j = { module = "org.slf4j:slf4j-api", version.ref = "slf4j"}
javacord = { module = "org.javacord:javacord", version.ref = "javacord"}
discord4j = { module = "com.discord4j:discord4j-core", version.ref = "discord4j"}
geantyref = { module = "io.leangen.geantyref:geantyref", version.ref = "geantyref"}

View File

@@ -20,7 +20,7 @@ dependencies {
testImplementation(libs.junit.jupiter)
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
implementation(libs.log4j)
implementation(libs.slf4j)
implementation(libs.geantyref)
}

View File

@@ -1,6 +1,6 @@
package net.tomatentum.marinara;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import net.tomatentum.marinara.registry.InteractionCheckRegistry;
import net.tomatentum.marinara.registry.InteractionRegistry;

View File

@@ -5,7 +5,7 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import net.tomatentum.marinara.util.LoggerUtil;
import net.tomatentum.marinara.util.ReflectionUtil;
@@ -27,7 +27,7 @@ public record AppliedCheck(InteractionCheck<?> check, Annotation annotation) {
logger.debug("Pre Check {} {} with context {}", check.getClass().getName(), result ? "succeeded" : "failed", context.toString());
return result;
} catch (IllegalAccessException | InvocationTargetException | SecurityException e) {
logger.fatal(e);
logger.error("Failed executing pre-check", e);
return false;
}
}
@@ -43,7 +43,7 @@ public record AppliedCheck(InteractionCheck<?> check, Annotation annotation) {
logger.debug("Executing post check {} with context {}", check.getClass().getName(), context.toString());
method.invoke(check, context, annotation);
} catch (IllegalAccessException | InvocationTargetException | SecurityException e) {
logger.fatal(e);
logger.error("Failed executing post-check", e);
}
}

View File

@@ -1,23 +0,0 @@
package net.tomatentum.marinara.interaction.commands;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption;
import net.tomatentum.marinara.interaction.commands.annotation.SubCommand;
import net.tomatentum.marinara.interaction.commands.annotation.SubCommandGroup;
public class CommandConverter<A extends Object> {
private Spec<A, ?, ?> spec;
public A convert(SlashCommandDefinition def) {
return null;
}
public static interface Spec<A extends Object, O extends Object, C extends Object> {
public A convertCommand(SlashCommandDefinition def);
public O convertSubCommand(SubCommand def, O[] options);
public O convertSubCommandGroup(SubCommandGroup def, O[] options);
public O convertOption(SlashCommandOption option, C[] choices);
public C[] convertChoice(SlashCommandOption option);
}
}

View File

@@ -4,8 +4,9 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import net.tomatentum.marinara.interaction.commands.annotation.CommandChoices;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption.PlaceHolderEnum;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOptionChoice;
@@ -18,10 +19,11 @@ import net.tomatentum.marinara.util.LoggerUtil;
public class SlashCommandDefinition {
public static SlashCommandOptionChoice[] getActualChoices(SlashCommandOption option) {
SlashCommandOptionChoice[] choices = option.choices();
if (choices.length <= 0 && !option.choiceEnum().equals(PlaceHolderEnum.class))
choices = EnumChoices.of(option.choiceEnum()).choices();
return choices;
CommandChoices choices = option.choices();
SlashCommandOptionChoice[] actualChoices = choices.value();
if (choices.value().length <= 0 && !choices.cenum().equals(PlaceHolderEnum.class))
actualChoices = EnumChoices.of(choices.cenum()).choices();
return actualChoices;
}
private Set<InteractionIdentifier> entries;
@@ -66,13 +68,13 @@ public class SlashCommandDefinition {
.map(x -> x.parent())
.toList();
return InteractionIdentifier.distinct(subCommandGroups).toArray(SlashCommandIdentifier[]::new);
return subCommandGroups.toArray(SlashCommandIdentifier[]::new);
}
public SlashCommandIdentifier[] getSubCommands() {
if (isRootCommand)
return null;
return InteractionIdentifier.distinct(entries.stream().toList()).toArray(SlashCommandIdentifier[]::new);
return entries.stream().filter(x -> x.parent() instanceof RootCommandIdentifier).toArray(SlashCommandIdentifier[]::new);
}
public SlashCommandIdentifier[] getSubCommands(String groupName) {
@@ -84,7 +86,7 @@ public class SlashCommandDefinition {
.map(x -> x.parent().parent())
.toList();
return InteractionIdentifier.distinct(subCommands).toArray(SlashCommandIdentifier[]::new);
return subCommands.toArray(SlashCommandIdentifier[]::new);
}
@Override
@@ -95,6 +97,10 @@ public class SlashCommandDefinition {
return this.rootIdentifier().equals(other.rootIdentifier());
}
public long[] serverIds() {
return rootIdentifier().serverIds();
}
public Set<InteractionIdentifier> entries() {
return this.entries;
}

View File

@@ -0,0 +1,8 @@
package net.tomatentum.marinara.interaction.commands.annotation;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption.PlaceHolderEnum;
public @interface CommandChoices {
public SlashCommandOptionChoice[] value() default {};
public Class<? extends Enum<?>> cenum() default PlaceHolderEnum.class;
}

View File

@@ -0,0 +1,6 @@
package net.tomatentum.marinara.interaction.commands.annotation;
public @interface Range {
public double min() default Double.MIN_VALUE;
public double max() default Double.MAX_VALUE;
}

View File

@@ -15,8 +15,8 @@ public @interface SlashCommandOption {
public SlashCommandOptionType type() default SlashCommandOptionType.STRING;
public boolean required() default false;
public boolean autocomplete() default false;
public SlashCommandOptionChoice[] choices() default {};
public Class<? extends Enum<?>> choiceEnum() default PlaceHolderEnum.class;
public Range range() default @Range;
public CommandChoices choices() default @CommandChoices;
public static enum PlaceHolderEnum {

View File

@@ -1,8 +1,5 @@
package net.tomatentum.marinara.interaction.ident;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import net.tomatentum.marinara.interaction.InteractionType;
@@ -38,20 +35,6 @@ public class InteractionIdentifier {
tryAddDescriptions(receiver.parent(), provider.parent());
}
/*
* TODO: Might not be the best solution. Propagating to future
* returns only one Identifier per name and takes the first present description
*/
public static Collection<InteractionIdentifier> distinct(List<InteractionIdentifier> identifiers) {
HashMap<String, InteractionIdentifier> distinctIdentifiers = new HashMap<>();
identifiers.forEach((x) -> {
InteractionIdentifier current = distinctIdentifiers.get(x.name());
if (current == null || (current.description().isBlank() && !x.description().isBlank()))
distinctIdentifiers.put(x.name(), x);
});
return distinctIdentifiers.values();
}
private InteractionIdentifier parent;
private String name;
private String description;

View File

@@ -1,5 +1,6 @@
package net.tomatentum.marinara.interaction.ident;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption;
public class RootCommandIdentifier extends SlashCommandIdentifier {
@@ -10,10 +11,10 @@ public class RootCommandIdentifier extends SlashCommandIdentifier {
InteractionIdentifier parent,
String name,
String description,
InteractionType type,
SlashCommandOption[] options,
boolean isAutocomplete,
long[] serverIds) {
super(parent, name, description, options, isAutocomplete);
super(parent, name, description, type, options);
this.serverIds = serverIds;
}
@@ -26,7 +27,6 @@ public class RootCommandIdentifier extends SlashCommandIdentifier {
private String name;
private String description;
private SlashCommandOption[] options;
private boolean isAutocomplete = false;
private long[] serverIds;
@@ -66,15 +66,6 @@ public class RootCommandIdentifier extends SlashCommandIdentifier {
return this;
}
public boolean autocomplete() {
return this.isAutocomplete;
}
public Builder autocomplete(boolean isAutocomplete) {
this.isAutocomplete = isAutocomplete;
return this;
}
public long[] serverIds() {
return this.serverIds;
}
@@ -84,8 +75,14 @@ public class RootCommandIdentifier extends SlashCommandIdentifier {
return this;
}
public SlashCommandIdentifier build() {
return new RootCommandIdentifier(parent, name, description, options, isAutocomplete, serverIds);
public SlashCommandIdentifier build(boolean autocomplete) {
return new RootCommandIdentifier(
parent,
name,
description,
autocomplete ? InteractionType.AUTOCOMPLETE : InteractionType.COMMAND,
options,
serverIds);
}
}

View File

@@ -11,10 +11,10 @@ public class SlashCommandIdentifier extends InteractionIdentifier {
InteractionIdentifier parent,
String name,
String description,
SlashCommandOption[] options,
boolean isAutocomplete
InteractionType type,
SlashCommandOption[] options
) {
super(parent, name, description, isAutocomplete ? InteractionType.AUTOCOMPLETE : InteractionType.COMMAND);
super(parent, name, description, type);
this.options = options;
}
@@ -27,7 +27,6 @@ public class SlashCommandIdentifier extends InteractionIdentifier {
private String name;
private String description;
private SlashCommandOption[] options;
private boolean isAutocomplete = false;
public InteractionIdentifier parent() {
return parent;
@@ -65,17 +64,13 @@ public class SlashCommandIdentifier extends InteractionIdentifier {
return this;
}
public boolean autocomplete() {
return this.isAutocomplete;
}
public Builder autocomplete(boolean isAutocomplete) {
this.isAutocomplete = isAutocomplete;
return this;
}
public SlashCommandIdentifier build() {
return new SlashCommandIdentifier(parent, name, description, options, isAutocomplete);
public SlashCommandIdentifier build(boolean autocomplete) {
return new SlashCommandIdentifier(
parent,
name,
description,
autocomplete ? InteractionType.AUTOCOMPLETE : InteractionType.COMMAND,
options);
}
}

View File

@@ -33,7 +33,7 @@ public class AutoCompleteInteractionMethod extends InteractionMethod {
if (autocompleteOptionValue != null)
return autocompleteOptionValue;
return marinara.getWrapper().getContextObjectProvider().getComponentContextObject(context, type);
return marinara.getWrapper().getContextObjectProvider().getInteractionContextObject(context, type);
}
@Override

View File

@@ -7,7 +7,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import net.tomatentum.marinara.Marinara;
import net.tomatentum.marinara.checks.AppliedCheck;
@@ -69,7 +69,7 @@ public abstract class InteractionMethod {
try {
method.invoke(handler, getParameters(context));
}catch (IllegalAccessException | InvocationTargetException ex) {
logger.fatal(ex);
logger.error("InteractionMethod failed to run", ex);
}
this.appliedChecks.forEach(x -> x.post(context));

View File

@@ -3,7 +3,7 @@ package net.tomatentum.marinara.parser;
import java.lang.reflect.Method;
import java.util.function.Consumer;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import net.tomatentum.marinara.interaction.annotation.Button;
import net.tomatentum.marinara.util.LoggerUtil;

View File

@@ -6,7 +6,7 @@ import java.util.Arrays;
import java.util.Optional;
import java.util.function.Consumer;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import net.tomatentum.marinara.checks.AppliedCheck;
import net.tomatentum.marinara.checks.InteractionCheck;

View File

@@ -3,7 +3,7 @@ package net.tomatentum.marinara.parser;
import java.lang.reflect.Method;
import java.util.function.Consumer;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommand;
@@ -37,9 +37,8 @@ public class SlashCommandParser implements AnnotationParser {
.name(cmd.name())
.description(cmd.description())
.options(cmd.options())
.autocomplete(isAutoComplete)
.serverIds(cmd.serverIds())
.build();
.build(isAutoComplete);
if (ReflectionUtil.isAnnotationPresent(method, SubCommandGroup.class)) {
SubCommandGroup cmdGroup = ReflectionUtil.getAnnotation(method, SubCommandGroup.class);
@@ -57,11 +56,10 @@ public class SlashCommandParser implements AnnotationParser {
.name(subCmd.name())
.description(subCmd.description())
.options(subCmd.options())
.autocomplete(isAutoComplete)
.build();
.build(isAutoComplete);
}
logger.trace("Parsed using SlashCommandParser for method {} with the result:\n{}", ReflectionUtil.getFullMethodName(method), lastIdentifier.toString());
logger.trace("Parsed using SlashCommandParser for method {} with the result: {}", ReflectionUtil.getFullMethodName(method), lastIdentifier.toString());
consumer.accept((SlashCommandIdentifier) lastIdentifier);
}

View File

@@ -6,7 +6,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import io.leangen.geantyref.GenericTypeReflector;
import net.tomatentum.marinara.checks.InteractionCheck;

View File

@@ -3,7 +3,7 @@ package net.tomatentum.marinara.registry;
import java.util.HashSet;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;

View File

@@ -1,32 +1,35 @@
package net.tomatentum.marinara.registry;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import net.tomatentum.marinara.Marinara;
import net.tomatentum.marinara.interaction.InteractionHandler;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.commands.SlashCommandDefinition;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.interaction.ident.RootCommandIdentifier;
import net.tomatentum.marinara.interaction.ident.SlashCommandIdentifier;
import net.tomatentum.marinara.util.LoggerUtil;
import net.tomatentum.marinara.wrapper.LibraryWrapper;
import net.tomatentum.marinara.util.ObjectAggregator;
import net.tomatentum.marinara.wrapper.IdentifierProvider;
import net.tomatentum.marinara.interaction.methods.InteractionMethod;
public class InteractionRegistry {
private Logger logger = LoggerUtil.getLogger(getClass());
private Set<InteractionEntry> interactions;
private Marinara marinara;
private IdentifierProvider identifierProvider;
public InteractionRegistry(Marinara marinara) {
this.interactions = new HashSet<>();
this.marinara = marinara;
this.identifierProvider = marinara.getWrapper().createIdentifierProvider();
marinara.getWrapper().subscribeInteractions(this::handle);
}
@@ -37,11 +40,12 @@ public class InteractionRegistry {
for (Method method : interactionHandler.getClass().getMethods()) {
InteractionMethod iMethod = InteractionMethod.create(method, interactionHandler, marinara);
if (iMethod != null) {
Optional<InteractionEntry> entry = this.interactions.stream().filter(iMethod::equals).findFirst();
if (entry.isEmpty()) {
interactions.add(new InteractionEntry(iMethod.identifier()).addMethod(iMethod));
}else
entry.get().addMethod(iMethod);
Optional<InteractionEntry> oentry = this.interactions.stream()
.filter(i -> i.identifier().equals(iMethod.identifier()))
.findFirst();
InteractionEntry entry = oentry.orElse(new InteractionEntry(iMethod.identifier())).addMethod(iMethod);
if (oentry.isEmpty()) this.interactions.add(entry);
logger.debug("Added {} method from {}", iMethod.method().getName(), interactionHandler.getClass().getSimpleName());
}
}
@@ -49,34 +53,25 @@ public class InteractionRegistry {
}
public void registerCommands() {
List<SlashCommandDefinition> defs = new ArrayList<>();
List<SlashCommandIdentifier> slashIdentifiers = interactions.stream()
List<InteractionIdentifier> slashIdentifiers = interactions.stream()
.filter((x) -> x.type().equals(InteractionType.COMMAND))
.map((x) -> (SlashCommandIdentifier)x.identifier())
.map((x) -> x.identifier())
.toList();
slashIdentifiers.forEach((ident) -> {
Optional<SlashCommandDefinition> appDef = defs.stream()
.filter((x) -> x.rootIdentifier().equals(ident.rootNode()))
.findFirst();
SlashCommandDefinition[] defs = new ObjectAggregator<InteractionIdentifier, RootCommandIdentifier, SlashCommandDefinition>(
i -> Arrays.asList((RootCommandIdentifier)i.rootNode()),
SlashCommandDefinition::addIdentifier,
SlashCommandDefinition::new)
.aggregate(slashIdentifiers)
.toArray(SlashCommandDefinition[]::new);
if (appDef.isPresent())
appDef.get().addIdentifier(ident);
else
defs.add(
new SlashCommandDefinition((RootCommandIdentifier) ident.rootNode())
.addIdentifier(ident));
});
marinara.getWrapper().registerSlashCommands(defs.toArray(SlashCommandDefinition[]::new));
logger.info("Registered all SlashCommands");
marinara.getWrapper().getRegisterer().register(defs);
}
public void handle(Object context) {
logger.debug("Received {} interaction ", context);
LibraryWrapper wrapper = marinara.getWrapper();
interactions.forEach((e) -> {
if (wrapper.getInteractionIdentifier(context).equals(e.identifier())) {
if (this.identifierProvider.provide(context).equals(e.identifier())) {
logger.info("Running {} interaction using {}\ncontext: {}", e.type(), e.toString(), context.toString());
e.runAll(context);
}

View File

@@ -1,21 +1,14 @@
package net.tomatentum.marinara.util;
import java.util.Properties;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.simple.SimpleLogger;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.apache.logging.log4j.util.ProviderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.NOPLoggerFactory;
public class LoggerUtil {
public static Logger getLogger(String name) {
if (ProviderUtil.hasProviders()) {
return LogManager.getLogger(name);
}else
return new SimpleLogger(name, Level.DEBUG, true, false, true, true, "yyyy-MM-dd HH:mm:ss.SSSZ", null,
new PropertiesUtil(new Properties()), System.out);
if (LoggerFactory.getILoggerFactory() instanceof NOPLoggerFactory)
return new SimpleLogger(name);
return LoggerFactory.getLogger(name);
}
public static Logger getLogger(Class<?> clazz) {

View File

@@ -0,0 +1,46 @@
package net.tomatentum.marinara.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
public class ObjectAggregator<O, K, V> {
private Function<O, Iterable<K>> keySupplier;
private BiConsumer<V, O> valueConsumer;
private Function<K, V> defaultGenerator;
public ObjectAggregator(
Function<O, Iterable<K>> keySupplier,
BiConsumer<V, O> valueConsumer,
Function<K, V> defaultGenerator) {
this.keySupplier = keySupplier;
this.valueConsumer = valueConsumer;
this.defaultGenerator = defaultGenerator;
}
public ObjectAggregator(
Function<O, Iterable<K>> keySupplier,
BiConsumer<V, O> valueConsumer,
Supplier<V> defaultGenerator) {
this.keySupplier = keySupplier;
this.valueConsumer = valueConsumer;
this.defaultGenerator = _ -> defaultGenerator.get();
}
public Collection<V> aggregate(Iterable<O> iterator) {
Map<K, V> map = new HashMap<>();
for (O element : iterator) {
Iterable<K> keys = this.keySupplier.apply(element);
for (K key : keys) {
V value = map.getOrDefault(key, this.defaultGenerator.apply(key));
this.valueConsumer.accept(value, element);
map.putIfAbsent(key, value);
}
}
return map.values();
}
}

View File

@@ -0,0 +1,15 @@
package net.tomatentum.marinara.util;
import java.util.ArrayList;
import java.util.function.Function;
public class ObjectListAggregator<O, K, V> extends ObjectAggregator<O, K, ArrayList<V>> {
public ObjectListAggregator(Function<O, Iterable<K>> keySupplier, Function<O, V> valueConsumer) {
super(keySupplier,
(l, o) -> l.add(valueConsumer.apply(o)),
() -> new ArrayList<>());
}
}

View File

@@ -102,6 +102,6 @@ public final class ReflectionUtil {
}
public static String getFullMethodName(Method method) {
return method.getClass().getName() + "." + method.getName();
return method.getDeclaringClass().getName() + "." + method.getName();
}
}

View File

@@ -0,0 +1,55 @@
package net.tomatentum.marinara.util;
import org.slf4j.Marker;
import org.slf4j.event.Level;
import org.slf4j.helpers.LegacyAbstractLogger;
import org.slf4j.helpers.MessageFormatter;
public class SimpleLogger extends LegacyAbstractLogger {
private String name;
public SimpleLogger(String name) {
this.name = name;
}
@Override
public boolean isTraceEnabled() {
return true;
}
@Override
public boolean isDebugEnabled() {
return true;
}
@Override
public boolean isInfoEnabled() {
return true;
}
@Override
public boolean isWarnEnabled() {
return true;
}
@Override
public boolean isErrorEnabled() {
return true;
}
@Override
protected String getFullyQualifiedCallerName() {
return this.name;
}
@Override
protected void handleNormalizedLoggingCall(Level level, Marker marker, String messagePattern, Object[] arguments,
Throwable throwable) {
String formatted = MessageFormatter.basicArrayFormat(messagePattern, arguments);
System.out.println("[%s] %s => %s".formatted(level, this.name, formatted));
}
}

View File

@@ -0,0 +1,70 @@
package net.tomatentum.marinara.wrapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import net.tomatentum.marinara.interaction.commands.SlashCommandDefinition;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOptionChoice;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.interaction.ident.RootCommandIdentifier;
import net.tomatentum.marinara.interaction.ident.SlashCommandIdentifier;
import net.tomatentum.marinara.util.LoggerUtil;
public class CommandConverter<A extends Object, O extends Object, C extends Object> {
public static <A, O, C> CommandConverter<A, O, C> of(Spec<A, O, C> spec) {
return new CommandConverter<>(spec);
}
private Logger logger = LoggerUtil.getLogger(getClass());
private Spec<A, O, C> spec;
CommandConverter(Spec<A, O, C> spec) {
this.spec = spec;
}
public A convert(SlashCommandDefinition def) {
logger.debug("Converting command {}", def);
List<O> options = new ArrayList<>();
if (!def.isRootCommand()) {
Arrays.stream(def.getSubCommands()).map(this::convertSubCommand).forEach(options::add);
Arrays.stream(def.getSubCommandGroups()).map(x -> this.convertSubCommandGroup(def, x)).forEach(options::add);
}else
Arrays.stream(def.rootIdentifier().options()).map(this::convertOption).forEach(options::add);
return spec.convertCommand(def.rootIdentifier(), options);
}
private O convertSubCommandGroup(SlashCommandDefinition def, InteractionIdentifier identifier) {
logger.debug("Converting subCommandGroup {} of {}", identifier, def);
SlashCommandIdentifier[] subCommands = def.getSubCommands(identifier.name());
List<O> convertedSubCommands = Arrays.stream(subCommands).map(this::convertSubCommand).toList();
return spec.convertSubCommandGroup(identifier, convertedSubCommands);
}
private O convertSubCommand(SlashCommandIdentifier identifier) {
logger.debug("Converting subCommand {}", identifier);
List<O> options = Arrays.stream(identifier.options()).map(this::convertOption).toList();
return spec.convertSubCommand(identifier, options);
}
private O convertOption(SlashCommandOption option) {
logger.debug("Converting option {}", option);
List<C> choices = Arrays.stream(SlashCommandDefinition.getActualChoices(option)).map(spec::convertChoice).toList();
return spec.convertOption(option, choices);
}
public static interface Spec<A extends Object, O extends Object, C extends Object> {
public A convertCommand(RootCommandIdentifier rootIdentifier, List<O> options);
public O convertSubCommandGroup(InteractionIdentifier identifier, List<O> subCommands);
public O convertSubCommand(InteractionIdentifier identifier, List<O> options);
public O convertOption(SlashCommandOption option, List<C> choices);
public C convertChoice(SlashCommandOptionChoice choice);
}
}

View File

@@ -0,0 +1,51 @@
package net.tomatentum.marinara.wrapper;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import net.tomatentum.marinara.interaction.commands.SlashCommandDefinition;
import net.tomatentum.marinara.util.LoggerUtil;
import net.tomatentum.marinara.util.ObjectAggregator;
public class CommandRegisterer<A extends Object> {
public static <A extends Object> CommandRegisterer<A> of(Strategy<A> strategy, CommandConverter<A, ?, ?> converter) {
return new CommandRegisterer<A>(strategy, converter);
}
private Logger logger = LoggerUtil.getLogger(getClass());
private Strategy<A> strategy;
private CommandConverter<A, ?, ?> converter;
CommandRegisterer(Strategy<A> strategy, CommandConverter<A, ?, ?> converter) {
this.strategy = strategy;
this.converter = converter;
}
public void register(SlashCommandDefinition[] slashDefs) {
Set<ServerCommandList<A>> serverCommands = new ObjectAggregator<SlashCommandDefinition, Long, ServerCommandList<A>>(
def -> Arrays.stream(def.serverIds()).boxed().toList(),
(l, o) -> l.add(converter.convert(o)),
ServerCommandList::new)
.aggregate(Arrays.asList(slashDefs)).stream()
.collect(Collectors.toSet());
Set<A> globalCommands = Arrays.stream(slashDefs)
.filter(x -> x.serverIds().length <= 0)
.map(converter::convert)
.collect(Collectors.toSet());
serverCommands.forEach(strategy::registerServer);
strategy.registerGlobal(globalCommands);
logger.info("Registered all SlashCommands");
}
public interface Strategy<A extends Object> {
void registerServer(ServerCommandList<A> commands);
void registerGlobal(Set<A> defs);
}
}

View File

@@ -0,0 +1,72 @@
package net.tomatentum.marinara.wrapper;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import io.leangen.geantyref.GenericTypeReflector;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.util.LoggerUtil;
import net.tomatentum.marinara.util.ReflectionUtil;
public class IdentifierProvider {
public static IdentifierProvider of(Converter<?>... converter) {
return new IdentifierProvider(Arrays.asList(converter));
}
private Map<Class<?>, Converter<?>> converter;
private Logger logger = LoggerUtil.getLogger(getClass());
private IdentifierProvider(List<Converter<?>> converter) {
this.converter = new HashMap<>();
for (Converter<?> conv : converter) {
if (conv.getClass().getName().contains("$$Lambda"))
throw new IllegalArgumentException("Lambdas cannot be used for IdentifierConverter because of Type erasure.");
Type type = GenericTypeReflector.getExactSuperType(conv.getClass(), Converter.class);
Type parameterType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
if (!(parameterType instanceof Class))
throw new IllegalArgumentException("Only full Class types are supported by IdentiferConverters");
this.converter.put((Class<?>) parameterType, conv);
}
}
public InteractionIdentifier provide(Object context) {
Type type = ReflectionUtil.getMostSpecificClass(
converter.keySet().stream().filter(x -> x.isAssignableFrom(context.getClass())).toArray(Class<?>[]::new),
context.getClass());
if (type == null)
logger.debug("No Identifier converter found for context {}", context.getClass().toString());
@SuppressWarnings("unchecked")
Converter<Object> conv = (Converter<Object>) converter.get(type);
return conv.convert(context);
}
@FunctionalInterface
public interface Converter<T extends Object> {
InteractionIdentifier convert(T context);
}
public static class LambdaWrapper<T extends Object> implements Converter<T> {
private Converter<T> converter;
LambdaWrapper(Converter<T> converter) {
this.converter = converter;
}
@Override
public InteractionIdentifier convert(T context) {
return this.converter.convert(context);
}
}
}

View File

@@ -3,16 +3,12 @@ package net.tomatentum.marinara.wrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import net.tomatentum.marinara.interaction.commands.SlashCommandDefinition;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
public abstract class LibraryWrapper {
private List<Consumer<Object>> interactionSubscriber;
protected LibraryWrapper() {
interactionSubscriber = new ArrayList<>();
this.interactionSubscriber = new ArrayList<>();
}
public void handleInteraction(Object context) {
@@ -26,9 +22,8 @@ public abstract class LibraryWrapper {
interactionSubscriber.remove(consumer);
}
public abstract void registerSlashCommands(SlashCommandDefinition[] defs);
public abstract InteractionIdentifier getInteractionIdentifier(Object context);
public abstract CommandRegisterer<?> getRegisterer();
public abstract IdentifierProvider createIdentifierProvider();
public abstract ContextObjectProvider getContextObjectProvider();
}

View File

@@ -0,0 +1,16 @@
package net.tomatentum.marinara.wrapper;
import java.util.HashSet;
public class ServerCommandList<A> extends HashSet<A>{
private long serverId;
public ServerCommandList(long serverId) {
this.serverId = serverId;
}
public long serverId() {
return serverId;
}
}

View File

@@ -19,11 +19,12 @@ dependencies {
// Use JUnit Jupiter for testing.
testImplementation(libs.junit.jupiter)
testImplementation(libs.mockito)
testImplementation(libs.discord4j)
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
implementation(libs.log4j)
implementation(libs.slf4j)
implementation(libs.discord4j) {
// exclude(module="discord4j-voice")
exclude(module="discord4j-voice")
}
implementation(libs.geantyref)
implementation(project(":lib"))

View File

@@ -0,0 +1,79 @@
package net.tomatentum.marinara.wrapper.discord4j;
import java.util.List;
import discord4j.core.object.command.ApplicationCommandOption.Type;
import discord4j.discordjson.json.ApplicationCommandOptionChoiceData;
import discord4j.discordjson.json.ApplicationCommandOptionData;
import discord4j.discordjson.json.ApplicationCommandRequest;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOptionChoice;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.interaction.ident.RootCommandIdentifier;
import net.tomatentum.marinara.wrapper.CommandConverter;
public class Discord4JConverterSpec implements CommandConverter.Spec<ApplicationCommandRequest, ApplicationCommandOptionData, ApplicationCommandOptionChoiceData> {
@Override
public ApplicationCommandRequest convertCommand(RootCommandIdentifier rootIdentifier,
List<ApplicationCommandOptionData> options) {
return ApplicationCommandRequest.builder()
.name(rootIdentifier.name())
.description(rootIdentifier.description())
.options(options)
.build();
}
@Override
public ApplicationCommandOptionData convertSubCommandGroup(InteractionIdentifier identifier,
List<ApplicationCommandOptionData> subCommands) {
return ApplicationCommandOptionData.builder()
.type(Type.SUB_COMMAND_GROUP.getValue())
.name(identifier.name())
.description(identifier.description())
.options(subCommands)
.build();
}
@Override
public ApplicationCommandOptionData convertSubCommand(InteractionIdentifier identifier,
List<ApplicationCommandOptionData> options) {
return ApplicationCommandOptionData.builder()
.type(Type.SUB_COMMAND_GROUP.getValue())
.name(identifier.name())
.description(identifier.description())
.options(options)
.build();
}
@Override
public ApplicationCommandOptionData convertOption(SlashCommandOption option,
List<ApplicationCommandOptionChoiceData> choices) {
Type type = Type.of(option.type().getValue());
return ApplicationCommandOptionData.builder()
.type(type.getValue())
.name(option.name())
.description(option.description())
.required(option.required())
.autocomplete(option.autocomplete())
.minLength(Double.valueOf(option.range().min()).intValue())
.minValue(option.range().min())
.maxLength(Double.valueOf(option.range().max()).intValue())
.maxValue(option.range().max())
.choices(choices)
.build();
}
@Override
public ApplicationCommandOptionChoiceData convertChoice(SlashCommandOptionChoice choice) {
var builder = ApplicationCommandOptionChoiceData.builder().name(choice.name());
if (choice.longValue() != Long.MAX_VALUE)
builder.value(choice.longValue());
if (choice.doubleValue() != Double.MAX_VALUE)
builder.value(choice.doubleValue());
if (!choice.stringValue().isEmpty())
builder.value(choice.stringValue());
return builder.build();
}
}

View File

@@ -0,0 +1,32 @@
package net.tomatentum.marinara.wrapper.discord4j;
import java.util.ArrayList;
import java.util.Set;
import discord4j.core.GatewayDiscordClient;
import discord4j.discordjson.json.ApplicationCommandRequest;
import discord4j.rest.service.ApplicationService;
import net.tomatentum.marinara.wrapper.CommandRegisterer;
import net.tomatentum.marinara.wrapper.ServerCommandList;
public class Discord4JRegistererStrategy implements CommandRegisterer.Strategy<ApplicationCommandRequest> {
private ApplicationService appService;
private long applicationId;
public Discord4JRegistererStrategy(GatewayDiscordClient api) {
this.appService = api.getRestClient().getApplicationService();
this.applicationId = api.getRestClient().getApplicationId().block();
}
@Override
public void registerServer(ServerCommandList<ApplicationCommandRequest> commands) {
appService.bulkOverwriteGuildApplicationCommand(applicationId, commands.serverId(), new ArrayList<>(commands));
}
@Override
public void registerGlobal(Set<ApplicationCommandRequest> defs) {
appService.bulkOverwriteGlobalApplicationCommand(applicationId, new ArrayList<>(defs));
}
}

View File

@@ -1,34 +1,25 @@
package net.tomatentum.marinara.wrapper.discord4j;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.function.Function;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import discord4j.core.GatewayDiscordClient;
import discord4j.core.event.domain.interaction.ButtonInteractionEvent;
import discord4j.core.event.domain.interaction.ChatInputAutoCompleteEvent;
import discord4j.core.event.domain.interaction.ChatInputInteractionEvent;
import discord4j.core.event.domain.interaction.InteractionCreateEvent;
import discord4j.core.object.command.ApplicationCommandInteractionOption;
import discord4j.core.object.command.ApplicationCommandOption.Type;
import discord4j.discordjson.json.ApplicationCommandOptionChoiceData;
import discord4j.discordjson.json.ApplicationCommandOptionData;
import discord4j.discordjson.json.ApplicationCommandRequest;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.commands.SlashCommandDefinition;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOptionChoice;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.interaction.ident.RootCommandIdentifier;
import net.tomatentum.marinara.interaction.ident.SlashCommandIdentifier;
import net.tomatentum.marinara.util.LoggerUtil;
import net.tomatentum.marinara.wrapper.CommandConverter;
import net.tomatentum.marinara.wrapper.CommandRegisterer;
import net.tomatentum.marinara.wrapper.ContextObjectProvider;
import net.tomatentum.marinara.wrapper.IdentifierProvider;
import net.tomatentum.marinara.wrapper.LibraryWrapper;
import net.tomatentum.marinara.wrapper.discord4j.identifierconverter.AutocompleteIdentifierConverter;
import net.tomatentum.marinara.wrapper.discord4j.identifierconverter.ButtonIdentifierConverter;
import net.tomatentum.marinara.wrapper.discord4j.identifierconverter.SlashCommandIdentifierConverter;
public class Discord4JWrapper extends LibraryWrapper {
@@ -42,156 +33,37 @@ public class Discord4JWrapper extends LibraryWrapper {
.filter(o -> !o.getType().equals(Type.SUB_COMMAND) && !o.getType().equals(Type.SUB_COMMAND_GROUP))
.toList();
private GatewayDiscordClient api;
private Discord4JContextObjectProvider contextObjectProvider;
private CommandRegisterer<ApplicationCommandRequest> commandRegisterer;
private Logger logger = LoggerUtil.getLogger(getClass());
public Discord4JWrapper(GatewayDiscordClient api) {
this.api = api;
this.contextObjectProvider = new Discord4JContextObjectProvider();
if (api != null)
var converter = CommandConverter.of(new Discord4JConverterSpec());
if (api != null) {
this.commandRegisterer = CommandRegisterer.of(new Discord4JRegistererStrategy(api), converter);
api.on(InteractionCreateEvent.class)
.subscribe(event -> handleInteraction(event));
else
}else
logger.warn("GatewayDiscordClient was null so no Events were subscribed to.");
logger.info("Discord4J wrapper loaded!");
}
@Override
public void registerSlashCommands(SlashCommandDefinition[] defs) {
HashMap<Long, List<ApplicationCommandRequest>> serverCommands = new HashMap<>();
List<ApplicationCommandRequest> globalCommands = new ArrayList<>();
long applicationId = api.getRestClient().getApplicationId().block();
for (SlashCommandDefinition slashCommandDefinition : defs) {
ApplicationCommandRequest request = convertSlashCommand(slashCommandDefinition);
if (slashCommandDefinition.rootIdentifier().serverIds().length > 0) {
for (long serverId : slashCommandDefinition.rootIdentifier().serverIds()) {
serverCommands.putIfAbsent(serverId, new ArrayList<>());
serverCommands.get(serverId).add(request);
}
}else
globalCommands.add(request);
}
for (long serverId : serverCommands.keySet()) {
api.getRestClient().getApplicationService().bulkOverwriteGuildApplicationCommand(applicationId, serverId, serverCommands.get(serverId));
}
api.getRestClient().getApplicationService().bulkOverwriteGlobalApplicationCommand(applicationId, globalCommands);
public CommandRegisterer<?> getRegisterer() {
return this.commandRegisterer;
}
@Override
public InteractionIdentifier getInteractionIdentifier(Object context) {
if (context instanceof ButtonInteractionEvent) {
ButtonInteractionEvent interaction = (ButtonInteractionEvent) context;
return InteractionIdentifier.builder().name(interaction.getCustomId()).type(InteractionType.BUTTON).build();
}
List<ApplicationCommandInteractionOption> options;
String commandName;
boolean isAutocomplete = false;
if (context instanceof ChatInputInteractionEvent) {
ChatInputInteractionEvent interaction = (ChatInputInteractionEvent) context;
options = SUB_FILTER.apply(interaction.getOptions());
commandName = interaction.getCommandName();
}else if (context instanceof ChatInputAutoCompleteEvent) {
ChatInputAutoCompleteEvent interaction = (ChatInputAutoCompleteEvent) context;
options = SUB_FILTER.apply(interaction.getOptions());
commandName = interaction.getCommandName();
isAutocomplete = true;
}else
return null;
InteractionIdentifier last = InteractionIdentifier.slashBuilder().name(commandName).autocomplete(isAutocomplete).build();
if (!options.isEmpty()) {
List<ApplicationCommandInteractionOption> sub_options = SUB_FILTER.apply(options.getFirst().getOptions());
if (!sub_options.isEmpty()) {
last = InteractionIdentifier.builder()
.name(options.getFirst().getName())
.type(isAutocomplete ? InteractionType.AUTOCOMPLETE : InteractionType.COMMAND)
.parent(last).build();
last = InteractionIdentifier.slashBuilder()
.name(sub_options.getFirst().getName())
.autocomplete(isAutocomplete)
.parent(last).build();
}else
last = InteractionIdentifier.slashBuilder()
.name(options.getFirst().getName())
.autocomplete(isAutocomplete)
.parent(last).build();
}
return last;
}
private ApplicationCommandRequest convertSlashCommand(SlashCommandDefinition def) {
List<ApplicationCommandOptionData> options = new ArrayList<>();
RootCommandIdentifier cmd = def.rootIdentifier();
if (!def.isRootCommand()) {
Arrays.stream(def.getSubCommands(null)).map(this::convertSubCommandDef).forEach(options::add);
Arrays.stream(def.getSubCommandGroups()).map((x) -> convertSubCommandGroupDef(def, x)).forEach(options::add);
}else {
Arrays.stream(cmd.options()).map(this::convertOptionDef).forEach(options::add);
}
return ApplicationCommandRequest.builder()
.name(cmd.name())
.description(cmd.description())
.options(options)
.build();
}
private ApplicationCommandOptionData convertSubCommandGroupDef(SlashCommandDefinition def, SlashCommandIdentifier subGroup) {
SlashCommandIdentifier[] subCommands = def.getSubCommands(subGroup.name());
List<ApplicationCommandOptionData> convertedSubCommands = Arrays.stream(subCommands).map(this::convertSubCommandDef).toList();
return ApplicationCommandOptionData.builder()
.type(Type.SUB_COMMAND_GROUP.getValue())
.name(subGroup.name())
.description(subGroup.description())
.options(convertedSubCommands)
.build();
}
private ApplicationCommandOptionData convertSubCommandDef(SlashCommandIdentifier sub) {
List<ApplicationCommandOptionData> convertedOptions = Arrays.stream(sub.options()).map(this::convertOptionDef).toList();
return ApplicationCommandOptionData.builder()
.type(Type.SUB_COMMAND_GROUP.getValue())
.name(sub.name())
.description(sub.description())
.options(convertedOptions)
.build();
}
private ApplicationCommandOptionData convertOptionDef(SlashCommandOption option) {
Type type = Enum.valueOf(Type.class, option.type().toString());
return ApplicationCommandOptionData.builder()
.type(type.getValue())
.name(option.name())
.description(option.description())
.required(option.required())
.autocomplete(option.autocomplete())
.choices(convertChoices(option))
.build();
}
private List<ApplicationCommandOptionChoiceData> convertChoices(SlashCommandOption option) {
List<ApplicationCommandOptionChoiceData> convertedChoices = new ArrayList<>();
for (SlashCommandOptionChoice choice : SlashCommandDefinition.getActualChoices(option)) {
var builder = ApplicationCommandOptionChoiceData.builder();
builder.name(choice.name());
if (choice.longValue() != Long.MAX_VALUE)
builder.value(choice.longValue());
if (choice.doubleValue() != Double.MAX_VALUE)
builder.value(choice.doubleValue());
if (!choice.stringValue().isEmpty())
builder.value(choice.stringValue());
convertedChoices.add(builder.build());
}
return convertedChoices;
public IdentifierProvider createIdentifierProvider() {
return IdentifierProvider.of(
new SlashCommandIdentifierConverter(),
new AutocompleteIdentifierConverter(),
new ButtonIdentifierConverter()
);
}
@Override

View File

@@ -0,0 +1,38 @@
package net.tomatentum.marinara.wrapper.discord4j.identifierconverter;
import java.util.List;
import discord4j.core.event.domain.interaction.ChatInputAutoCompleteEvent;
import discord4j.core.object.command.ApplicationCommandInteractionOption;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.wrapper.IdentifierProvider;
import net.tomatentum.marinara.wrapper.discord4j.Discord4JWrapper;
public class AutocompleteIdentifierConverter implements IdentifierProvider.Converter<ChatInputAutoCompleteEvent> {
@Override
public InteractionIdentifier convert(ChatInputAutoCompleteEvent context) {
List<ApplicationCommandInteractionOption> options = Discord4JWrapper.SUB_FILTER.apply(context.getOptions());
String commandName = context.getCommandName();
if (!options.isEmpty()) {
List<ApplicationCommandInteractionOption> sub_options = Discord4JWrapper.SUB_FILTER.apply(options.getFirst().getOptions());
if (!sub_options.isEmpty())
return InteractionIdentifier.createHierarchy(
InteractionType.AUTOCOMPLETE,
commandName,
options.getFirst().getName(),
sub_options.getFirst().getName());
else
return InteractionIdentifier.createHierarchy(
InteractionType.AUTOCOMPLETE,
commandName,
options.getFirst().getName());
}else
return InteractionIdentifier.createHierarchy(
InteractionType.AUTOCOMPLETE,
commandName);
}
}

View File

@@ -0,0 +1,15 @@
package net.tomatentum.marinara.wrapper.discord4j.identifierconverter;
import discord4j.core.event.domain.interaction.ButtonInteractionEvent;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.wrapper.IdentifierProvider;
public class ButtonIdentifierConverter implements IdentifierProvider.Converter<ButtonInteractionEvent> {
@Override
public InteractionIdentifier convert(ButtonInteractionEvent context) {
return InteractionIdentifier.builder().name(context.getCustomId()).type(InteractionType.BUTTON).build();
}
}

View File

@@ -0,0 +1,39 @@
package net.tomatentum.marinara.wrapper.discord4j.identifierconverter;
import java.util.List;
import discord4j.core.event.domain.interaction.ChatInputInteractionEvent;
import discord4j.core.object.command.ApplicationCommandInteractionOption;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.wrapper.IdentifierProvider;
import net.tomatentum.marinara.wrapper.discord4j.Discord4JWrapper;
public class SlashCommandIdentifierConverter implements IdentifierProvider.Converter<ChatInputInteractionEvent> {
@Override
public InteractionIdentifier convert(ChatInputInteractionEvent context) {
List<ApplicationCommandInteractionOption> options = Discord4JWrapper.SUB_FILTER.apply(context.getOptions());
String commandName = context.getCommandName();
if (!options.isEmpty()) {
List<ApplicationCommandInteractionOption> sub_options = Discord4JWrapper.SUB_FILTER.apply(options.getFirst().getOptions());
if (!sub_options.isEmpty())
return InteractionIdentifier.createHierarchy(
InteractionType.COMMAND,
commandName,
options.getFirst().getName(),
sub_options.getFirst().getName());
else
return InteractionIdentifier.createHierarchy(
InteractionType.COMMAND,
commandName,
options.getFirst().getName());
}else
return InteractionIdentifier.createHierarchy(
InteractionType.COMMAND,
commandName);
}
}

View File

@@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import discord4j.core.event.domain.interaction.ChatInputInteractionEvent;
import net.tomatentum.marinara.interaction.InteractionHandler;
import net.tomatentum.marinara.interaction.commands.annotation.CommandChoices;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommand;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption;
import net.tomatentum.marinara.interaction.commands.option.SlashCommandOptionType;
@@ -20,7 +21,7 @@ public class TestCommand implements InteractionHandler {
name = "foo",
description = "foo bar is very fooby",
type = SlashCommandOptionType.STRING,
choiceEnum = TestChoiceEnum.class
choices = @CommandChoices(cenum = TestChoiceEnum.class)
)
}
)

View File

@@ -21,7 +21,7 @@ dependencies {
testImplementation(libs.mockito)
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
implementation(libs.log4j)
implementation(libs.slf4j)
implementation(libs.javacord)
implementation(libs.geantyref)
implementation(project(":lib"))

View File

@@ -0,0 +1,77 @@
package net.tomatentum.marinara.wrapper.javacord;
import java.util.List;
import org.javacord.api.interaction.SlashCommand;
import org.javacord.api.interaction.SlashCommandBuilder;
import org.javacord.api.interaction.SlashCommandOption;
import org.javacord.api.interaction.SlashCommandOptionBuilder;
import org.javacord.api.interaction.SlashCommandOptionChoice;
import org.javacord.api.interaction.SlashCommandOptionChoiceBuilder;
import org.javacord.api.interaction.SlashCommandOptionType;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.interaction.ident.RootCommandIdentifier;
import net.tomatentum.marinara.wrapper.CommandConverter;
public class JavacordConverterSpec implements CommandConverter.Spec<SlashCommandBuilder, SlashCommandOption, SlashCommandOptionChoice> {
@Override
public SlashCommandBuilder convertCommand(RootCommandIdentifier rootIdentifier, List<SlashCommandOption> options) {
return SlashCommand.with(rootIdentifier.name(), rootIdentifier.description(), options);
}
@Override
public SlashCommandOption convertSubCommandGroup(InteractionIdentifier identifier,
List<SlashCommandOption> subCommands) {
return SlashCommandOption.createWithOptions(
SlashCommandOptionType.SUB_COMMAND_GROUP,
identifier.name(),
identifier.description(),
subCommands);
}
@Override
public SlashCommandOption convertSubCommand(InteractionIdentifier identifier, List<SlashCommandOption> options) {
return SlashCommandOption.createWithOptions(
SlashCommandOptionType.SUB_COMMAND,
identifier.name(),
identifier.description(),
options);
}
@Override
public SlashCommandOption convertOption(
net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption option,
List<SlashCommandOptionChoice> choices) {
SlashCommandOptionType type = SlashCommandOptionType.fromValue(option.type().getValue());
return new SlashCommandOptionBuilder()
.setType(type)
.setName(option.name())
.setDescription(option.description())
.setRequired(option.required())
.setAutocompletable(option.autocomplete())
.setMinLength(Double.valueOf(option.range().min()).longValue())
.setDecimalMinValue(option.range().min())
.setMaxLength(Double.valueOf(option.range().max()).longValue())
.setDecimalMaxValue(option.range().max())
.setChoices(choices)
.build();
}
@Override
public SlashCommandOptionChoice convertChoice(
net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOptionChoice choice) {
SlashCommandOptionChoiceBuilder builder = new SlashCommandOptionChoiceBuilder().setName(choice.name());
if (choice.longValue() != Long.MAX_VALUE)
builder.setValue(choice.longValue());
/*
not yet available
if (choice.doubleValue() != Double.MAX_VALUE)
builder.setValue(choice.doubleValue());
*/
if (!choice.stringValue().isEmpty())
builder.setValue(choice.stringValue());
return builder.build();
}
}

View File

@@ -0,0 +1,29 @@
package net.tomatentum.marinara.wrapper.javacord;
import java.util.Set;
import org.javacord.api.DiscordApi;
import org.javacord.api.interaction.SlashCommandBuilder;
import net.tomatentum.marinara.wrapper.CommandRegisterer;
import net.tomatentum.marinara.wrapper.ServerCommandList;
public class JavacordRegistererStrategy implements CommandRegisterer.Strategy<SlashCommandBuilder> {
private DiscordApi api;
public JavacordRegistererStrategy(DiscordApi api) {
this.api = api;
}
@Override
public void registerServer(ServerCommandList<SlashCommandBuilder> commands) {
api.bulkOverwriteServerApplicationCommands(commands.serverId(), commands);
}
@Override
public void registerGlobal(Set<SlashCommandBuilder> defs) {
api.bulkOverwriteGlobalApplicationCommands(defs);
}
}

View File

@@ -1,179 +1,50 @@
package net.tomatentum.marinara.wrapper.javacord;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.javacord.api.DiscordApi;
import org.javacord.api.interaction.AutocompleteInteraction;
import org.javacord.api.interaction.ButtonInteraction;
import org.javacord.api.interaction.SlashCommandBuilder;
import org.javacord.api.interaction.SlashCommandInteraction;
import org.javacord.api.interaction.SlashCommandInteractionOption;
import org.javacord.api.interaction.SlashCommandOptionBuilder;
import org.javacord.api.interaction.SlashCommandOptionChoiceBuilder;
import org.javacord.api.interaction.SlashCommandOptionType;
import org.slf4j.Logger;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.commands.SlashCommandDefinition;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOptionChoice;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.interaction.ident.RootCommandIdentifier;
import net.tomatentum.marinara.interaction.ident.SlashCommandIdentifier;
import net.tomatentum.marinara.wrapper.CommandConverter;
import net.tomatentum.marinara.wrapper.CommandRegisterer;
import net.tomatentum.marinara.wrapper.ContextObjectProvider;
import net.tomatentum.marinara.wrapper.IdentifierProvider;
import net.tomatentum.marinara.util.LoggerUtil;
import net.tomatentum.marinara.wrapper.LibraryWrapper;
import net.tomatentum.marinara.wrapper.javacord.identifierconverter.AutocompleteIdentifierConverter;
import net.tomatentum.marinara.wrapper.javacord.identifierconverter.ButtonIdentifierConverter;
import net.tomatentum.marinara.wrapper.javacord.identifierconverter.SlashCommandIdentifierConverter;
public class JavacordWrapper extends LibraryWrapper {
private DiscordApi api;
private JavacordContextObjectProvider contextObjectProvider;
private CommandRegisterer<SlashCommandBuilder> commandRegisterer;
private Logger logger = LoggerUtil.getLogger(getClass());
public JavacordWrapper(DiscordApi api) {
this.api = api;
this.contextObjectProvider = new JavacordContextObjectProvider();
if (api != null)
var converter = CommandConverter.of(new JavacordConverterSpec());
if (api != null) {
this.commandRegisterer = CommandRegisterer.of(new JavacordRegistererStrategy(api), converter);
api.addInteractionCreateListener((e) -> handleInteraction(e.getInteraction()));
else
}else
logger.warn("DiscordApi was null so no Events were subscribed to.");
logger.info("Javacord wrapper loaded!");
}
@Override
public void registerSlashCommands(SlashCommandDefinition[] defs) {
HashMap<Long, Set<SlashCommandBuilder>> serverCommands = new HashMap<>();
Set<SlashCommandBuilder> globalCommands = new HashSet<>();
for (SlashCommandDefinition slashCommandDefinition : defs) {
SlashCommandBuilder builder = convertSlashCommand(slashCommandDefinition);
if (slashCommandDefinition.rootIdentifier().serverIds().length > 0) {
for (long serverId : slashCommandDefinition.rootIdentifier().serverIds()) {
serverCommands.putIfAbsent(serverId, new HashSet<>());
serverCommands.get(serverId).add(builder);
}
}else
globalCommands.add(builder);
}
for (long serverId : serverCommands.keySet()) {
api.bulkOverwriteServerApplicationCommands(serverId, serverCommands.get(serverId));
}
api.bulkOverwriteGlobalApplicationCommands(globalCommands);
public CommandRegisterer<?> getRegisterer() {
return this.commandRegisterer;
}
@Override
public InteractionIdentifier getInteractionIdentifier(Object context) {
if (context instanceof ButtonInteraction) {
ButtonInteraction button = (ButtonInteraction) context;
return InteractionIdentifier.builder().name(button.getCustomId()).type(InteractionType.BUTTON).build();
}
if (!(context instanceof SlashCommandInteraction))
return null;
boolean isAutocomplete = false;
if (context instanceof AutocompleteInteraction)
isAutocomplete = true;
SlashCommandInteraction interaction = (SlashCommandInteraction) context;
InteractionIdentifier lastIdentifier = InteractionIdentifier.rootBuilder()
.name(interaction.getCommandName())
.autocomplete(isAutocomplete)
.build();
List<SlashCommandInteractionOption> options = interaction.getOptions();
if (!options.isEmpty()) {
if (!options.getFirst().getArguments().isEmpty()) {
lastIdentifier = InteractionIdentifier.builder()
.name(options.getFirst().getName())
.type(isAutocomplete ? InteractionType.AUTOCOMPLETE : InteractionType.COMMAND)
.parent(lastIdentifier)
.build();
lastIdentifier = InteractionIdentifier.slashBuilder()
.name(options.getFirst().getOptions().getFirst().getName())
.autocomplete(isAutocomplete)
.parent(lastIdentifier)
.build();
}else
lastIdentifier = InteractionIdentifier.slashBuilder()
.name(options.getFirst().getName())
.autocomplete(isAutocomplete)
.parent(lastIdentifier)
.build();
}
return lastIdentifier;
}
private SlashCommandBuilder convertSlashCommand(SlashCommandDefinition def) {
List<org.javacord.api.interaction.SlashCommandOption> options = new ArrayList<>();
RootCommandIdentifier cmd = def.rootIdentifier();
if (!def.isRootCommand()) {
Arrays.stream(def.getSubCommands(null)).map(this::convertSubCommandDef).forEach(options::add);
Arrays.stream(def.getSubCommandGroups()).map((x) -> convertSubCommandGroupDef(def, x)).forEach(options::add);
}else {
Arrays.stream(cmd.options()).map(this::convertOptionDef).forEach(options::add);
}
return org.javacord.api.interaction.SlashCommand.with(cmd.name(), cmd.description(), options);
}
private org.javacord.api.interaction.SlashCommandOption convertSubCommandGroupDef(SlashCommandDefinition def, SlashCommandIdentifier subGroup) {
SlashCommandIdentifier[] subCommands = def.getSubCommands(subGroup.name());
List<org.javacord.api.interaction.SlashCommandOption> convertedSubCommands = Arrays.stream(subCommands).map(this::convertSubCommandDef).toList();
return org.javacord.api.interaction.SlashCommandOption.createWithOptions(
org.javacord.api.interaction.SlashCommandOptionType.SUB_COMMAND_GROUP,
subGroup.name(),
subGroup.description(),
convertedSubCommands);
}
private org.javacord.api.interaction.SlashCommandOption convertSubCommandDef(SlashCommandIdentifier sub) {
List<org.javacord.api.interaction.SlashCommandOption> convertedOptions = Arrays.stream(sub.options()).map(this::convertOptionDef).toList();
return org.javacord.api.interaction.SlashCommandOption.createWithOptions(
org.javacord.api.interaction.SlashCommandOptionType.SUB_COMMAND,
sub.name(),
sub.description(),
convertedOptions);
}
private org.javacord.api.interaction.SlashCommandOption convertOptionDef(SlashCommandOption option) {
SlashCommandOptionType type = SlashCommandOptionType.fromValue(option.type().getValue());
SlashCommandOptionBuilder builder = new SlashCommandOptionBuilder();
builder
.setType(type)
.setName(option.name())
.setDescription(option.description())
.setRequired(option.required())
.setAutocompletable(option.autocomplete())
.setChoices(convertChoices(option));
return builder.build();
}
private List<org.javacord.api.interaction.SlashCommandOptionChoice> convertChoices(SlashCommandOption option) {
List<org.javacord.api.interaction.SlashCommandOptionChoice> convertedChoices = new ArrayList<>();
for (SlashCommandOptionChoice choice : SlashCommandDefinition.getActualChoices(option)) {
SlashCommandOptionChoiceBuilder builder = new SlashCommandOptionChoiceBuilder();
builder.setName(choice.name());
if (choice.longValue() != Long.MAX_VALUE)
builder.setValue(choice.longValue());
/*
not yet available
if (choice.doubleValue() != Double.MAX_VALUE)
builder.setValue(choice.doubleValue());
*/
if (!choice.stringValue().isEmpty())
builder.setValue(choice.stringValue());
convertedChoices.add(builder.build());
}
return convertedChoices;
public IdentifierProvider createIdentifierProvider() {
return IdentifierProvider.of(
new SlashCommandIdentifierConverter(),
new AutocompleteIdentifierConverter(),
new ButtonIdentifierConverter()
);
}
@Override

View File

@@ -0,0 +1,37 @@
package net.tomatentum.marinara.wrapper.javacord.identifierconverter;
import java.util.List;
import org.javacord.api.interaction.AutocompleteInteraction;
import org.javacord.api.interaction.SlashCommandInteractionOption;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.wrapper.IdentifierProvider;
public class AutocompleteIdentifierConverter implements IdentifierProvider.Converter<AutocompleteInteraction> {
@Override
public InteractionIdentifier convert(AutocompleteInteraction context) {
List<SlashCommandInteractionOption> options = context.getOptions();
String commandName = context.getCommandName();
if (!options.isEmpty()) {
List<SlashCommandInteractionOption> sub_options = context.getOptions().getFirst().getOptions();
if (!sub_options.isEmpty())
return InteractionIdentifier.createHierarchy(
InteractionType.AUTOCOMPLETE,
commandName,
options.getFirst().getName(),
sub_options.getFirst().getName());
else
return InteractionIdentifier.createHierarchy(
InteractionType.AUTOCOMPLETE,
commandName,
options.getFirst().getName());
}else
return InteractionIdentifier.createHierarchy(
InteractionType.AUTOCOMPLETE,
commandName);
}
}

View File

@@ -0,0 +1,16 @@
package net.tomatentum.marinara.wrapper.javacord.identifierconverter;
import org.javacord.api.interaction.ButtonInteraction;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.wrapper.IdentifierProvider;
public class ButtonIdentifierConverter implements IdentifierProvider.Converter<ButtonInteraction> {
@Override
public InteractionIdentifier convert(ButtonInteraction context) {
return InteractionIdentifier.builder().name(context.getCustomId()).type(InteractionType.BUTTON).build();
}
}

View File

@@ -0,0 +1,38 @@
package net.tomatentum.marinara.wrapper.javacord.identifierconverter;
import java.util.List;
import org.javacord.api.interaction.SlashCommandInteraction;
import org.javacord.api.interaction.SlashCommandInteractionOption;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.wrapper.IdentifierProvider;
public class SlashCommandIdentifierConverter implements IdentifierProvider.Converter<SlashCommandInteraction> {
@Override
public InteractionIdentifier convert(SlashCommandInteraction context) {
List<SlashCommandInteractionOption> options = context.getOptions();
String commandName = context.getCommandName();
if (!options.isEmpty()) {
List<SlashCommandInteractionOption> sub_options = context.getOptions().getFirst().getOptions();
if (!sub_options.isEmpty())
return InteractionIdentifier.createHierarchy(
InteractionType.COMMAND,
commandName,
options.getFirst().getName(),
sub_options.getFirst().getName());
else
return InteractionIdentifier.createHierarchy(
InteractionType.COMMAND,
commandName,
options.getFirst().getName());
}else
return InteractionIdentifier.createHierarchy(
InteractionType.COMMAND,
commandName);
}
}

View File

@@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import org.javacord.api.interaction.SlashCommandInteraction;
import net.tomatentum.marinara.interaction.InteractionHandler;
import net.tomatentum.marinara.interaction.commands.annotation.CommandChoices;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommand;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption;
import net.tomatentum.marinara.interaction.commands.option.SlashCommandOptionType;
@@ -21,7 +22,7 @@ public class TestCommand implements InteractionHandler {
name = "foo",
description = "foo bar is very fooby",
type = SlashCommandOptionType.STRING,
choiceEnum = TestChoiceEnum.class
choices = @CommandChoices(cenum = TestChoiceEnum.class)
)
}
)