Skip to content

Instantly share code, notes, and snippets.

@NotArchon
Created April 14, 2023 22:55
Show Gist options
  • Select an option

  • Save NotArchon/534369ba0822fd06c0cc270b10037df3 to your computer and use it in GitHub Desktop.

Select an option

Save NotArchon/534369ba0822fd06c0cc270b10037df3 to your computer and use it in GitHub Desktop.
package io.archon.discord;
import io.archon.discord.api.Interaction;
import io.archon.discord.api.interactions.*;
import io.archon.web.other.GsonInstance;
public class DiscordInteraction {
private static <T> T dataToType(Object dataObj, Class<T> type) {
String json = dataObj == null ? "" : GsonInstance.normal().toJson(dataObj);
return GsonInstance.normal().fromJson(json, type);
}
public static void handle(String json, Handler handler) {
Interaction interaction = GsonInstance.normal().fromJson(json, Interaction.class);
Object data = interaction.getData(); // this will end up being parsed as a map by default
switch(interaction.getType()) {
case 1 -> handler.handle(interaction, dataToType(data, Ping.class));
case 2 -> handler.handle(interaction, dataToType(data, ApplicationCommand.class));
case 3 -> handler.handle(interaction, dataToType(data, MessageComponent.class));
case 4 -> handler.handle(interaction, dataToType(data, ApplicationCommandAutoComplete.class));
case 5 -> handler.handle(interaction, dataToType(data, ModalSubmit.class));
default -> handler.unknown(interaction);
}
}
public interface Handler {
default void handle(Interaction interaction, Ping ping) {}
default void handle(Interaction interaction, ApplicationCommand command) {}
default void handle(Interaction interaction, MessageComponent message) {}
default void handle(Interaction interaction, ApplicationCommandAutoComplete autoComplete) {}
default void handle(Interaction interaction, ModalSubmit modalSubmit) {}
default void unknown(Interaction interaction) {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment