Skip to content

Commit 667da34

Browse files
Merge pull request #340 from Java-Discord/dynxsty/better_notifications
Refactored NotificationService
2 parents 6b15baf + 859a08f commit 667da34

18 files changed

+208
-199
lines changed

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
66
import net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdateNicknameEvent;
77
import net.dv8tion.jda.api.hooks.ListenerAdapter;
8-
import net.javadiscord.javabot.systems.notification.GuildNotificationService;
8+
import net.javadiscord.javabot.systems.notification.NotificationService;
99
import net.javadiscord.javabot.util.ExceptionLogger;
1010
import net.javadiscord.javabot.util.StringUtils;
1111

@@ -71,7 +71,7 @@ private void changeName(Member member) {
7171
member.getUser().openPrivateChannel()
7272
.flatMap(channel -> channel.sendMessageFormat("Your nickname has been set to `%s` since both your user- and nickname's first three characters were deemed as not-pingable.", newName))
7373
.queue();
74-
new GuildNotificationService(member.getGuild()).sendLogChannelNotification("Changed %s's nickname from `%s` to `%s`.", member.getAsMention(), oldName, newName);
74+
NotificationService.withGuild(member.getGuild()).sendToModerationLog(c -> c.sendMessageFormat("Changed %s's nickname from `%s` to `%s`.", member.getAsMention(), oldName, newName));
7575
}
7676

7777
/**

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import net.javadiscord.javabot.data.config.guild.HelpConfig;
1414
import net.javadiscord.javabot.systems.help.HelpChannelUpdater;
1515
import net.javadiscord.javabot.systems.help.checks.SimpleGreetingCheck;
16-
import net.javadiscord.javabot.systems.notification.GuildNotificationService;
16+
import net.javadiscord.javabot.systems.notification.NotificationService;
1717
import net.javadiscord.javabot.util.ExceptionLogger;
1818
import net.javadiscord.javabot.util.StringUtils;
1919
import org.jetbrains.annotations.NotNull;
@@ -47,7 +47,7 @@ public void onReady(@NotNull ReadyEvent event) {
4747
helpConfig.getUpdateIntervalSeconds(),
4848
TimeUnit.SECONDS
4949
);
50-
new GuildNotificationService(guild).sendLogChannelNotification(buildBootedUpEmbed());
50+
NotificationService.withGuild(guild).sendToModerationLog(c -> c.sendMessageEmbeds(buildBootedUpEmbed()));
5151
}
5252
try {
5353
Bot.getCustomTagManager().init();

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.systems.notification.GuildNotificationService;
13+
import net.javadiscord.javabot.systems.notification.NotificationService;
1414
import net.javadiscord.javabot.util.ExceptionLogger;
1515
import org.jetbrains.annotations.NotNull;
1616

@@ -123,7 +123,7 @@ private void checkNewMessageAutomod(@Nonnull Message message) {
123123
private void checkContentAutomod(@Nonnull Message message) {
124124
//Check for Advertising Links
125125
if (hasAdvertisingLink(message)) {
126-
new GuildNotificationService(message.getGuild()).sendLogChannelNotification("Message: `" + message.getContentRaw() + "`");
126+
NotificationService.withGuild(message.getGuild()).sendToModerationLog(c -> c.sendMessageFormat("Message: `%s`", message.getContentRaw()));
127127
new ModerationService(Bot.getConfig().get(message.getGuild()))
128128
.warn(
129129
message.getAuthor(),
@@ -141,7 +141,7 @@ private void checkContentAutomod(@Nonnull Message message) {
141141

142142
//Check for suspicious Links
143143
if (hasSuspiciousLink(message)) {
144-
new GuildNotificationService(message.getGuild()).sendLogChannelNotification("Suspicious Link sent by: %s (`%s`)", message.getMember().getAsMention(), message);
144+
NotificationService.withGuild(message.getGuild()).sendToModerationLog(c -> c.sendMessageFormat("Suspicious Link sent by: %s (`%s`)", message.getAuthor().getAsMention(), message.getContentRaw()));
145145
new ModerationService(Bot.getConfig().get(message.getGuild()))
146146
.warn(
147147
message.getAuthor(),

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

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
import net.javadiscord.javabot.systems.moderation.warn.dao.WarnRepository;
1313
import net.javadiscord.javabot.systems.moderation.warn.model.Warn;
1414
import net.javadiscord.javabot.systems.moderation.warn.model.WarnSeverity;
15-
import net.javadiscord.javabot.systems.notification.GuildNotificationService;
16-
import net.javadiscord.javabot.systems.notification.UserNotificationService;
15+
import net.javadiscord.javabot.systems.notification.NotificationService;
1716
import net.javadiscord.javabot.util.ExceptionLogger;
1817
import net.javadiscord.javabot.util.Responses;
1918
import org.jetbrains.annotations.NotNull;
@@ -73,8 +72,8 @@ public void warn(User user, WarnSeverity severity, String reason, Member warnedB
7372
dao.insert(new Warn(user.getIdLong(), warnedBy.getIdLong(), severity, reason));
7473
int totalSeverity = dao.getTotalSeverityWeight(user.getIdLong(), LocalDateTime.now().minusDays(moderationConfig.getWarnTimeoutDays()));
7574
MessageEmbed warnEmbed = buildWarnEmbed(user, warnedBy, severity, totalSeverity, reason);
76-
new UserNotificationService(user).sendDirectMessageNotification(warnEmbed);
77-
new GuildNotificationService(moderationConfig.getGuild()).sendLogChannelNotification(warnEmbed);
75+
NotificationService.withUser(user).sendDirectMessage(c -> c.sendMessageEmbeds(warnEmbed));
76+
NotificationService.withGuild(moderationConfig.getGuild()).sendToModerationLog(c -> c.sendMessageEmbeds(warnEmbed));
7877
if (!quiet && channel.getIdLong() != moderationConfig.getLogChannelId()) {
7978
channel.sendMessageEmbeds(warnEmbed).queue();
8079
}
@@ -94,8 +93,8 @@ public void discardAllWarns(User user, User clearedBy) {
9493
DbHelper.doDaoAction(WarnRepository::new, dao -> {
9594
dao.discardAll(user.getIdLong());
9695
MessageEmbed embed = buildClearWarnsEmbed(user, clearedBy);
97-
new UserNotificationService(user).sendDirectMessageNotification(embed);
98-
new GuildNotificationService(moderationConfig.getGuild()).sendLogChannelNotification(embed);
96+
NotificationService.withUser(user).sendDirectMessage(c -> c.sendMessageEmbeds(embed));
97+
NotificationService.withGuild(moderationConfig.getGuild()).sendToModerationLog(c -> c.sendMessageEmbeds(embed));
9998
});
10099
}
101100

@@ -113,8 +112,7 @@ public boolean discardWarnById(long id, User clearedBy) {
113112
if (warnOptional.isPresent()) {
114113
Warn warn = warnOptional.get();
115114
repo.discardById(warn.getId());
116-
new GuildNotificationService(moderationConfig.getGuild())
117-
.sendLogChannelNotification(buildClearWarnsByIdEmbed(warn, clearedBy));
115+
NotificationService.withGuild(moderationConfig.getGuild()).sendToModerationLog(c -> c.sendMessageEmbeds(buildClearWarnsByIdEmbed(warn, clearedBy)));
118116
return true;
119117
}
120118
} catch (SQLException e) {
@@ -153,8 +151,8 @@ public List<Warn> getWarns(long userId) {
153151
public void timeout(@Nonnull Member member, @Nonnull String reason, @Nonnull Member timedOutBy, @Nonnull Duration duration, @Nonnull MessageChannel channel, boolean quiet) {
154152
MessageEmbed timeoutEmbed = buildTimeoutEmbed(member, timedOutBy, reason, duration);
155153
member.getGuild().timeoutFor(member, duration).queue(s -> {
156-
new UserNotificationService(member.getUser()).sendDirectMessageNotification(timeoutEmbed);
157-
new GuildNotificationService(member.getGuild()).sendLogChannelNotification(timeoutEmbed);
154+
NotificationService.withUser(member.getUser()).sendDirectMessage(c -> c.sendMessageEmbeds(timeoutEmbed));
155+
NotificationService.withGuild(member.getGuild()).sendToModerationLog(c -> c.sendMessageEmbeds(timeoutEmbed));
158156
if (!quiet) channel.sendMessageEmbeds(timeoutEmbed).queue();
159157
}, ExceptionLogger::capture);
160158
}
@@ -171,8 +169,8 @@ public void timeout(@Nonnull Member member, @Nonnull String reason, @Nonnull Mem
171169
public void removeTimeout(Member member, String reason, Member removedBy, MessageChannel channel, boolean quiet) {
172170
MessageEmbed removeTimeoutEmbed = buildTimeoutRemovedEmbed(member, removedBy, reason);
173171
removedBy.getGuild().removeTimeout(member).queue(s -> {
174-
new UserNotificationService(member.getUser()).sendDirectMessageNotification(removeTimeoutEmbed);
175-
new GuildNotificationService(member.getGuild()).sendLogChannelNotification(removeTimeoutEmbed);
172+
NotificationService.withUser(member.getUser()).sendDirectMessage(c -> c.sendMessageEmbeds(removeTimeoutEmbed));
173+
NotificationService.withGuild(member.getGuild()).sendToModerationLog(c -> c.sendMessageEmbeds(removeTimeoutEmbed));
176174
if (!quiet) channel.sendMessageEmbeds(removeTimeoutEmbed).queue();
177175
}, ExceptionLogger::capture);
178176
}
@@ -189,8 +187,8 @@ public void removeTimeout(Member member, String reason, Member removedBy, Messag
189187
public void ban(User user, String reason, Member bannedBy, MessageChannel channel, boolean quiet) {
190188
MessageEmbed banEmbed = buildBanEmbed(user, bannedBy, reason);
191189
bannedBy.getGuild().ban(user, BAN_DELETE_DAYS, reason).queue(s -> {
192-
new UserNotificationService(user).sendDirectMessageNotification(banEmbed);
193-
new GuildNotificationService(bannedBy.getGuild()).sendLogChannelNotification(banEmbed);
190+
NotificationService.withUser(user).sendDirectMessage(c -> c.sendMessageEmbeds(banEmbed));
191+
NotificationService.withGuild(bannedBy.getGuild()).sendToModerationLog(c -> c.sendMessageEmbeds(banEmbed));
194192
if (!quiet) channel.sendMessageEmbeds(banEmbed).queue();
195193
}, ExceptionLogger::capture);
196194
}
@@ -235,8 +233,8 @@ private boolean isBanned(@NotNull Guild guild, long userId) {
235233
public void kick(User user, String reason, Member kickedBy, MessageChannel channel, boolean quiet) {
236234
MessageEmbed kickEmbed = buildKickEmbed(user, kickedBy, reason);
237235
kickedBy.getGuild().kick(user).queue(s -> {
238-
new UserNotificationService(user).sendDirectMessageNotification(kickEmbed);
239-
new GuildNotificationService(kickedBy.getGuild()).sendLogChannelNotification(kickEmbed);
236+
NotificationService.withUser(user).sendDirectMessage(c -> c.sendMessageEmbeds(kickEmbed));
237+
NotificationService.withGuild(kickedBy.getGuild()).sendToModerationLog(c -> c.sendMessageEmbeds(kickEmbed));
240238
if (!quiet) channel.sendMessageEmbeds(kickEmbed).queue();
241239
}, ExceptionLogger::capture);
242240
}

src/main/java/net/javadiscord/javabot/systems/moderation/server_lock/ServerLockManager.java

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,11 @@
1010
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
1111
import net.dv8tion.jda.api.hooks.ListenerAdapter;
1212
import net.javadiscord.javabot.Bot;
13+
import net.javadiscord.javabot.systems.notification.GuildNotificationService;
14+
import net.javadiscord.javabot.systems.notification.NotificationService;
1315
import net.javadiscord.javabot.util.Constants;
1416
import net.javadiscord.javabot.data.config.GuildConfig;
1517
import net.javadiscord.javabot.data.config.guild.ServerLockConfig;
16-
import net.javadiscord.javabot.systems.notification.GuildNotificationService;
1718
import net.javadiscord.javabot.util.Responses;
1819
import net.javadiscord.javabot.util.TimeUtils;
1920
import org.jetbrains.annotations.NotNull;
@@ -193,7 +194,7 @@ private void rejectUserDuringRaid(@NotNull GuildMemberJoinEvent event) {
193194
c.sendMessage(Constants.INVITE_URL).setEmbeds(buildServerLockEmbed(event.getGuild())).queue(msg ->
194195
event.getMember().kick().queue()));
195196
String diff = new TimeUtils().formatDurationToNow(event.getMember().getTimeCreated());
196-
new GuildNotificationService(event.getGuild()).sendLogChannelNotification("**%s** (%s old) tried to join this server.", event.getMember().getUser().getAsTag(), diff);
197+
NotificationService.withGuild(event.getGuild()).sendToModerationLog(c -> c.sendMessageFormat("**%s** (%s old) tried to join this server.", event.getMember().getUser().getAsTag(), diff));
197198
}
198199

199200
/**
@@ -210,7 +211,7 @@ public void lockServer(Guild guild, @NotNull Collection<Member> potentialRaiders
210211
c.sendMessage(Constants.INVITE_URL).setEmbeds(buildServerLockEmbed(guild)).queue(msg -> {
211212
member.kick().queue(
212213
success -> {},
213-
error -> new GuildNotificationService(guild).sendLogChannelNotification("Could not kick member %s%n> `%s`", member.getUser().getAsTag(), error.getMessage()));
214+
error -> NotificationService.withGuild(guild).sendToModerationLog(m -> m.sendMessageFormat("Could not kick member %s%n> `%s`", member.getUser().getAsTag(), error.getMessage())));
214215
});
215216
});
216217
}
@@ -228,19 +229,19 @@ public void lockServer(Guild guild, @NotNull Collection<Member> potentialRaiders
228229
GuildConfig config = Bot.getConfig().get(guild);
229230
config.getServerLockConfig().setLocked("true");
230231
Bot.getConfig().get(guild).flush();
231-
GuildNotificationService notification = new GuildNotificationService(guild);
232+
GuildNotificationService notification = NotificationService.withGuild(guild);
232233
if (lockedBy == null) {
233-
notification.sendLogChannelNotification("""
234+
notification.sendToModerationLog(c -> c.sendMessageFormat("""
234235
**Server Locked** %s
235236
The automated locking system has detected that the following %d users may be part of a raid:
236237
%s
237238
""",
238239
config.getModerationConfig().getStaffRole().getAsMention(),
239240
potentialRaiders.size(),
240241
membersString
241-
);
242+
));
242243
} else {
243-
notification.sendLogChannelNotification("Server locked by " + lockedBy.getAsMention());
244+
notification.sendToModerationLog(c -> c.sendMessage("Server locked by " + lockedBy.getAsMention()));
244245
}
245246
}
246247

@@ -255,11 +256,11 @@ public void unlockServer(Guild guild, @Nullable User unlockedby) {
255256
config.setLocked("false");
256257
Bot.getConfig().get(guild).flush();
257258
guildMemberQueues.clear();
258-
GuildNotificationService notification = new GuildNotificationService(guild);
259+
GuildNotificationService notification = NotificationService.withGuild(guild);
259260
if (unlockedby == null) {
260-
notification.sendLogChannelNotification("Server unlocked automatically.");
261+
notification.sendToModerationLog(c -> c.sendMessage("Server unlocked automatically."));
261262
} else {
262-
notification.sendLogChannelNotification("Server unlocked by " + unlockedby.getAsMention());
263+
notification.sendToModerationLog(c -> c.sendMessage("Server unlocked by " + unlockedby.getAsMention()));
263264
}
264265
}
265266
}
Lines changed: 24 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,50 @@
11
package net.javadiscord.javabot.systems.notification;
22

3+
import lombok.AccessLevel;
4+
import lombok.RequiredArgsConstructor;
35
import lombok.extern.slf4j.Slf4j;
46
import net.dv8tion.jda.api.entities.Guild;
5-
import net.dv8tion.jda.api.entities.MessageEmbed;
7+
import net.dv8tion.jda.api.entities.MessageChannel;
8+
import net.dv8tion.jda.api.requests.restaction.MessageAction;
69
import net.javadiscord.javabot.Bot;
7-
import net.javadiscord.javabot.data.config.GuildConfig;
10+
import org.jetbrains.annotations.NotNull;
11+
12+
import java.util.function.Function;
813

914
/**
10-
* Sends notifications within a single {@link Guild}.
15+
* Handles all sorts of guild notifications.
1116
*/
1217
@Slf4j
13-
public final class GuildNotificationService extends NotificationService {
18+
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
19+
public final class GuildNotificationService extends NotificationService.MessageChannelNotification {
1420

1521
private final Guild guild;
16-
private final GuildConfig config;
17-
18-
public GuildNotificationService(Guild guild) {
19-
this.guild = guild;
20-
this.config = Bot.getConfig().get(guild);
21-
}
22-
23-
/**
24-
* Sends a {@link MessageEmbed} to the Guild's log channel.
25-
*
26-
* @param embed The {@link MessageEmbed} to send.
27-
*/
28-
public void sendLogChannelNotification(MessageEmbed embed) {
29-
if (config.getModerationConfig().getLogChannel() == null) {
30-
log.warn("Could not find Log Channel for Guild {}", guild.getName());
31-
return;
32-
}
33-
this.sendMessageChannelNotification(config.getModerationConfig().getLogChannel(), embed);
34-
}
3522

3623
/**
37-
* Sends a simple Message to the Guild's log channel.
24+
* Sends a notification to the log channel.
3825
*
39-
* @param string The message that should be sent.
40-
* @param args Optional args for formatting.
26+
* @param function The {@link Function} to use which MUST return a {@link MessageAction}.
4127
*/
42-
public void sendLogChannelNotification(String string, Object... args) {
43-
if (config.getModerationConfig().getLogChannel() == null) {
44-
log.warn("Could not find Log Channel for Guild {}", guild.getName());
28+
public void sendToModerationLog(@NotNull Function<MessageChannel, MessageAction> function) {
29+
MessageChannel channel = Bot.getConfig().get(guild).getModerationConfig().getLogChannel();
30+
if (channel == null) {
31+
log.error("Could not send message to LogChannel in guild " + guild.getId());
4532
return;
4633
}
47-
this.sendMessageChannelNotification(config.getModerationConfig().getLogChannel(), string, args);
34+
send(channel, function);
4835
}
4936

5037
/**
51-
* Sends a {@link MessageEmbed} to the Guild's message log channel.
38+
* Sends a notification to the message cache log channel.
5239
*
53-
* @param embed The {@link MessageEmbed} to send.
40+
* @param function The {@link Function} to use which MUST return a {@link MessageAction}.
5441
*/
55-
public void sendMessageLogChannelNotification(MessageEmbed embed) {
56-
if (config.getMessageCacheConfig().getMessageCacheLogChannel() == null) {
57-
log.warn("Could not find Message Log Channel for Guild {}", guild.getName());
42+
public void sendToMessageLog(@NotNull Function<MessageChannel, MessageAction> function) {
43+
MessageChannel channel = Bot.getConfig().get(guild).getMessageCacheConfig().getMessageCacheLogChannel();
44+
if (channel == null) {
45+
log.error("Could not find MessageCacheLogChannel in guild " + guild.getId());
5846
return;
5947
}
60-
this.sendMessageChannelNotification(config.getMessageCacheConfig().getMessageCacheLogChannel(), embed);
48+
send(channel, function);
6149
}
6250
}
Lines changed: 42 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,59 @@
11
package net.javadiscord.javabot.systems.notification;
22

33
import lombok.extern.slf4j.Slf4j;
4+
import net.dv8tion.jda.api.entities.Guild;
45
import net.dv8tion.jda.api.entities.MessageChannel;
5-
import net.dv8tion.jda.api.entities.MessageEmbed;
66
import net.dv8tion.jda.api.entities.User;
7+
import net.dv8tion.jda.api.requests.restaction.MessageAction;
8+
import net.javadiscord.javabot.util.ExceptionLogger;
9+
import org.jetbrains.annotations.Contract;
10+
import org.jetbrains.annotations.NotNull;
711

12+
import java.util.function.Function;
813

914
/**
10-
* Abstract class used for sending Notifications to Discord Users and Channels.
15+
* Handles all types of guild & user notifications.
1116
*/
12-
@Slf4j
13-
public abstract class NotificationService {
14-
void sendDirectMessageNotification(User user, MessageEmbed message) {
15-
user.openPrivateChannel().queue(
16-
channel -> sendMessageChannelNotification(channel, message),
17-
error -> log.warn("Could not send private Notification to User " + user.getAsTag())
18-
);
17+
public final class NotificationService {
18+
private NotificationService() {
1919
}
2020

21-
void sendDirectMessageNotification(User user, String s, Object... args) {
22-
user.openPrivateChannel().queue(
23-
channel -> sendMessageChannelNotification(channel, s, args),
24-
error -> log.warn("Could not send private Notification to User " + user.getAsTag())
25-
);
21+
@Contract("_ -> new")
22+
public static @NotNull GuildNotificationService withGuild(Guild guild) {
23+
return new GuildNotificationService(guild);
2624
}
2725

28-
void sendMessageChannelNotification(MessageChannel channel, MessageEmbed message) {
29-
channel.sendMessageEmbeds(message).queue(s -> {}, e -> log.warn("Could not send embed to channel " + channel.getName()));
26+
@Contract("_ -> new")
27+
public static @NotNull UserNotificationService withUser(User user) {
28+
return new UserNotificationService(user);
3029
}
3130

32-
void sendMessageChannelNotification(MessageChannel channel, String s, Object... args) {
33-
channel.sendMessageFormat(s, args).queue(success -> {}, e -> log.warn("Could not send message to channel " + channel.getName()));
31+
public static @NotNull QOTWGuildNotificationService withQOTW(Guild guild) {
32+
return new QOTWGuildNotificationService(guild);
33+
}
34+
35+
public static @NotNull QOTWNotificationService withQOTW(Guild guild, User user) {
36+
return new QOTWNotificationService(user, guild);
37+
}
38+
39+
/**
40+
* Abstract class which streamlines the logic of sending messages to a {@link MessageChannel}.
41+
*/
42+
@Slf4j
43+
abstract static class MessageChannelNotification {
44+
/**
45+
* Sends a single message to the specified {@link MessageChannel} using the
46+
* specified {@link Function}.
47+
*
48+
* @param channel The target {@link MessageChannel}.
49+
* @param function The {@link Function} which is used in order to send the message.
50+
*/
51+
protected void send(MessageChannel channel, @NotNull Function<MessageChannel, MessageAction> function) {
52+
function.apply(channel).queue(s -> {
53+
}, err -> {
54+
ExceptionLogger.capture(err, getClass().getSimpleName());
55+
log.error("Could not send message to channel \" " + channel.getName() + "\": ", err);
56+
});
57+
}
3458
}
3559
}

0 commit comments

Comments
 (0)