Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.requests.GatewayIntent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.commands.Commands;
import org.togetherjava.tjbot.commands.system.CommandSystem;
import org.togetherjava.tjbot.config.Config;
import org.togetherjava.tjbot.db.Database;
import org.togetherjava.tjbot.routines.ModAuditLogRoutine;

import javax.security.auth.login.LoginException;
import java.io.IOException;
Expand Down Expand Up @@ -77,15 +77,12 @@ public static void runBot(String token, Path databasePath) {
Database database = new Database("jdbc:sqlite:" + databasePath.toAbsolutePath());

JDA jda = JDABuilder.createDefault(token)
.addEventListeners(new CommandSystem(database))
.enableIntents(GatewayIntent.GUILD_MEMBERS)
.build();
jda.addEventListener(new CommandSystem(jda, database));
jda.awaitReady();
logger.info("Bot is ready");

// TODO This should be moved into some proper command system instead (see GH issue #235
// which adds support for routines)
new ModAuditLogRoutine(jda, database).start();

Runtime.getRuntime().addShutdownHook(new Thread(Application::onShutdown));
} catch (LoginException e) {
logger.error("Failed to login", e);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.togetherjava.tjbot.commands;

import net.dv8tion.jda.api.JDA;
import org.jetbrains.annotations.NotNull;
import org.togetherjava.tjbot.commands.basic.DatabaseCommand;
import org.togetherjava.tjbot.commands.basic.PingCommand;
Expand All @@ -12,6 +13,7 @@
import org.togetherjava.tjbot.commands.tags.TagSystem;
import org.togetherjava.tjbot.commands.tags.TagsCommand;
import org.togetherjava.tjbot.db.Database;
import org.togetherjava.tjbot.routines.ModAuditLogRoutine;

import java.util.ArrayList;
import java.util.Collection;
Expand All @@ -22,7 +24,7 @@
* pick it up from and register it with the system.
* <p>
* To add a new slash command, extend the commands returned by
* {@link #createSlashCommands(Database)}.
* {@link #createSlashCommands(JDA, Database)}.
*/
public enum Commands {
;
Expand All @@ -33,13 +35,23 @@ public enum Commands {
* Calling this method multiple times will result in multiple commands being created, which
* generally should be avoided.
*
* @param jda the JDA instance commands will be registered at
* @param database the database of the application, which commands can use to persist data
* @return a collection of all slash commands
*/
public static @NotNull Collection<SlashCommand> createSlashCommands(
public static @NotNull Collection<SlashCommand> createSlashCommands(@NotNull JDA jda,
@NotNull Database database) {
TagSystem tagSystem = new TagSystem(database);
ModerationActionsStore actionsStore = new ModerationActionsStore(database);

// TODO This should be moved into some proper command system instead (see GH issue #235
// which adds support for routines)
new ModAuditLogRoutine(jda, database).start();

// TODO This should be moved into some proper command system instead (see GH issue #236
// which adds support for listeners)
jda.addEventListener(new RejoinMuteListener(actionsStore));

// NOTE The command system can add special system relevant commands also by itself,
// hence this list may not necessarily represent the full list of all commands actually
// available.
Expand All @@ -57,6 +69,8 @@ public enum Commands {
commands.add(new UnbanCommand(actionsStore));
commands.add(new FreeCommand());
commands.add(new AuditCommand(actionsStore));
commands.add(new MuteCommand(actionsStore));
commands.add(new UnmuteCommand(actionsStore));

return commands;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.config.Config;

import java.awt.*;
import java.time.Instant;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.regex.Pattern;

/**
* Utility class offering helpers revolving around user moderation, such as banning or kicking.
*/
enum ModerationUtils {
public enum ModerationUtils {
;

private static final Logger logger = LoggerFactory.getLogger(ModerationUtils.class);
Expand All @@ -26,6 +29,8 @@ enum ModerationUtils {
*/
private static final int REASON_MAX_LENGTH = 512;
static final Color AMBIENT_COLOR = Color.decode("#895FE8");
public static final Predicate<String> isMuteRole =
Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate();

/**
* Checks whether the given reason is valid. If not, it will handle the situation and respond to
Expand Down Expand Up @@ -85,6 +90,41 @@ static boolean handleCanInteractWithTarget(@NotNull String actionVerb, @NotNull
return true;
}

/**
* Checks whether the given author and bot can interact with the given role. For example whether
* they have enough permissions to add or remove this role to users.
* <p>
* If not, it will handle the situation and respond to the user.
*
* @param bot the bot attempting to interact with the user
* @param author the author triggering the command
* @param role the role to interact with
* @param event the event used to respond to the user
* @return Whether the author and bot can interact with the role
*/
@SuppressWarnings("BooleanMethodNameMustStartWithQuestion")
static boolean handleCanInteractWithRole(@NotNull Member bot, @NotNull Member author,
@NotNull Role role, @NotNull Interaction event) {
if (!author.canInteract(role)) {
event
.reply("The role %s is too powerful for you to interact with."
.formatted(role.getAsMention()))
.setEphemeral(true)
.queue();
return false;
}

if (!bot.canInteract(role)) {
event
.reply("The role %s is too powerful for me to interact with."
.formatted(role.getAsMention()))
.setEphemeral(true)
.queue();
return false;
}
return true;
}

Comment thread
RealYusufIsmail marked this conversation as resolved.
Resolved
/**
* Checks whether the given bot has enough permission to execute the given action. For example
* whether it has enough permissions to ban users.
Expand Down Expand Up @@ -115,6 +155,81 @@ static boolean handleHasBotPermissions(@NotNull String actionVerb,
return true;
}

private static void handleAbsentTarget(@NotNull String actionVerb, @NotNull Interaction event) {
Comment thread
Zabuzard marked this conversation as resolved.
Resolved
event
.reply("I can not %s the given user since they are not part of the guild anymore."
.formatted(actionVerb))
.setEphemeral(true)
.queue();
}
Comment thread
RealYusufIsmail marked this conversation as resolved.
Resolved

/**
* Checks whether the given bot and author have enough permission to change the roles of a given
* target. For example whether they have enough permissions to add a role to a user.
* <p>
* If not, it will handle the situation and respond to the user.
* <p>
* The checks include:
* <ul>
Comment thread
Zabuzard marked this conversation as resolved.
Resolved
* <li>the role does not exist on the guild</li>
* <li>the target is not member of the guild</li>
* <li>the bot or author do not have enough permissions to interact with the target</li>
* <li>the bot or author do not have enough permissions to interact with the role</li>
* <li>the author does not have the required role for this interaction</li>
* <li>the bot does not have the MANAGE_ROLES permission</li>
* <li>the given reason is too long</li>
* </ul>
*
* @param role the role to change, or {@code null} if it does not exist on the guild
* @param actionVerb the interaction as verb, for example {@code "mute"} or {@code "unmute"}
* @param target the target user to change roles from, or {@code null} if the user is not member
* of the guild
* @param bot the bot executing this interaction
* @param author the author attempting to interact with the target
* @param guild the guild this interaction is executed on
* @param hasRequiredRole a predicate used to identify required roles by their name
* @param reason the reason for this interaction
* @param event the event used to respond to the user
* @return Whether the bot and the author have enough permission
*/
@SuppressWarnings({"MethodWithTooManyParameters", "BooleanMethodNameMustStartWithQuestion",
"squid:S107"})
static boolean handleRoleChangeChecks(@Nullable Role role, @NotNull String actionVerb,
Comment thread
Zabuzard marked this conversation as resolved.
Resolved
@Nullable Member target, @NotNull Member bot, @NotNull Member author,
@NotNull Guild guild, @NotNull Predicate<? super String> hasRequiredRole,
@NotNull CharSequence reason, @NotNull Interaction event) {
if (role == null) {
event
.reply("Can not %s the user, unable to find the corresponding role on this server"
.formatted(actionVerb))
.setEphemeral(true)
.queue();
Comment thread
Zabuzard marked this conversation as resolved.
Resolved
logger.warn("The guild '{}' does not have a role to {} users.", guild.getName(),
actionVerb);
return false;
}

// Member doesn't exist if attempting to change roles of a user who is not part of the guild
// anymore.
if (target == null) {
handleAbsentTarget(actionVerb, event);
return false;
}
if (!handleCanInteractWithTarget(actionVerb, bot, author, target, event)) {
return false;
}
if (!handleCanInteractWithRole(bot, author, role, event)) {
return false;
}
if (!handleHasAuthorRole(actionVerb, hasRequiredRole, author, event)) {
return false;
}
if (!handleHasBotPermissions(actionVerb, Permission.MANAGE_ROLES, bot, guild, event)) {
return false;
}
Comment thread
Zabuzard marked this conversation as resolved.
Resolved
return ModerationUtils.handleReason(reason, event);
}

/**
* Checks whether the given author has enough permission to execute the given action. For
* example whether they have enough permissions to ban users.
Expand Down Expand Up @@ -171,7 +286,7 @@ static boolean handleHasAuthorRole(@NotNull String actionVerb,

/**
* Creates a message to be displayed as response to a moderation action.
*
* <p>
* Essentially, it informs others about the action, such as "John banned Bob for playing with
* the fire.".
*
Expand Down Expand Up @@ -200,6 +315,16 @@ static boolean handleHasAuthorRole(@NotNull String actionVerb,
.build();
}

/**
* Gets the role used to mute a member in a guild.
*
* @param guild the guild to get the muted role from
* @return the muted role, if found
*/
public static @NotNull Optional<Role> getMutedRole(@NotNull Guild guild) {
return guild.getRoles().stream().filter(role -> isMuteRole.test(role.getName())).findAny();
}

/**
* All available moderation actions.
*/
Expand All @@ -215,7 +340,15 @@ enum Action {
/**
* When a user kicks another user.
*/
KICK("kicked");
KICK("kicked"),
/**
* When a user mutes another user.
*/
MUTE("muted"),
/**
* When a user unmutes another user.
*/
UNMUTE("unmuted");

private final String verb;

Expand Down
Loading