Skip to content

Commit 07f7bc4

Browse files
Introduction of NotificationService
1 parent c00e0a9 commit 07f7bc4

File tree

17 files changed

+208
-131
lines changed

17 files changed

+208
-131
lines changed

src/main/java/net/javadiscord/javabot/command/InteractionHandler.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import net.javadiscord.javabot.command.interfaces.UserContextCommand;
2929
import net.javadiscord.javabot.systems.staff.custom_commands.dao.CustomCommandRepository;
3030
import net.javadiscord.javabot.systems.staff.custom_commands.model.CustomCommand;
31+
import net.javadiscord.javabot.systems.notification.GuildNotificationService;
3132
import net.javadiscord.javabot.util.GuildUtils;
3233
import org.jetbrains.annotations.NotNull;
3334
import org.slf4j.Logger;
@@ -146,13 +147,13 @@ private void handleResponseException(ResponseException e, CommandInteraction int
146147
StringWriter sw = new StringWriter();
147148
PrintWriter pw = new PrintWriter(sw);
148149
e.getCause().printStackTrace(pw);
149-
GuildUtils.getLogChannel(interaction.getGuild()).sendMessageFormat(
150+
new GuildNotificationService(interaction.getGuild()).sendLogChannelNotification(
150151
"An exception occurred when %s issued the **%s** command in %s:\n```%s```\n",
151152
interaction.getUser().getAsMention(),
152153
interaction.getName(),
153154
interaction.getTextChannel().getAsMention(),
154155
sw.toString()
155-
).queue();
156+
);
156157
}
157158
}
158159

src/main/java/net/javadiscord/javabot/data/h2db/message_cache/MessageCache.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import net.javadiscord.javabot.data.h2db.message_cache.dao.MessageCacheRepository;
1212
import net.javadiscord.javabot.data.h2db.message_cache.model.CachedMessage;
1313
import net.javadiscord.javabot.systems.commands.IdCalculatorCommand;
14-
import net.javadiscord.javabot.util.GuildUtils;
1514
import net.javadiscord.javabot.util.TimeUtils;
1615

1716
import java.io.ByteArrayInputStream;
@@ -90,7 +89,7 @@ public void cache(Message message) {
9089
*/
9190
public void sendUpdatedMessageToLog(Message updated, CachedMessage before) {
9291
if (updated.getContentRaw().trim().equals(before.getMessageContent())) return;
93-
MessageAction action = GuildUtils.getCacheLogChannel(updated.getGuild())
92+
MessageAction action = Bot.config.get(updated.getGuild()).getMessageCache().getMessageCacheLogChannel()
9493
.sendMessageEmbeds(this.buildMessageEditEmbed(updated.getGuild(), updated.getAuthor(), updated.getChannel(), before, updated))
9594
.setActionRow(Button.link(updated.getJumpUrl(), "Jump to Message"));
9695
if (before.getMessageContent().length() > MessageEmbed.VALUE_MAX_LENGTH || updated.getContentRaw().length() > MessageEmbed.VALUE_MAX_LENGTH) {
@@ -108,7 +107,7 @@ public void sendUpdatedMessageToLog(Message updated, CachedMessage before) {
108107
*/
109108
public void sendDeletedMessageToLog(Guild guild, MessageChannel channel, CachedMessage message) {
110109
guild.getJDA().retrieveUserById(message.getAuthorId()).queue(author -> {
111-
MessageAction action = GuildUtils.getCacheLogChannel(guild)
110+
MessageAction action = Bot.config.get(guild).getMessageCache().getMessageCacheLogChannel()
112111
.sendMessageEmbeds(this.buildMessageDeleteEmbed(guild, author, channel, message));
113112
if (message.getMessageContent().length() > MessageEmbed.VALUE_MAX_LENGTH) {
114113
action.addFile(this.buildDeletedMessageFile(author, message), message.getMessageId() + ".txt");

src/main/java/net/javadiscord/javabot/listener/StartupListener.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import net.javadiscord.javabot.Constants;
1010
import net.javadiscord.javabot.systems.help.HelpChannelUpdater;
1111
import net.javadiscord.javabot.systems.help.checks.SimpleGreetingCheck;
12+
import net.javadiscord.javabot.systems.notification.GuildNotificationService;
1213
import net.javadiscord.javabot.util.GuildUtils;
1314

1415
import java.util.Comparator;
@@ -51,7 +52,7 @@ public void onReady(ReadyEvent event) {
5152
helpConfig.getUpdateIntervalSeconds(),
5253
TimeUnit.SECONDS
5354
);
54-
GuildUtils.getLogChannel(guild).sendMessage("I have just been booted up!").queue();
55+
new GuildNotificationService(guild).sendLogChannelNotification("I have just been booted up!");
5556
}
5657
}
5758
}

src/main/java/net/javadiscord/javabot/systems/moderation/AutoMod.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import net.dv8tion.jda.api.hooks.ListenerAdapter;
1111
import net.javadiscord.javabot.Bot;
1212
import net.javadiscord.javabot.systems.moderation.warn.model.WarnSeverity;
13-
import net.javadiscord.javabot.util.GuildUtils;
13+
import net.javadiscord.javabot.systems.notification.GuildNotificationService;
1414

1515
import javax.annotation.Nonnull;
1616
import javax.net.ssl.HttpsURLConnection;
@@ -125,7 +125,7 @@ private void checkNewMessageAutomod(@Nonnull Message message) {
125125
private void checkContentAutomod(@Nonnull Message message) {
126126
//Check for Advertising Links
127127
if (hasAdvertisingLink(message)) {
128-
GuildUtils.getLogChannel(message.getGuild()).sendMessage("Message: `" + message.getContentRaw() + "`").queue();
128+
new GuildNotificationService(message.getGuild()).sendLogChannelNotification("Message: `" + message.getContentRaw() + "`");
129129
new ModerationService(message.getJDA(), Bot.config.get(message.getGuild()))
130130
.warn(
131131
message.getMember(),
@@ -143,7 +143,7 @@ private void checkContentAutomod(@Nonnull Message message) {
143143

144144
//Check for suspicious Links
145145
if (hasSuspiciousLink(message)) {
146-
GuildUtils.getLogChannel(message.getGuild()).sendMessage(String.format("Suspicious Link sent by: %s (`%s`)", message.getMember().getAsMention(), message)).queue();
146+
new GuildNotificationService(message.getGuild()).sendLogChannelNotification("Suspicious Link sent by: %s (`%s`)", message.getMember().getAsMention(), message);
147147
new ModerationService(message.getJDA(), Bot.config.get(message.getGuild()))
148148
.warn(
149149
message.getMember(),

src/main/java/net/javadiscord/javabot/systems/moderation/ServerLock.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import net.dv8tion.jda.api.hooks.ListenerAdapter;
1111
import net.javadiscord.javabot.Bot;
1212
import net.javadiscord.javabot.Constants;
13-
import net.javadiscord.javabot.util.GuildUtils;
13+
import net.javadiscord.javabot.systems.notification.GuildNotificationService;
1414
import net.javadiscord.javabot.util.TimeUtils;
1515
import org.jetbrains.annotations.NotNull;
1616

@@ -190,7 +190,7 @@ private void rejectUserDuringRaid(GuildMemberJoinEvent event) {
190190
});
191191
});
192192
String diff = new TimeUtils().formatDurationToNow(event.getMember().getTimeCreated());
193-
GuildUtils.getLogChannel(event.getGuild()).sendMessageFormat("**%s** (%s old) tried to join this server.", event.getMember().getUser().getAsTag(), diff).queue();
193+
new GuildNotificationService(event.getGuild()).sendLogChannelNotification("**%s** (%s old) tried to join this server.", event.getMember().getUser().getAsTag(), diff);
194194
}
195195

196196
/**
@@ -205,9 +205,8 @@ private void lockServer(Guild guild, Collection<Member> potentialRaiders) {
205205
member.getUser().openPrivateChannel().queue(c -> {
206206
c.sendMessage("https://discord.gg/java").setEmbeds(buildServerLockEmbed(guild)).queue(msg -> {
207207
member.kick().queue(
208-
success -> {
209-
},
210-
error -> GuildUtils.getLogChannel(guild).sendMessageFormat("Could not kick member %s%n> `%s`", member.getUser().getAsTag(), error.getMessage()).queue());
208+
success -> {},
209+
error -> new GuildNotificationService(guild).sendLogChannelNotification("Could not kick member %s%n> `%s`", member.getUser().getAsTag(), error.getMessage()));
211210
});
212211
});
213212
}
@@ -225,15 +224,15 @@ private void lockServer(Guild guild, Collection<Member> potentialRaiders) {
225224
var config = Bot.config.get(guild);
226225
config.getServerLock().setLocked("true");
227226
Bot.config.get(guild).flush();
228-
GuildUtils.getLogChannel(guild).sendMessageFormat("""
227+
new GuildNotificationService(guild).sendLogChannelNotification("""
229228
**Server Locked** %s
230229
The automated locking system has detected that the following %d users may be part of a raid:
231230
%s
232231
""",
233232
config.getModeration().getStaffRole().getAsMention(),
234233
potentialRaiders.size(),
235234
membersString
236-
).queue();
235+
);
237236
}
238237

239238
/**
@@ -245,6 +244,6 @@ private void unlockServer(Guild guild) {
245244
var config = Bot.config.get(guild).getServerLock();
246245
config.setLocked("false");
247246
Bot.config.get(guild).flush();
248-
GuildUtils.getLogChannel(guild).sendMessage("Server unlocked automatically.").queue();
247+
new GuildNotificationService(guild).sendLogChannelNotification("Server unlocked automatically.");
249248
}
250249
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package net.javadiscord.javabot.systems.notification;
2+
3+
import net.dv8tion.jda.api.entities.Guild;
4+
import net.dv8tion.jda.api.entities.MessageEmbed;
5+
import net.javadiscord.javabot.Bot;
6+
import net.javadiscord.javabot.data.config.GuildConfig;
7+
8+
/**
9+
* Sends notifications within a single {@link Guild}.
10+
*/
11+
public non-sealed class GuildNotificationService extends NotificationService {
12+
13+
private final Guild guild;
14+
private final GuildConfig config;
15+
16+
public GuildNotificationService(Guild guild) {
17+
this.guild = guild;
18+
this.config = Bot.config.get(guild);
19+
}
20+
21+
public void sendLogChannelNotification(MessageEmbed embed) {
22+
this.sendMessageChannelNotification(config.getModeration().getLogChannel(), embed);
23+
}
24+
25+
public void sendLogChannelNotification(String string, Object... args) {
26+
this.sendMessageChannelNotification(config.getModeration().getLogChannel(), string, args);
27+
}
28+
29+
public void sendMessageLogChannelNotification(MessageEmbed embed) {
30+
this.sendMessageChannelNotification(config.getMessageCache().getMessageCacheLogChannel(), embed);
31+
}
32+
33+
private void sendMessageLogChannelNotification(String string, Object... args) {
34+
this.sendMessageChannelNotification(config.getMessageCache().getMessageCacheLogChannel(), string, args);
35+
}
36+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package net.javadiscord.javabot.systems.notification;
2+
3+
import lombok.extern.slf4j.Slf4j;
4+
import net.dv8tion.jda.api.entities.MessageChannel;
5+
import net.dv8tion.jda.api.entities.MessageEmbed;
6+
import net.dv8tion.jda.api.entities.User;
7+
8+
9+
/**
10+
* Abstract class used for sending Notifications to Discord Users and Channels.
11+
*/
12+
@Slf4j
13+
public abstract sealed class NotificationService permits GuildNotificationService, QOTWNotificationService {
14+
void sendDirectMessageNotification(User user, MessageEmbed message) {
15+
user.openPrivateChannel().queue(
16+
channel -> channel.sendMessageEmbeds(message).queue(),
17+
error -> log.warn("Could not send private Notification to User " + user.getAsTag())
18+
);
19+
}
20+
21+
void sendMessageChannelNotification(MessageChannel channel, MessageEmbed message) {
22+
channel.sendMessageEmbeds(message).queue();
23+
}
24+
25+
void sendMessageChannelNotification(MessageChannel channel, String s, Object... args) {
26+
channel.sendMessageFormat(s, args).queue();
27+
}
28+
}
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package net.javadiscord.javabot.systems.notification;
2+
3+
import lombok.extern.slf4j.Slf4j;
4+
import net.dv8tion.jda.api.EmbedBuilder;
5+
import net.dv8tion.jda.api.entities.Guild;
6+
import net.dv8tion.jda.api.entities.MessageEmbed;
7+
import net.dv8tion.jda.api.entities.User;
8+
import net.javadiscord.javabot.Bot;
9+
import net.javadiscord.javabot.systems.qotw.dao.QuestionPointsRepository;
10+
import net.javadiscord.javabot.systems.qotw.model.QOTWAccount;
11+
12+
import java.sql.Connection;
13+
import java.sql.SQLException;
14+
import java.time.Instant;
15+
16+
/**
17+
* Sends Notifications regarding QOTW.
18+
*/
19+
@Slf4j
20+
public non-sealed class QOTWNotificationService extends NotificationService {
21+
22+
private final User user;
23+
private final Guild guild;
24+
private final QOTWAccount account;
25+
26+
/**
27+
* The constructor of this class.
28+
*
29+
* @param user The user that should be notified.
30+
* @param guild The guild from where the notification was sent.
31+
*/
32+
public QOTWNotificationService(User user, Guild guild) {
33+
this.user = user;
34+
this.guild = guild;
35+
QOTWAccount account;
36+
try (Connection connection = Bot.dataSource.getConnection()) {
37+
QuestionPointsRepository dao = new QuestionPointsRepository(connection);
38+
account = dao.getAccountByUserId(user.getIdLong());
39+
} catch (SQLException e) {
40+
e.printStackTrace();
41+
account = null;
42+
}
43+
this.account = account;
44+
}
45+
46+
public void sendBestAnswerNotification() {
47+
this.sendDirectMessageNotification(user, this.buildBestAnswerEmbed(account.getPoints()));
48+
}
49+
50+
public void sendAccountIncrementedNotification() {
51+
this.sendDirectMessageNotification(user, this.buildAccountIncrementEmbed(account.getPoints()));
52+
}
53+
54+
private MessageEmbed buildBestAnswerEmbed(long points) {
55+
return new EmbedBuilder()
56+
.setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl())
57+
.setTitle("QOTW Notification")
58+
.setColor(Bot.config.get(guild).getSlashCommand().getSuccessColor())
59+
.setDescription(String.format(
60+
"""
61+
Your submission was marked as the best answer!
62+
You've been granted **`1 extra QOTW-Point`**! (total: %s)""", points))
63+
.setTimestamp(Instant.now())
64+
.build();
65+
}
66+
67+
private MessageEmbed buildAccountIncrementEmbed(long points) {
68+
return new EmbedBuilder()
69+
.setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl())
70+
.setTitle("QOTW Notification")
71+
.setColor(Bot.config.get(guild).getSlashCommand().getSuccessColor())
72+
.setDescription(String.format(
73+
"""
74+
Your submission was accepted! %s
75+
You've been granted **`1 QOTW-Point`**! (total: %s)""",
76+
Bot.config.get(guild).getEmote().getSuccessEmote().getAsMention(), points))
77+
.setTimestamp(Instant.now())
78+
.build();
79+
}
80+
}

src/main/java/net/javadiscord/javabot/systems/qotw/QOTWJob.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import net.javadiscord.javabot.systems.qotw.dao.QuestionQueueRepository;
1515
import net.javadiscord.javabot.systems.qotw.model.QOTWQuestion;
1616
import net.javadiscord.javabot.tasks.jobs.DiscordApiJob;
17-
import net.javadiscord.javabot.util.GuildUtils;
17+
import net.javadiscord.javabot.systems.notification.GuildNotificationService;
1818
import org.quartz.JobExecutionContext;
1919
import org.quartz.JobExecutionException;
2020

@@ -39,7 +39,7 @@ protected void execute(JobExecutionContext context, JDA jda) throws JobExecution
3939
QuestionQueueRepository repo = new QuestionQueueRepository(c);
4040
var nextQuestion = repo.getNextQuestion(guild.getIdLong());
4141
if (nextQuestion.isEmpty()) {
42-
GuildUtils.getLogChannel(guild).sendMessageFormat("Warning! %s No available next question for QOTW!", config.getQotw().getQOTWReviewRole().getAsMention()).queue();
42+
new GuildNotificationService(guild).sendLogChannelNotification("Warning! %s No available next question for QOTW!", config.getQotw().getQOTWReviewRole().getAsMention());
4343
} else {
4444
QOTWQuestion question = nextQuestion.get();
4545
QOTWConfig qotw = config.getQotw();
@@ -57,7 +57,7 @@ protected void execute(JobExecutionContext context, JDA jda) throws JobExecution
5757
}
5858
} catch (SQLException e) {
5959
e.printStackTrace();
60-
GuildUtils.getLogChannel(guild).sendMessageFormat("Warning! %s Could not send next QOTW question:\n```\n%s\n```\n", config.getQotw().getQOTWReviewRole().getAsMention(), e.getMessage()).queue();
60+
new GuildNotificationService(guild).sendLogChannelNotification("Warning! %s Could not send next QOTW question:\n```\n%s\n```\n", config.getQotw().getQOTWReviewRole().getAsMention(), e.getMessage());
6161
throw new JobExecutionException(e);
6262
}
6363
}

src/main/java/net/javadiscord/javabot/systems/qotw/QOTWReminderJob.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import net.javadiscord.javabot.data.config.guild.ModerationConfig;
66
import net.javadiscord.javabot.systems.qotw.dao.QuestionQueueRepository;
77
import net.javadiscord.javabot.tasks.jobs.DiscordApiJob;
8-
import net.javadiscord.javabot.util.GuildUtils;
8+
import net.javadiscord.javabot.systems.notification.GuildNotificationService;
99
import org.quartz.JobExecutionContext;
1010
import org.quartz.JobExecutionException;
1111

@@ -23,15 +23,15 @@ protected void execute(JobExecutionContext context, JDA jda) throws JobExecution
2323
var repo = new QuestionQueueRepository(c);
2424
var q = repo.getNextQuestion(guild.getIdLong());
2525
if (q.isEmpty()) {
26-
GuildUtils.getLogChannel(guild).sendMessageFormat(
26+
new GuildNotificationService(guild).sendLogChannelNotification(
2727
"Warning! %s There's no Question of the Week in the queue. Please add one before it's time to post!",
28-
config.getStaffRole().getAsMention()).queue();
28+
config.getStaffRole().getAsMention());
2929
}
3030
} catch (SQLException e) {
3131
e.printStackTrace();
32-
GuildUtils.getLogChannel(guild).sendMessageFormat(
32+
new GuildNotificationService(guild).sendLogChannelNotification(
3333
"Warning! %s Could not check to see if there's a question in the QOTW queue:\n```\n%s\n```\n",
34-
config.getStaffRole().getAsMention(), e.getMessage()).queue();
34+
config.getStaffRole().getAsMention(), e.getMessage());
3535
throw new JobExecutionException(e);
3636
}
3737
}

0 commit comments

Comments
 (0)