Skip to content
This repository was archived by the owner on Dec 1, 2021. It is now read-only.

Add Activity Systems #21

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ dependencies {
implementation 'org.yaml:snakeyaml:1.29'
implementation 'com.google.code.gson:gson:2.8.9'

implementation 'org.openpnp:opencv:4.5.1-2'

// Persistence Dependencies
implementation 'org.mongodb:mongodb-driver:3.12.10'
implementation 'com.h2database:h2:1.4.200'
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/net/javadiscord/javabot2/Bot.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public static void main(String[] args) {
SlashCommandListener commandListener = new SlashCommandListener(
api,
args.length > 0 && args[0].equalsIgnoreCase("--register-commands"),
"commands/moderation.yaml"
"commands/moderation.yaml", "commands/activity.yaml"
);
api.addSlashCommandCreateListener(commandListener);
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package net.javadiscord.javabot2.command;

import org.javacord.api.interaction.SlashCommandInteraction;
import org.javacord.api.interaction.callback.InteractionImmediateResponseBuilder;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
* Abstract command handler which is useful for commands which consist of lots
* of subcommands. A child class will supply a map of subcommand handlers, so
* that this parent handler can do the logic of finding the right subcommand to
* invoke depending on the event received.
*/
public class DelegatingCommandHandler implements SlashCommandHandler {
private final Map<String, SlashCommandHandler> subcommandHandlers;
private final Map<String, SlashCommandHandler> subcommandGroupHandlers;

/**
* Constructs the handler with an already-initialized map of subcommands.
* @param subcommandHandlers The map of subcommands to use.
*/
public DelegatingCommandHandler(Map<String, SlashCommandHandler> subcommandHandlers) {
this.subcommandHandlers = subcommandHandlers;
this.subcommandGroupHandlers = new HashMap<>();
}

/**
* Constructs the handler with an empty map, which subcommands can be added
* to via {@link DelegatingCommandHandler#addSubcommand(String, SlashCommandHandler)}.
*/
public DelegatingCommandHandler() {
this.subcommandHandlers = new HashMap<>();
this.subcommandGroupHandlers = new HashMap<>();
}

/**
* Gets an unmodifiable map of the subcommand handlers this delegating
* handler has registered.
* @return An unmodifiable map containing all registered subcommands.
*/
public Map<String, SlashCommandHandler> getSubcommandHandlers() {
return Collections.unmodifiableMap(this.subcommandHandlers);
}

/**
* Gets an unmodifiable map of the subcommand group handlers that this
* handler has registered.
* @return An unmodifiable map containing all registered group handlers.
*/
public Map<String, SlashCommandHandler> getSubcommandGroupHandlers() {
return Collections.unmodifiableMap(this.subcommandGroupHandlers);
}

/**
* Adds a subcommand to this handler.
* @param name The name of the subcommand. <em>This is case-sensitive.</em>
* @param handler The handler that will be called to handle subcommands with
* the given name.
* @throws UnsupportedOperationException If this handler was initialized
* with an unmodifiable map of subcommand handlers.
*/
protected void addSubcommand(String name, SlashCommandHandler handler) {
this.subcommandHandlers.put(name, handler);
}

/**
* Adds a subcommand group handler to this handler.
* @param name The name of the subcommand group. <em>This is case-sensitive.</em>
* @param handler The handler that will be called to handle commands within
* the given subcommand's name.
* @throws UnsupportedOperationException If this handler was initialized
* with an unmodifiable map of subcommand group handlers.
*/
protected void addSubcommandGroup(String name, SlashCommandHandler handler) {
this.subcommandGroupHandlers.put(name, handler);
}

/**
* Handles the case where the main command is called without any subcommand.
* @param interaction The event.
* @return The reply action that is sent to the user.
*/
protected InteractionImmediateResponseBuilder handleNonSubcommand(SlashCommandInteraction interaction) {
return Responses.warning(interaction, "Missing Subcommand", "Please specify a subcommand.");
}

/**
* Handles a slash command interaction.
*
* @param interaction The interaction.
* @return An immediate response to the interaction.
* @throws ResponseException If an error occurs while handling the event.
*/
@Override
public InteractionImmediateResponseBuilder handle(SlashCommandInteraction interaction) throws ResponseException {
var subCommandOption = interaction.getOptionByIndex(0);
if (subCommandOption.isPresent() && subCommandOption.get().isSubcommandOrGroup()) {
var firstOption = subCommandOption.get();
// TODO: Implement some way of handling subcommand groups! For now javacord is quite scuffed in that regard.
// SlashCommandHandler groupHandler = this.getSubcommandGroupHandlers().get(firstOption.getName());
// if (groupHandler != null) return groupHandler.handle(interaction);
SlashCommandHandler subcommandHandler = this.getSubcommandHandlers().get(firstOption.getName());
if (subcommandHandler != null) return subcommandHandler.handle(interaction);
}
return handleNonSubcommand(interaction);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public SlashCommandListener(DiscordApi api, boolean sendUpdate, String... resour
this.commandHandlers = new HashMap<>();
registerSlashCommands(api, resources)
.thenAcceptAsync(commandHandlers::putAll)
.thenRun(() -> log.info("Registered all slash commands."));
.thenRun(() -> log.info("Registered and updated all slash commands."));
} else {
this.commandHandlers = initializeHandlers(CommandDataLoader.load(resources));
log.info("Registered all slash commands.");
Expand Down Expand Up @@ -74,6 +74,7 @@ private CompletableFuture<Map<String, SlashCommandHandler>> registerSlashCommand
Map<String, Long> nameToId = new HashMap<>();
for (var slashCommand : slashCommands) {
nameToId.put(slashCommand.getName(), slashCommand.getId());
log.info("Updated slash command {}.", slashCommand.getName());
}
return updatePermissions(api, commandConfigs, nameToId)
.thenRun(() -> log.info("Updated permissions for all slash commands."))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static CommandConfig[] load(String... resources) {
continue;
}
CommandConfig[] cs = yaml.loadAs(is, CommandConfig[].class);
commands.addAll(Arrays.stream(cs).toList());
if (cs != null) commands.addAll(Arrays.stream(cs).toList());
}
return commands.toArray(new CommandConfig[0]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class OptionConfig {
*/
public SlashCommandOptionBuilder toData() {
var builder = new SlashCommandOptionBuilder()
.setType(SlashCommandOptionType.valueOf(this.type.toUpperCase()))
.setType(SlashCommandOptionType.valueOf(this.type.trim().toUpperCase()))
.setName(this.name)
.setDescription(this.description)
.setRequired(this.required);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package net.javadiscord.javabot2.db;

import java.sql.Connection;
import java.sql.SQLException;

@FunctionalInterface
public interface ConnectionFunction<T> {
T apply(Connection c) throws SQLException;
}
70 changes: 70 additions & 0 deletions src/main/java/net/javadiscord/javabot2/db/DbActions.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package net.javadiscord.javabot2.db;

import net.javadiscord.javabot2.Bot;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;

/**
* Utility that provides some convenience methods for performing database
* actions.
*/
public class DbActions {
// Hide the constructor.
private DbActions () {}

/**
* Does an asynchronous database action using the bot's async pool.
* @param consumer The consumer that will use a connection.
* @return A future that completes when the action is complete.
*/
public static CompletableFuture<Void> doAction(ConnectionConsumer consumer) {
CompletableFuture<Void> future = new CompletableFuture<>();
Bot.asyncPool.submit(() -> {
try (var c = Bot.hikariDataSource.getConnection()) {
consumer.consume(c);
future.complete(null);
} catch (SQLException e) {
future.completeExceptionally(e);
}
});
return future;
}

/**
* Does an asynchronous database action using the bot's async pool, and
* wraps access to the connection behind a data access object that can be
* built using the provided dao constructor.
* @param daoConstructor A function to build a DAO using a connection.
* @param consumer The consumer that does something with the DAO.
* @param <T> The type of data access object. Usually some kind of repository.
* @return A future that completes when the action is complete.
*/
public static <T> CompletableFuture<Void> doDaoAction(Function<Connection, T> daoConstructor, DaoConsumer<T> consumer) {
CompletableFuture<Void> future = new CompletableFuture<>();
Bot.asyncPool.submit(() -> {
try (var c = Bot.hikariDataSource.getConnection()) {
var dao = daoConstructor.apply(c);
consumer.consume(dao);
future.complete(null);
} catch (SQLException e) {
future.completeExceptionally(e);
}
});
return future;
}

public static <T> CompletableFuture<T> doAction(ConnectionFunction<T> function) {
CompletableFuture<T> future = new CompletableFuture<>();
Bot.asyncPool.submit(() -> {
try (var c = Bot.hikariDataSource.getConnection()) {
future.complete(function.apply(c));
} catch (SQLException e) {
future.completeExceptionally(e);
}
});
return future;
}
}
45 changes: 0 additions & 45 deletions src/main/java/net/javadiscord/javabot2/db/DbHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,15 @@
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import net.javadiscord.javabot2.Bot;
import net.javadiscord.javabot2.config.BotConfig;
import org.h2.tools.Server;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.regex.Pattern;

/**
Expand Down Expand Up @@ -65,47 +61,6 @@ public static HikariDataSource initDataSource(BotConfig config) {
return ds;
}

/**
* Does an asynchronous database action using the bot's async pool.
* @param consumer The consumer that will use a connection.
* @return A future that completes when the action is complete.
*/
public static CompletableFuture<Void> doDbAction(ConnectionConsumer consumer) {
CompletableFuture<Void> future = new CompletableFuture<>();
Bot.asyncPool.submit(() -> {
try (var c = Bot.hikariDataSource.getConnection()) {
consumer.consume(c);
future.complete(null);
} catch (SQLException e) {
future.completeExceptionally(e);
}
});
return future;
}

/**
* Does an asynchronous database action using the bot's async pool, and
* wraps access to the connection behind a data access object that can be
* built using the provided dao constructor.
* @param daoConstructor A function to build a DAO using a connection.
* @param consumer The consumer that does something with the DAO.
* @param <T> The type of data access object. Usually some kind of repository.
* @return A future that completes when the action is complete.
*/
public static <T> CompletableFuture<Void> doDaoAction(Function<Connection, T> daoConstructor, DaoConsumer<T> consumer) {
CompletableFuture<Void> future = new CompletableFuture<>();
Bot.asyncPool.submit(() -> {
try (var c = Bot.hikariDataSource.getConnection()) {
var dao = daoConstructor.apply(c);
consumer.consume(dao);
future.complete(null);
} catch (SQLException e) {
future.completeExceptionally(e);
}
});
return future;
}

private static boolean shouldInitSchema(String jdbcUrl) {
var p = Pattern.compile("jdbc:h2:tcp://localhost:\\d+/(.*)");
var m = p.matcher(jdbcUrl);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/**
* The "activity" system contains commands and services pertaining to events and
* activities that the server manages.
*/
package net.javadiscord.javabot2.systems.activity;
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package net.javadiscord.javabot2.systems.activity.qotw;

import net.javadiscord.javabot2.command.ResponseException;
import net.javadiscord.javabot2.command.Responses;
import net.javadiscord.javabot2.command.SlashCommandHandler;
import org.javacord.api.interaction.SlashCommandInteraction;
import org.javacord.api.interaction.callback.InteractionImmediateResponseBuilder;

public class AddQuestionSubcommand implements SlashCommandHandler {
@Override
public InteractionImmediateResponseBuilder handle(SlashCommandInteraction interaction) throws ResponseException {
String question = interaction.getOptionStringValueByName("question")
.orElseThrow(ResponseException.warning("Missing required question."));
int priority = (int) interaction.getOptionLongValueByName("priority")
.orElse(0L).longValue();
var service = new QOTWService();
service.saveNewQuestion(interaction.getUser(), question, priority)
.thenAcceptAsync(q -> {
interaction.getChannel().orElseThrow().sendMessage("Question **" + q.getId() + "** has been added to the queue.");
})
.exceptionallyAsync(throwable -> {
interaction.getChannel().orElseThrow().sendMessage("An error occurred and the question could not be added to the queue.");
return null;
});
return Responses.success(interaction, "Question Added", "Your question has been added to the QOTW queue.");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package net.javadiscord.javabot2.systems.activity.qotw;

import net.javadiscord.javabot2.command.ResponseException;
import net.javadiscord.javabot2.command.SlashCommandHandler;
import org.javacord.api.interaction.SlashCommandInteraction;
import org.javacord.api.interaction.callback.InteractionImmediateResponseBuilder;

public class ListAnswersSubcommand implements SlashCommandHandler {
/**
* Handles a slash command interaction.
*
* @param interaction The interaction.
* @return An immediate response to the interaction.
* @throws ResponseException If an error occurs while handling the event.
*/
@Override
public InteractionImmediateResponseBuilder handle(SlashCommandInteraction interaction) throws ResponseException {
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package net.javadiscord.javabot2.systems.activity.qotw;

import net.javadiscord.javabot2.command.ResponseException;
import net.javadiscord.javabot2.command.SlashCommandHandler;
import org.javacord.api.interaction.SlashCommandInteraction;
import org.javacord.api.interaction.callback.InteractionImmediateResponseBuilder;

public class ListQuestionsSubcommand implements SlashCommandHandler {
/**
* Handles a slash command interaction.
*
* @param interaction The interaction.
* @return An immediate response to the interaction.
* @throws ResponseException If an error occurs while handling the event.
*/
@Override
public InteractionImmediateResponseBuilder handle(SlashCommandInteraction interaction) throws ResponseException {
return null;
}
}
Loading