diff --git a/build.gradle b/build.gradle index 660b482..c71e7b9 100644 --- a/build.gradle +++ b/build.gradle @@ -2,6 +2,8 @@ plugins { id'java' id'application' id'com.github.johnrengelman.shadow' version '5.2.0' + id 'org.springframework.boot' version '2.5.4' + id 'io.spring.dependency-management' version '1.0.11.RELEASE' } group 'de.foursoft' @@ -20,6 +22,7 @@ repositories { } dependencies { + implementation 'org.springframework.boot:spring-boot-starter' implementation ('net.dv8tion:JDA:4.3.0_310') { exclude module: 'opus-java' } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 44e7c4d..3ab0b72 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/src/main/java/de/foursoft/discordbot/BotConfiguration.java b/src/main/java/de/foursoft/discordbot/BotConfiguration.java new file mode 100644 index 0000000..dc52682 --- /dev/null +++ b/src/main/java/de/foursoft/discordbot/BotConfiguration.java @@ -0,0 +1,29 @@ +package de.foursoft.discordbot; + +import com.jagrosh.jdautilities.commons.waiter.EventWaiter; +import net.dv8tion.jda.api.hooks.EventListener; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.lang.reflect.Proxy; + +@Configuration +public class BotConfiguration { + + @Autowired + ListenerAdapterDispatcher dispatcher; + + @Bean + public EventWaiter eventWaiter(){ + return new EventWaiter(); + } + + @Bean + public EventListener eventListener(){ + return (EventListener) Proxy.newProxyInstance( + BotConfiguration.class.getClassLoader(), + new Class[] { EventListener.class }, + dispatcher); + } +} diff --git a/src/main/java/de/foursoft/discordbot/BotInitializer.java b/src/main/java/de/foursoft/discordbot/BotInitializer.java new file mode 100644 index 0000000..2e59c44 --- /dev/null +++ b/src/main/java/de/foursoft/discordbot/BotInitializer.java @@ -0,0 +1,49 @@ +package de.foursoft.discordbot; + +import com.jagrosh.jdautilities.commons.waiter.EventWaiter; +import net.dv8tion.jda.api.JDABuilder; +import net.dv8tion.jda.api.hooks.EventListener; +import net.dv8tion.jda.api.requests.GatewayIntent; +import net.dv8tion.jda.api.utils.ChunkingFilter; +import net.dv8tion.jda.api.utils.MemberCachePolicy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.security.auth.login.LoginException; + +@Component +public class BotInitializer { + private static final Logger LOGGER = LoggerFactory.getLogger(FourSoftDiscordBot.class); + + @Autowired + private EventWaiter eventWaiter; + @Autowired + private EventListener eventListener; + + @PostConstruct + private void init(){ + Configuration config = new Configuration("config.properties"); + + try { + JDABuilder.createDefault(config.getToken()) // init default settings + .setChunkingFilter(ChunkingFilter.ALL) // load all members + .enableIntents( + GatewayIntent.GUILD_MEMBERS, // allow access to guild members + GatewayIntent.GUILD_PRESENCES // access to online status and activities + ) + .setMemberCachePolicy(MemberCachePolicy.ALL) // always cache members + .addEventListeners(eventListener) + .addEventListeners(eventWaiter) // waits for events + .build().awaitReady(); // wait until the API is ready + } catch (LoginException e) { + LOGGER.error("Could not start the Bot, invalid Token!"); + System.exit(-1); + } catch (InterruptedException e) { + LOGGER.error("Could not start the Bot, interrupted while waiting!"); + System.exit(-1); + } + } +} diff --git a/src/main/java/de/foursoft/discordbot/BotListener.java b/src/main/java/de/foursoft/discordbot/BotListener.java deleted file mode 100644 index a248738..0000000 --- a/src/main/java/de/foursoft/discordbot/BotListener.java +++ /dev/null @@ -1,113 +0,0 @@ -package de.foursoft.discordbot; - -import de.foursoft.discordbot.commands.Command; -import de.foursoft.discordbot.listener.DadListener; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote; -import net.dv8tion.jda.api.events.message.guild.GuildMessageDeleteEvent; -import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; -import net.dv8tion.jda.api.events.message.guild.GuildMessageUpdateEvent; -import net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent; -import net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionRemoveEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.regex.Pattern; - -public class BotListener extends ListenerAdapter { - - private static final Pattern WHITESPACES_PATTERN = Pattern.compile("\\s+"); - private static final Logger LOGGER = LoggerFactory.getLogger(BotListener.class); - - private static final String PREFIX = "!"; - -// private static final Map -// -// static { -// MAP.put(ListenerAdapter::onStageInstanceDelete, DadListener.class); -// } - - private final CommandRegistry commandRegistry; - - public BotListener(CommandRegistry commandRegistry) { - this.commandRegistry = commandRegistry; - } - - @Override - public void onGuildMessageReceived(GuildMessageReceivedEvent event) { - User user = event.getAuthor(); - Message message = event.getMessage(); - - - // Mentions will converted to ids, Markdown characters are included - String contentRaw = message.getContentRaw(); - - LOGGER.info("{}: {}", user.getAsTag(), contentRaw); - - //TODO insert into generic event dispatcher - new DadListener().accept(event); - - if (!contentRaw.startsWith(PREFIX)) { - return; - } - - // split at whitespaces - final String contentWithoutPrefix = contentRaw.substring(PREFIX.length()).trim(); - String[] args = WHITESPACES_PATTERN.split(contentWithoutPrefix); - - String userCommand = args[0].toLowerCase(); // args will never be empty due to the impl of split - if (userCommand.isEmpty()) { - return; - } - - final Command cmd = commandRegistry.getCommand(userCommand); - if (cmd == null) { - return; - } - - cmd.execute(event); - - } - - - @Override - public void onGuildMessageUpdate(GuildMessageUpdateEvent event) { - // means a message was edited or (un)pinned - // NOTE: Previous Content / State is not provided by the API - - Message message = event.getMessage(); - - LOGGER.info("[MESSAGE EDIT] {}", message.getContentRaw()); - } - - @Override - public void onGuildMessageDelete(GuildMessageDeleteEvent event) { - // NOTE: Message Content / State is not provided by the API - - TextChannel channel = event.getChannel(); - long msgId = event.getMessageIdLong(); - LOGGER.info("Message with Id {} was deleted from {}", msgId, channel.getName()); - } - - @Override - public void onGuildMessageReactionAdd(GuildMessageReactionAddEvent event) { - Member member = event.getMember(); - long msgId = event.getMessageIdLong(); - ReactionEmote reaction = event.getReactionEmote(); // can be emoji or emote - - boolean isEmoji = reaction.isEmoji(); // default emojis like :D - boolean isEmote = reaction.isEmote(); // emote = custom emoji, is bound to a server - - LOGGER.info("{} reacted to Message with Id {}", member.getUser().getAsTag(), msgId); - } - - - @Override - public void onGuildMessageReactionRemove(GuildMessageReactionRemoveEvent event) { - // Same as above - - LOGGER.info("{} removed reaction from Message with Id {}", event.getUser().getAsTag(), event.getMessageIdLong()); - } - -} diff --git a/src/main/java/de/foursoft/discordbot/CommandRegistry.java b/src/main/java/de/foursoft/discordbot/CommandRegistry.java deleted file mode 100644 index 5662461..0000000 --- a/src/main/java/de/foursoft/discordbot/CommandRegistry.java +++ /dev/null @@ -1,21 +0,0 @@ -package de.foursoft.discordbot; - -import de.foursoft.discordbot.commands.Command; -import net.dv8tion.jda.api.events.Event; - -import java.util.HashMap; -import java.util.Map; - -public class CommandRegistry { - - private final Map> commands = new HashMap<>(); - - public CommandRegistry addCommand(String name, Command command) { - commands.put(name, command); - return this; - } - - public Command getCommand(String name) { - return (Command)commands.get(name); - } -} diff --git a/src/main/java/de/foursoft/discordbot/FourSoftDiscordBot.java b/src/main/java/de/foursoft/discordbot/FourSoftDiscordBot.java index 6b619e8..867e56b 100644 --- a/src/main/java/de/foursoft/discordbot/FourSoftDiscordBot.java +++ b/src/main/java/de/foursoft/discordbot/FourSoftDiscordBot.java @@ -1,68 +1,15 @@ package de.foursoft.discordbot; -import com.jagrosh.jdautilities.commons.waiter.EventWaiter; -import de.foursoft.discordbot.commands.PingCommand; -import de.foursoft.discordbot.commands.ReactCommand; -import de.foursoft.discordbot.commands.ResetCommand; -import de.foursoft.discordbot.commands.SecretCommand; -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.JDABuilder; -import net.dv8tion.jda.api.requests.GatewayIntent; -import net.dv8tion.jda.api.utils.ChunkingFilter; -import net.dv8tion.jda.api.utils.MemberCachePolicy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.security.auth.login.LoginException; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +@SpringBootApplication +@ComponentScan("de.foursoft") public class FourSoftDiscordBot { - private static final Logger LOGGER = LoggerFactory.getLogger(FourSoftDiscordBot.class); - - private final JDA discordApi; - - private final EventWaiter eventWaiter = new EventWaiter(); - - private final CommandRegistry commandRegistry = new CommandRegistry(); - - public FourSoftDiscordBot() { - Configuration config = new Configuration("config.properties"); - - // init commands - commandRegistry.addCommand("ping", new PingCommand()) - .addCommand("react", new ReactCommand()) - .addCommand("secret", new SecretCommand(eventWaiter)) - .addCommand("reset", new ResetCommand()); - - JDA tmpJda = null; - try { - tmpJda = JDABuilder.createDefault(config.getToken()) // init default settings - .setChunkingFilter(ChunkingFilter.ALL) // load all members - .enableIntents( - GatewayIntent.GUILD_MEMBERS, // allow access to guild members - GatewayIntent.GUILD_PRESENCES // access to online status and activities - ) - .setMemberCachePolicy(MemberCachePolicy.ALL) // always cache members - .addEventListeners(new BotListener(commandRegistry)) // enable the class to receive events - .addEventListeners(eventWaiter) // waits for events - .build().awaitReady(); // wait until the API is ready - } catch (LoginException e) { - LOGGER.error("Could not start the Bot, invalid Token!"); - System.exit(-1); - } catch (InterruptedException e) { - LOGGER.error("Could not start the Bot, interrupted while waiting!"); - System.exit(-1); - } - - discordApi = tmpJda; - } - - public JDA getDiscordApi() { - return discordApi; - } - public static void main(String[] args) { - new FourSoftDiscordBot(); + SpringApplication.run(FourSoftDiscordBot.class, args); } } diff --git a/src/main/java/de/foursoft/discordbot/ListenerAdapterDispatcher.java b/src/main/java/de/foursoft/discordbot/ListenerAdapterDispatcher.java new file mode 100644 index 0000000..42af7fc --- /dev/null +++ b/src/main/java/de/foursoft/discordbot/ListenerAdapterDispatcher.java @@ -0,0 +1,45 @@ +package de.foursoft.discordbot; + +import de.foursoft.discordbot.eventconsumer.EventConsumer; +import net.dv8tion.jda.api.events.Event; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Component +public class ListenerAdapterDispatcher implements InvocationHandler { + + @Autowired + private List allEventConsumers; + + private Map> consumerByEvent; + + @PostConstruct + private void init(){ + consumerByEvent = allEventConsumers.stream().collect(Collectors.groupingBy(EventConsumer::getClassOfT)); + } + + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + + if(args.length != 1){ + return null; + } + + Object event = args[0]; + + consumerByEvent.getOrDefault(event.getClass(), Collections.emptyList()) + .forEach(c -> c.execute((Event) event)); + + return null; + } +} diff --git a/src/main/java/de/foursoft/discordbot/commands/Command.java b/src/main/java/de/foursoft/discordbot/commands/Command.java deleted file mode 100644 index 8cea2e2..0000000 --- a/src/main/java/de/foursoft/discordbot/commands/Command.java +++ /dev/null @@ -1,10 +0,0 @@ -package de.foursoft.discordbot.commands; - -import net.dv8tion.jda.api.events.Event; - -public abstract class Command { - - public abstract String getName(); - - public abstract void execute(T event); -} diff --git a/src/main/java/de/foursoft/discordbot/commands/GuildMessageReceivedCommand.java b/src/main/java/de/foursoft/discordbot/commands/GuildMessageReceivedCommand.java deleted file mode 100644 index 1b75b55..0000000 --- a/src/main/java/de/foursoft/discordbot/commands/GuildMessageReceivedCommand.java +++ /dev/null @@ -1,6 +0,0 @@ -package de.foursoft.discordbot.commands; - -import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; - -public abstract class GuildMessageReceivedCommand extends Command { -} diff --git a/src/main/java/de/foursoft/discordbot/listener/DadListener.java b/src/main/java/de/foursoft/discordbot/eventconsumer/DadEventConsumer.java similarity index 77% rename from src/main/java/de/foursoft/discordbot/listener/DadListener.java rename to src/main/java/de/foursoft/discordbot/eventconsumer/DadEventConsumer.java index 06e931e..38890f8 100644 --- a/src/main/java/de/foursoft/discordbot/listener/DadListener.java +++ b/src/main/java/de/foursoft/discordbot/eventconsumer/DadEventConsumer.java @@ -1,13 +1,14 @@ -package de.foursoft.discordbot.listener; +package de.foursoft.discordbot.eventconsumer; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; +import org.springframework.stereotype.Component; import java.util.*; -import java.util.function.Consumer; -public class DadListener implements Consumer { +@Component +public class DadEventConsumer extends EventConsumer { private static final Set VALID_KEY_PHRASES; @@ -20,7 +21,12 @@ public class DadListener implements Consumer { } @Override - public void accept(GuildMessageReceivedEvent event) { + public Class getClassOfT() { + return GuildMessageReceivedEvent.class; + } + + @Override + public void execute(GuildMessageReceivedEvent event) { Message message = event.getMessage(); String contentRaw = message.getContentRaw(); diff --git a/src/main/java/de/foursoft/discordbot/eventconsumer/EventConsumer.java b/src/main/java/de/foursoft/discordbot/eventconsumer/EventConsumer.java new file mode 100644 index 0000000..78c4f49 --- /dev/null +++ b/src/main/java/de/foursoft/discordbot/eventconsumer/EventConsumer.java @@ -0,0 +1,10 @@ +package de.foursoft.discordbot.eventconsumer; + +import net.dv8tion.jda.api.events.Event; + +public abstract class EventConsumer { + + public abstract Class getClassOfT(); + + public abstract void execute(T event); +} diff --git a/src/main/java/de/foursoft/discordbot/eventconsumer/GuildMessageReceivedEventConsumer.java b/src/main/java/de/foursoft/discordbot/eventconsumer/GuildMessageReceivedEventConsumer.java new file mode 100644 index 0000000..aa34d47 --- /dev/null +++ b/src/main/java/de/foursoft/discordbot/eventconsumer/GuildMessageReceivedEventConsumer.java @@ -0,0 +1,56 @@ +package de.foursoft.discordbot.eventconsumer; + +import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.regex.Pattern; + +public abstract class GuildMessageReceivedEventConsumer extends EventConsumer { + + private static final Logger LOGGER = LoggerFactory.getLogger(GuildMessageReceivedEventConsumer.class); + + private static final Pattern WHITESPACES_PATTERN = Pattern.compile("\\s+"); + private static final String PREFIX = "!"; + + @Override + public void execute(GuildMessageReceivedEvent event) { + User user = event.getAuthor(); + Message message = event.getMessage(); + + + // Mentions will converted to ids, Markdown characters are included + String contentRaw = message.getContentRaw(); + + LOGGER.info("{}: {}", user.getAsTag(), contentRaw); + + if (!contentRaw.startsWith(PREFIX)) { + return; + } + + // split at whitespaces + final String contentWithoutPrefix = contentRaw.substring(PREFIX.length()).trim(); + String[] args = WHITESPACES_PATTERN.split(contentWithoutPrefix); + + String userCommand = args[0].toLowerCase(); // args will never be empty due to the impl of split + if (userCommand.isEmpty()) { + return; + } + + if (getName().equals(userCommand)){ + doExecute(event); + } + + } + + protected abstract String getName(); + + protected abstract void doExecute(GuildMessageReceivedEvent event); + + @Override + public Class getClassOfT() { + return GuildMessageReceivedEvent.class; + } +} diff --git a/src/main/java/de/foursoft/discordbot/commands/PingCommand.java b/src/main/java/de/foursoft/discordbot/eventconsumer/PingEventConsumer.java similarity index 54% rename from src/main/java/de/foursoft/discordbot/commands/PingCommand.java rename to src/main/java/de/foursoft/discordbot/eventconsumer/PingEventConsumer.java index cc8b662..3812f48 100644 --- a/src/main/java/de/foursoft/discordbot/commands/PingCommand.java +++ b/src/main/java/de/foursoft/discordbot/eventconsumer/PingEventConsumer.java @@ -1,15 +1,17 @@ -package de.foursoft.discordbot.commands; +package de.foursoft.discordbot.eventconsumer; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; +import org.springframework.stereotype.Component; + +@Component +public class PingEventConsumer extends GuildMessageReceivedEventConsumer { -public class PingCommand extends GuildMessageReceivedCommand { - @Override public String getName() { return "ping"; } @Override - public void execute(GuildMessageReceivedEvent event) { + public void doExecute(GuildMessageReceivedEvent event) { event.getChannel().sendMessage("Pong!") .queue(); // IMPORTANT - .queue is needed when request is made } diff --git a/src/main/java/de/foursoft/discordbot/commands/ReactCommand.java b/src/main/java/de/foursoft/discordbot/eventconsumer/ReactEventConsumer.java similarity index 70% rename from src/main/java/de/foursoft/discordbot/commands/ReactCommand.java rename to src/main/java/de/foursoft/discordbot/eventconsumer/ReactEventConsumer.java index 98d2b75..d0ebd6f 100644 --- a/src/main/java/de/foursoft/discordbot/commands/ReactCommand.java +++ b/src/main/java/de/foursoft/discordbot/eventconsumer/ReactEventConsumer.java @@ -1,22 +1,23 @@ -package de.foursoft.discordbot.commands; +package de.foursoft.discordbot.eventconsumer; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; -public class ReactCommand extends GuildMessageReceivedCommand { - private static final Logger LOGGER = LoggerFactory.getLogger(ReactCommand.class); +@Component +public class ReactEventConsumer extends GuildMessageReceivedEventConsumer { + private static final Logger LOGGER = LoggerFactory.getLogger(ReactEventConsumer.class); private static final String THUMBS_UP_UNICODE = "\uD83D\uDC4D"; - @Override public String getName() { return "react"; } @Override - public void execute(GuildMessageReceivedEvent event) { + public void doExecute(GuildMessageReceivedEvent event) { Message message = event.getMessage(); message.addReaction(THUMBS_UP_UNICODE).queue(success -> { LOGGER.debug("Reaction worked!"); diff --git a/src/main/java/de/foursoft/discordbot/eventconsumer/ReactionAddEventConsumer.java b/src/main/java/de/foursoft/discordbot/eventconsumer/ReactionAddEventConsumer.java new file mode 100644 index 0000000..07afeb1 --- /dev/null +++ b/src/main/java/de/foursoft/discordbot/eventconsumer/ReactionAddEventConsumer.java @@ -0,0 +1,31 @@ +package de.foursoft.discordbot.eventconsumer; + +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.MessageReaction; +import net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class ReactionAddEventConsumer extends EventConsumer { + + private static final Logger LOGGER = LoggerFactory.getLogger(ReactionAddEventConsumer.class); + + @Override + public Class getClassOfT() { + return GuildMessageReactionAddEvent.class; + } + + @Override + public void execute(GuildMessageReactionAddEvent event) { + Member member = event.getMember(); + long msgId = event.getMessageIdLong(); + MessageReaction.ReactionEmote reaction = event.getReactionEmote(); // can be emoji or emote + + boolean isEmoji = reaction.isEmoji(); // default emojis like :D + boolean isEmote = reaction.isEmote(); // emote = custom emoji, is bound to a server + + LOGGER.info("{} reacted to Message with Id {}", member.getUser().getAsTag(), msgId); + } +} diff --git a/src/main/java/de/foursoft/discordbot/commands/ResetCommand.java b/src/main/java/de/foursoft/discordbot/eventconsumer/ResetEventConsumer.java similarity index 77% rename from src/main/java/de/foursoft/discordbot/commands/ResetCommand.java rename to src/main/java/de/foursoft/discordbot/eventconsumer/ResetEventConsumer.java index 25f79f7..f61d990 100644 --- a/src/main/java/de/foursoft/discordbot/commands/ResetCommand.java +++ b/src/main/java/de/foursoft/discordbot/eventconsumer/ResetEventConsumer.java @@ -1,4 +1,4 @@ -package de.foursoft.discordbot.commands; +package de.foursoft.discordbot.eventconsumer; import static de.foursoft.discordbot.GuildUtilsAndConstantsAndOtherUsefulStuffAndShit.PASSWORD_CATEGORY_ID; import static de.foursoft.discordbot.GuildUtilsAndConstantsAndOtherUsefulStuffAndShit.deleteChannel; @@ -7,16 +7,17 @@ import net.dv8tion.jda.api.entities.Category; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; +import org.springframework.stereotype.Component; -public class ResetCommand extends GuildMessageReceivedCommand { +@Component +public class ResetEventConsumer extends GuildMessageReceivedEventConsumer { - @Override public String getName() { return "reset"; } @Override - public void execute(GuildMessageReceivedEvent event) { + public void doExecute(GuildMessageReceivedEvent event) { Guild guild = event.getGuild(); Category category = guild.getCategoryById(PASSWORD_CATEGORY_ID); diff --git a/src/main/java/de/foursoft/discordbot/commands/SecretCommand.java b/src/main/java/de/foursoft/discordbot/eventconsumer/SecretEventConsumer.java similarity index 92% rename from src/main/java/de/foursoft/discordbot/commands/SecretCommand.java rename to src/main/java/de/foursoft/discordbot/eventconsumer/SecretEventConsumer.java index 18c870d..e9d9d54 100644 --- a/src/main/java/de/foursoft/discordbot/commands/SecretCommand.java +++ b/src/main/java/de/foursoft/discordbot/eventconsumer/SecretEventConsumer.java @@ -1,92 +1,95 @@ -package de.foursoft.discordbot.commands; - -import static de.foursoft.discordbot.GuildUtilsAndConstantsAndOtherUsefulStuffAndShit.PASSWORD_CATEGORY_ID; -import static de.foursoft.discordbot.GuildUtilsAndConstantsAndOtherUsefulStuffAndShit.deleteChannel; - -import com.jagrosh.jdautilities.commons.waiter.EventWaiter; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -public class SecretCommand extends GuildMessageReceivedCommand { - private static final Map PASSWORD_TO_CHANNELS = new HashMap<>(); - private static final long FAIL_CHANNEL = 852912833024491520L; - private final EventWaiter eventWaiter; - - { - PASSWORD_TO_CHANNELS.put("1234", 852912770969370624L); - PASSWORD_TO_CHANNELS.put("1337", 852912856814845962L); - } - - public SecretCommand(EventWaiter eventWaiter) { - this.eventWaiter = eventWaiter; - } - - @Override - public String getName() { - return "secret"; - } - - @Override - public void execute(GuildMessageReceivedEvent event) { - Guild guild = event.getGuild(); - User user = event.getAuthor(); - SelfUser selfUser = event.getJDA().getSelfUser(); - final Category pwCategory = guild.getCategoryById(PASSWORD_CATEGORY_ID); - guild.createTextChannel("enter-the-password-" + user.getName(), pwCategory) - .addRolePermissionOverride(guild.getPublicRole().getIdLong(), null, Collections.singletonList(Permission.VIEW_CHANNEL)) - .addMemberPermissionOverride(user.getIdLong(), Collections.singletonList(Permission.VIEW_CHANNEL), null) - .addMemberPermissionOverride(selfUser.getIdLong(), Collections.singletonList(Permission.VIEW_CHANNEL), null) - .queue(pwChannel -> { - eventWaiter.waitForEvent(GuildMessageReceivedEvent.class, - userResponse -> userResponse.getAuthor().equals(user) && - userResponse.getChannel().equals(pwChannel), - userResponse -> { - - handlePasswordResponse(userResponse); - deleteChannel(pwChannel, 1, TimeUnit.MINUTES); - }, - 1, TimeUnit.MINUTES, () -> { - deleteChannel(pwChannel); - }); - }); - } - - private void handlePasswordResponse(GuildMessageReceivedEvent userResponse) { - final TextChannel channel = userResponse.getChannel(); - - Long targetChannelId = PASSWORD_TO_CHANNELS.get(userResponse.getMessage() - .getContentRaw()); - - long channelId; - String responseMessage; - if (targetChannelId == null) { - channelId = FAIL_CHANNEL; - responseMessage = "password incorrect!"; - } else { - channelId = targetChannelId; - responseMessage = "password correct, you have permission to enter the <#" + targetChannelId + ">"; - } - TextChannel targetChannel = userResponse.getGuild().getTextChannelById(channelId); - - if (targetChannel == null) { - userResponse.getGuild().getOwner().getUser().openPrivateChannel().queue(privateChannel -> { - privateChannel.sendMessage("Channel with id " + channelId + " does not exist anymore!").queue(); - }); - - channel.sendMessage("Internal Server Error, please try again later.").queue(); - return; - } - - targetChannel - .upsertPermissionOverride(userResponse.getMember()) - .setAllow(Permission.VIEW_CHANNEL) - .queue(); - channel.sendMessage(responseMessage).queue(); - } -} +package de.foursoft.discordbot.eventconsumer; + +import static de.foursoft.discordbot.GuildUtilsAndConstantsAndOtherUsefulStuffAndShit.PASSWORD_CATEGORY_ID; +import static de.foursoft.discordbot.GuildUtilsAndConstantsAndOtherUsefulStuffAndShit.deleteChannel; + +import com.jagrosh.jdautilities.commons.waiter.EventWaiter; +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +@Component +public class SecretEventConsumer extends GuildMessageReceivedEventConsumer { + private static final Map PASSWORD_TO_CHANNELS = new HashMap<>(); + + private static final long FAIL_CHANNEL = 852912833024491520L; + + private final EventWaiter eventWaiter; + + { + PASSWORD_TO_CHANNELS.put("1234", 852912770969370624L); + PASSWORD_TO_CHANNELS.put("1337", 852912856814845962L); + } + + public SecretEventConsumer(EventWaiter eventWaiter) { + this.eventWaiter = eventWaiter; + } + + public String getName() { + return "secret"; + } + + @Override + public void doExecute(GuildMessageReceivedEvent event) { + Guild guild = event.getGuild(); + User user = event.getAuthor(); + SelfUser selfUser = event.getJDA().getSelfUser(); + final Category pwCategory = guild.getCategoryById(PASSWORD_CATEGORY_ID); + guild.createTextChannel("enter-the-password-" + user.getName(), pwCategory) + .addRolePermissionOverride(guild.getPublicRole().getIdLong(), null, Collections.singletonList(Permission.VIEW_CHANNEL)) + .addMemberPermissionOverride(user.getIdLong(), Collections.singletonList(Permission.VIEW_CHANNEL), null) + .addMemberPermissionOverride(selfUser.getIdLong(), Collections.singletonList(Permission.VIEW_CHANNEL), null) + .queue(pwChannel -> { + eventWaiter.waitForEvent(GuildMessageReceivedEvent.class, + userResponse -> userResponse.getAuthor().equals(user) && + userResponse.getChannel().equals(pwChannel), + userResponse -> { + + handlePasswordResponse(userResponse); + deleteChannel(pwChannel, 1, TimeUnit.MINUTES); + }, + 1, TimeUnit.MINUTES, () -> { + deleteChannel(pwChannel); + }); + }); + } + + private void handlePasswordResponse(GuildMessageReceivedEvent userResponse) { + final TextChannel channel = userResponse.getChannel(); + + Long targetChannelId = PASSWORD_TO_CHANNELS.get(userResponse.getMessage() + .getContentRaw()); + + long channelId; + String responseMessage; + if (targetChannelId == null) { + channelId = FAIL_CHANNEL; + responseMessage = "password incorrect!"; + } else { + channelId = targetChannelId; + responseMessage = "password correct, you have permission to enter the <#" + targetChannelId + ">"; + } + TextChannel targetChannel = userResponse.getGuild().getTextChannelById(channelId); + + if (targetChannel == null) { + userResponse.getGuild().getOwner().getUser().openPrivateChannel().queue(privateChannel -> { + privateChannel.sendMessage("Channel with id " + channelId + " does not exist anymore!").queue(); + }); + + channel.sendMessage("Internal Server Error, please try again later.").queue(); + return; + } + + targetChannel + .upsertPermissionOverride(userResponse.getMember()) + .setAllow(Permission.VIEW_CHANNEL) + .queue(); + channel.sendMessage(responseMessage).queue(); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..12c10a3 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.main.web-application-type=NONE \ No newline at end of file