Skip to content

Commit 9a40b34

Browse files
author
Dynxsty
authored
Merge pull request #21 from Java-Discord/andrew/some_cleanup
2 parents 63d02b5 + a1bd338 commit 9a40b34

File tree

5 files changed

+166
-94
lines changed

5 files changed

+166
-94
lines changed

src/main/java/com/javadiscord/javabot/Bot.java

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,46 @@
55
import net.dv8tion.jda.api.JDA;
66
import net.dv8tion.jda.api.JDABuilder;
77
import net.dv8tion.jda.api.OnlineStatus;
8+
import net.dv8tion.jda.api.entities.Guild;
89
import net.dv8tion.jda.api.requests.GatewayIntent;
910
import net.dv8tion.jda.api.utils.MemberCachePolicy;
1011
import net.dv8tion.jda.api.utils.cache.CacheFlag;
1112

1213
import java.nio.file.Path;
1314
import java.util.Properties;
1415

16+
/**
17+
* The main class where the bot is initialized.
18+
*/
1519
public class Bot {
20+
/**
21+
* Loads the bot properties, first from the internal classpath properties
22+
* file, and then any properties file in the current working directory will
23+
* take precedence over that.
24+
*/
1625
private static final Properties properties = new MultiProperties(
1726
MultiProperties.getClasspathResource("bot.properties").orElseThrow(),
1827
Path.of("bot.props")
19-
2028
);
2129

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

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

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

35-
//EVENTS
36-
jda.addEventListener(new GuildJoin());
37-
jda.addEventListener(new UserJoin());
38-
jda.addEventListener(new UserLeave());
39-
jda.addEventListener(new Startup());
40-
jda.addEventListener(PresenceUpdater.standardActivities());
41-
jda.addEventListener(new SuggestionListener());
42-
jda.addEventListener(new AutoMod());
43-
jda.addEventListener(new SubmissionListener());
44-
jda.addEventListener(new StarboardListener());
61+
/**
62+
* Adds all of the bot's event listeners to the JDA instance, except for the
63+
* main {@link SlashCommands} listener.
64+
* @param jda The JDA bot instance to add listeners to.
65+
*/
66+
private static void addEventListeners(JDA jda) {
67+
jda.addEventListener(
68+
new GuildJoin(),
69+
new UserJoin(),
70+
new UserLeave(),
71+
new Startup(),
72+
PresenceUpdater.standardActivities(),
73+
new SuggestionListener(),
74+
new AutoMod(),
75+
new SubmissionListener(),
76+
new StarboardListener(),
77+
new ButtonClickListener()
78+
);
4579
}
4680

4781
/**

src/main/java/com/javadiscord/javabot/SlashCommands.java

Lines changed: 19 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import com.google.gson.JsonObject;
44
import com.google.gson.JsonParser;
55
import com.javadiscord.javabot.commands.SlashCommandHandler;
6-
import com.javadiscord.javabot.events.SubmissionListener;
76
import com.javadiscord.javabot.other.Constants;
87
import com.javadiscord.javabot.properties.command.CommandConfig;
98
import com.javadiscord.javabot.properties.command.CommandDataConfig;
@@ -13,9 +12,6 @@
1312
import com.mongodb.client.MongoDatabase;
1413
import net.dv8tion.jda.api.EmbedBuilder;
1514
import net.dv8tion.jda.api.entities.Guild;
16-
import net.dv8tion.jda.api.entities.Member;
17-
import net.dv8tion.jda.api.entities.Role;
18-
import net.dv8tion.jda.api.events.interaction.ButtonClickEvent;
1915
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
2016
import net.dv8tion.jda.api.hooks.ListenerAdapter;
2117
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
@@ -26,9 +22,17 @@
2622
import java.util.Map;
2723

2824
import static com.javadiscord.javabot.events.Startup.mongoClient;
29-
import static com.javadiscord.javabot.events.Startup.preferredGuild;
3025
import static com.mongodb.client.model.Filters.eq;
3126

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

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

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

104118
commands.queue();
105119
}
106-
107-
@Override
108-
public void onButtonClick(ButtonClickEvent event) {
109-
if (event.getUser().isBot()) return;
110-
111-
String[] id = event.getComponentId().split(":");
112-
event.deferEdit().queue();
113-
114-
JsonObject root;
115-
Document document;
116-
117-
Guild guild = preferredGuild;
118-
119-
MongoDatabase database = mongoClient.getDatabase("other");
120-
MongoCollection<Document> reactionroles = database.getCollection("reactionroles");
121-
MongoCollection<Document> openSubmissions = database.getCollection("open_submissions");
122-
MongoCollection<Document> submissionMessages = database.getCollection("submission_messages");
123-
124-
switch (id[0]) {
125-
case "dm-submission":
126-
127-
document = openSubmissions.find(eq("guild_id", guild.getId())).first();
128-
129-
root = JsonParser.parseString(document.toJson()).getAsJsonObject();
130-
String text = root.get("text").getAsString();
131-
132-
switch (id[1]) {
133-
case "send": new SubmissionListener().dmSubmissionSend(event, text); break;
134-
case "cancel": new SubmissionListener().dmSubmissionCancel(event); break;
135-
}
136-
openSubmissions.deleteOne(document);
137-
break;
138-
139-
case "submission":
140-
141-
document = submissionMessages.find(eq("guild_id", guild.getId())).first();
142-
143-
root = JsonParser.parseString(document.toJson()).getAsJsonObject();
144-
String userID = root.get("user_id").getAsString();
145-
146-
switch (id[1]) {
147-
case "approve": new SubmissionListener().submissionApprove(event, userID); break;
148-
case "decline": new SubmissionListener().submissionDecline(event); break;
149-
}
150-
submissionMessages.deleteOne(document);
151-
break;
152-
153-
case "reactionroles":
154-
155-
String messageID = id[1];
156-
String buttonLabel = id[2];
157-
158-
Member member = event.getGuild().retrieveMemberById(event.getUser().getId()).complete();
159-
160-
BasicDBObject criteria = new BasicDBObject()
161-
.append("guild_id", event.getGuild().getId())
162-
.append("message_id", messageID)
163-
.append("button_label", buttonLabel);
164-
165-
String JSON = reactionroles.find(criteria).first().toJson();
166-
167-
JsonObject Root = JsonParser.parseString(JSON).getAsJsonObject();
168-
String roleID = Root.get("role_id").getAsString();
169-
170-
Role role = event.getGuild().getRoleById(roleID);
171-
172-
if (member.getRoles().contains(role)) {
173-
event.getGuild().removeRoleFromMember(member, role).queue();
174-
event.getHook().sendMessage("Removed Role: " + role.getAsMention()).setEphemeral(true).queue();
175-
} else {
176-
event.getGuild().addRoleToMember(member, role).queue();
177-
event.getHook().sendMessage("Added Role: " + role.getAsMention()).setEphemeral(true).queue();
178-
}
179-
break;
180-
}
181-
}
182120
}

src/main/java/com/javadiscord/javabot/commands/moderation/Ban.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
1111
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
1212

13-
import java.util.Date;
13+
import java.time.Instant;
1414

1515
public class Ban implements SlashCommandHandler {
1616

@@ -41,7 +41,7 @@ public void handle(SlashCommandEvent event) {
4141
.addField("ID", "```" + member.getId() + "```", false)
4242
.addField("Reason", "```" + reason + "```", false)
4343
.setFooter("ID: " + member.getId())
44-
.setTimestamp(new Date().toInstant())
44+
.setTimestamp(Instant.now())
4545
.build();
4646

4747
event.replyEmbeds(eb).queue();
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
package com.javadiscord.javabot.events;
2+
3+
import com.google.gson.JsonObject;
4+
import com.google.gson.JsonParser;
5+
import com.mongodb.BasicDBObject;
6+
import com.mongodb.client.MongoCollection;
7+
import com.mongodb.client.MongoDatabase;
8+
import net.dv8tion.jda.api.entities.Guild;
9+
import net.dv8tion.jda.api.entities.Member;
10+
import net.dv8tion.jda.api.entities.Role;
11+
import net.dv8tion.jda.api.events.interaction.ButtonClickEvent;
12+
import net.dv8tion.jda.api.hooks.ListenerAdapter;
13+
import org.bson.Document;
14+
15+
import static com.javadiscord.javabot.events.Startup.mongoClient;
16+
import static com.javadiscord.javabot.events.Startup.preferredGuild;
17+
import static com.mongodb.client.model.Filters.eq;
18+
19+
public class ButtonClickListener extends ListenerAdapter {
20+
@Override
21+
public void onButtonClick(ButtonClickEvent event) {
22+
if (event.getUser().isBot()) return;
23+
24+
event.deferEdit().queue();
25+
26+
Guild guild = preferredGuild;
27+
MongoDatabase database = mongoClient.getDatabase("other");
28+
String[] id = event.getComponentId().split(":");
29+
switch (id[0]) {
30+
case "dm-submission":
31+
this.handleDmSubmission(database, guild, event);
32+
break;
33+
case "submission":
34+
this.handleSubmission(database, guild, event);
35+
break;
36+
case "reactionroles":
37+
this.handleReactionRoles(database, guild, event);
38+
break;
39+
}
40+
}
41+
42+
private void handleDmSubmission(MongoDatabase database, Guild guild, ButtonClickEvent event) {
43+
MongoCollection<Document> openSubmissions = database.getCollection("open_submissions");
44+
Document document = openSubmissions.find(eq("guild_id", guild.getId())).first();
45+
JsonObject root = JsonParser.parseString(document.toJson()).getAsJsonObject();
46+
String text = root.get("text").getAsString();
47+
String[] id = event.getComponentId().split(":");
48+
switch (id[1]) {
49+
case "send": new SubmissionListener().dmSubmissionSend(event, text); break;
50+
case "cancel": new SubmissionListener().dmSubmissionCancel(event); break;
51+
}
52+
openSubmissions.deleteOne(document);
53+
}
54+
55+
private void handleSubmission(MongoDatabase database, Guild guild, ButtonClickEvent event) {
56+
MongoCollection<Document> submissionMessages = database.getCollection("submission_messages");
57+
Document document = submissionMessages.find(eq("guild_id", guild.getId())).first();
58+
JsonObject root = JsonParser.parseString(document.toJson()).getAsJsonObject();
59+
String userID = root.get("user_id").getAsString();
60+
String[] id = event.getComponentId().split(":");
61+
switch (id[1]) {
62+
case "approve": new SubmissionListener().submissionApprove(event, userID); break;
63+
case "decline": new SubmissionListener().submissionDecline(event); break;
64+
}
65+
submissionMessages.deleteOne(document);
66+
}
67+
68+
private void handleReactionRoles(MongoDatabase database, Guild guild, ButtonClickEvent event) {
69+
String[] id = event.getComponentId().split(":");
70+
String messageID = id[1];
71+
String buttonLabel = id[2];
72+
73+
Member member = event.getGuild().retrieveMemberById(event.getUser().getId()).complete();
74+
75+
BasicDBObject criteria = new BasicDBObject()
76+
.append("guild_id", event.getGuild().getId())
77+
.append("message_id", messageID)
78+
.append("button_label", buttonLabel);
79+
80+
MongoCollection<Document> reactionroles = database.getCollection("reactionroles");
81+
String JSON = reactionroles.find(criteria).first().toJson();
82+
83+
JsonObject Root = JsonParser.parseString(JSON).getAsJsonObject();
84+
String roleID = Root.get("role_id").getAsString();
85+
86+
Role role = event.getGuild().getRoleById(roleID);
87+
88+
if (member.getRoles().contains(role)) {
89+
event.getGuild().removeRoleFromMember(member, role).queue();
90+
event.getHook().sendMessage("Removed Role: " + role.getAsMention()).setEphemeral(true).queue();
91+
} else {
92+
event.getGuild().addRoleToMember(member, role).queue();
93+
event.getHook().sendMessage("Added Role: " + role.getAsMention()).setEphemeral(true).queue();
94+
}
95+
}
96+
}

src/main/java/com/javadiscord/javabot/properties/command/CommandDataConfig.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44

55
import java.io.InputStream;
66

7+
/**
8+
* Simple helper class that loads an array of {@link CommandConfig} instances
9+
* from the commands.yaml file.
10+
*/
711
public class CommandDataConfig {
812
public static CommandConfig[] load() {
913
Yaml yaml = new Yaml();

0 commit comments

Comments
 (0)