Skip to content
Merged
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
56 changes: 45 additions & 11 deletions src/main/java/com/javadiscord/javabot/Bot.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,46 @@
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.MemberCachePolicy;
import net.dv8tion.jda.api.utils.cache.CacheFlag;

import java.nio.file.Path;
import java.util.Properties;

/**
* The main class where the bot is initialized.
*/
public class Bot {
/**
* Loads the bot properties, first from the internal classpath properties
* file, and then any properties file in the current working directory will
* take precedence over that.
*/
private static final Properties properties = new MultiProperties(
MultiProperties.getClasspathResource("bot.properties").orElseThrow(),
Path.of("bot.props")

);

/**
* A reference to the slash command listener that's the main point of
* interaction for users with this bot. It's marked as a publicly accessible
* reference so that {@link SlashCommands#registerSlashCommands(Guild)} can
* be called wherever it's needed.
*/
public static SlashCommands slashCommands;

/**
* The main method that starts the bot. This involves a few steps:
* <ol>
* <li>Initializing the {@link SlashCommands} listener (which reads command data from a YAML file).</li>
* <li>Creating and configuring the {@link JDA} instance that enables the bot's Discord connectivity.</li>
* <li>Adding event listeners to the bot.</li>
* </ol>
* @param args Command-line arguments.
* @throws Exception If any exception occurs during bot creation.
*/
public static void main(String[] args) throws Exception {
slashCommands = new SlashCommands();

Expand All @@ -31,17 +55,27 @@ public static void main(String[] args) throws Exception {
.enableIntents(GatewayIntent.GUILD_MEMBERS, GatewayIntent.GUILD_PRESENCES)
.addEventListeners(slashCommands)
.build();
addEventListeners(jda);
}

//EVENTS
jda.addEventListener(new GuildJoin());
jda.addEventListener(new UserJoin());
jda.addEventListener(new UserLeave());
jda.addEventListener(new Startup());
jda.addEventListener(PresenceUpdater.standardActivities());
jda.addEventListener(new SuggestionListener());
jda.addEventListener(new AutoMod());
jda.addEventListener(new SubmissionListener());
jda.addEventListener(new StarboardListener());
/**
* Adds all of the bot's event listeners to the JDA instance, except for the
* main {@link SlashCommands} listener.
* @param jda The JDA bot instance to add listeners to.
*/
private static void addEventListeners(JDA jda) {
jda.addEventListener(
new GuildJoin(),
new UserJoin(),
new UserLeave(),
new Startup(),
PresenceUpdater.standardActivities(),
new SuggestionListener(),
new AutoMod(),
new SubmissionListener(),
new StarboardListener(),
new ButtonClickListener()
);
}

/**
Expand Down
100 changes: 19 additions & 81 deletions src/main/java/com/javadiscord/javabot/SlashCommands.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.javadiscord.javabot.commands.SlashCommandHandler;
import com.javadiscord.javabot.events.SubmissionListener;
import com.javadiscord.javabot.other.Constants;
import com.javadiscord.javabot.properties.command.CommandConfig;
import com.javadiscord.javabot.properties.command.CommandDataConfig;
Expand All @@ -13,9 +12,6 @@
import com.mongodb.client.MongoDatabase;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.events.interaction.ButtonClickEvent;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
Expand All @@ -26,9 +22,17 @@
import java.util.Map;

import static com.javadiscord.javabot.events.Startup.mongoClient;
import static com.javadiscord.javabot.events.Startup.preferredGuild;
import static com.mongodb.client.model.Filters.eq;

/**
* This listener is responsible for handling slash commands sent by users in
* guilds where the bot is active, and responding to them by calling the
* appropriate {@link SlashCommandHandler}.
* <p>
* The list of valid commands, and their associated handlers, are defined in
* the commands.yaml file under the resources directory.
* </p>
*/
public class SlashCommands extends ListenerAdapter {
/**
* Maps every command name and alias to an instance of the command, for
Expand Down Expand Up @@ -69,6 +73,16 @@ public void onSlashCommand(SlashCommandEvent event) {
}
}

/**
* Registers all slash commands defined in commands.yaml for the given guild
* so that users can see the commands when they type a "/".
* <p>
* It does this by attempting to add an entry to {@link SlashCommands#commandsIndex}
* whose key is the command name, and whose value is a new instance of
* the handler class which the command has specified.
* </p>
* @param guild The guild to update commands for.
*/
public void registerSlashCommands(Guild guild) {
CommandListUpdateAction commands = guild.updateCommands();

Expand Down Expand Up @@ -103,80 +117,4 @@ public void registerSlashCommands(Guild guild) {

commands.queue();
}

@Override
public void onButtonClick(ButtonClickEvent event) {
if (event.getUser().isBot()) return;

String[] id = event.getComponentId().split(":");
event.deferEdit().queue();

JsonObject root;
Document document;

Guild guild = preferredGuild;

MongoDatabase database = mongoClient.getDatabase("other");
MongoCollection<Document> reactionroles = database.getCollection("reactionroles");
MongoCollection<Document> openSubmissions = database.getCollection("open_submissions");
MongoCollection<Document> submissionMessages = database.getCollection("submission_messages");

switch (id[0]) {
case "dm-submission":

document = openSubmissions.find(eq("guild_id", guild.getId())).first();

root = JsonParser.parseString(document.toJson()).getAsJsonObject();
String text = root.get("text").getAsString();

switch (id[1]) {
case "send": new SubmissionListener().dmSubmissionSend(event, text); break;
case "cancel": new SubmissionListener().dmSubmissionCancel(event); break;
}
openSubmissions.deleteOne(document);
break;

case "submission":

document = submissionMessages.find(eq("guild_id", guild.getId())).first();

root = JsonParser.parseString(document.toJson()).getAsJsonObject();
String userID = root.get("user_id").getAsString();

switch (id[1]) {
case "approve": new SubmissionListener().submissionApprove(event, userID); break;
case "decline": new SubmissionListener().submissionDecline(event); break;
}
submissionMessages.deleteOne(document);
break;

case "reactionroles":

String messageID = id[1];
String buttonLabel = id[2];

Member member = event.getGuild().retrieveMemberById(event.getUser().getId()).complete();

BasicDBObject criteria = new BasicDBObject()
.append("guild_id", event.getGuild().getId())
.append("message_id", messageID)
.append("button_label", buttonLabel);

String JSON = reactionroles.find(criteria).first().toJson();

JsonObject Root = JsonParser.parseString(JSON).getAsJsonObject();
String roleID = Root.get("role_id").getAsString();

Role role = event.getGuild().getRoleById(roleID);

if (member.getRoles().contains(role)) {
event.getGuild().removeRoleFromMember(member, role).queue();
event.getHook().sendMessage("Removed Role: " + role.getAsMention()).setEphemeral(true).queue();
} else {
event.getGuild().addRoleToMember(member, role).queue();
event.getHook().sendMessage("Added Role: " + role.getAsMention()).setEphemeral(true).queue();
}
break;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;

import java.util.Date;
import java.time.Instant;

public class Ban implements SlashCommandHandler {

Expand Down Expand Up @@ -41,7 +41,7 @@ public void handle(SlashCommandEvent event) {
.addField("ID", "```" + member.getId() + "```", false)
.addField("Reason", "```" + reason + "```", false)
.setFooter("ID: " + member.getId())
.setTimestamp(new Date().toInstant())
.setTimestamp(Instant.now())
.build();

event.replyEmbeds(eb).queue();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package com.javadiscord.javabot.events;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.events.interaction.ButtonClickEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.bson.Document;

import static com.javadiscord.javabot.events.Startup.mongoClient;
import static com.javadiscord.javabot.events.Startup.preferredGuild;
import static com.mongodb.client.model.Filters.eq;

public class ButtonClickListener extends ListenerAdapter {
@Override
public void onButtonClick(ButtonClickEvent event) {
if (event.getUser().isBot()) return;

event.deferEdit().queue();

Guild guild = preferredGuild;
MongoDatabase database = mongoClient.getDatabase("other");
String[] id = event.getComponentId().split(":");
switch (id[0]) {
case "dm-submission":
this.handleDmSubmission(database, guild, event);
break;
case "submission":
this.handleSubmission(database, guild, event);
break;
case "reactionroles":
this.handleReactionRoles(database, guild, event);
break;
}
}

private void handleDmSubmission(MongoDatabase database, Guild guild, ButtonClickEvent event) {
MongoCollection<Document> openSubmissions = database.getCollection("open_submissions");
Document document = openSubmissions.find(eq("guild_id", guild.getId())).first();
JsonObject root = JsonParser.parseString(document.toJson()).getAsJsonObject();
String text = root.get("text").getAsString();
String[] id = event.getComponentId().split(":");
switch (id[1]) {
case "send": new SubmissionListener().dmSubmissionSend(event, text); break;
case "cancel": new SubmissionListener().dmSubmissionCancel(event); break;
}
openSubmissions.deleteOne(document);
}

private void handleSubmission(MongoDatabase database, Guild guild, ButtonClickEvent event) {
MongoCollection<Document> submissionMessages = database.getCollection("submission_messages");
Document document = submissionMessages.find(eq("guild_id", guild.getId())).first();
JsonObject root = JsonParser.parseString(document.toJson()).getAsJsonObject();
String userID = root.get("user_id").getAsString();
String[] id = event.getComponentId().split(":");
switch (id[1]) {
case "approve": new SubmissionListener().submissionApprove(event, userID); break;
case "decline": new SubmissionListener().submissionDecline(event); break;
}
submissionMessages.deleteOne(document);
}

private void handleReactionRoles(MongoDatabase database, Guild guild, ButtonClickEvent event) {
String[] id = event.getComponentId().split(":");
String messageID = id[1];
String buttonLabel = id[2];

Member member = event.getGuild().retrieveMemberById(event.getUser().getId()).complete();

BasicDBObject criteria = new BasicDBObject()
.append("guild_id", event.getGuild().getId())
.append("message_id", messageID)
.append("button_label", buttonLabel);

MongoCollection<Document> reactionroles = database.getCollection("reactionroles");
String JSON = reactionroles.find(criteria).first().toJson();

JsonObject Root = JsonParser.parseString(JSON).getAsJsonObject();
String roleID = Root.get("role_id").getAsString();

Role role = event.getGuild().getRoleById(roleID);

if (member.getRoles().contains(role)) {
event.getGuild().removeRoleFromMember(member, role).queue();
event.getHook().sendMessage("Removed Role: " + role.getAsMention()).setEphemeral(true).queue();
} else {
event.getGuild().addRoleToMember(member, role).queue();
event.getHook().sendMessage("Added Role: " + role.getAsMention()).setEphemeral(true).queue();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

import java.io.InputStream;

/**
* Simple helper class that loads an array of {@link CommandConfig} instances
* from the commands.yaml file.
*/
public class CommandDataConfig {
public static CommandConfig[] load() {
Yaml yaml = new Yaml();
Expand Down