commit d2f4cf2ac42d7c7d0bd5e4453e17d5c5c21f6467 parent 5e86942bde5a0eaa01d6fa09a70d368839ef1c7c Author: Wim Dupont <wim@wimdupont.com> Date: Sat, 1 Apr 2023 19:52:16 +0200 removed pvm discordnames to use discordid instead Diffstat:
14 files changed, 106 insertions(+), 123 deletions(-)
diff --git a/src/main/java/com/wimdupont/sxcybot/SxcyBotApplication.java b/src/main/java/com/wimdupont/sxcybot/SxcyBotApplication.java @@ -84,7 +84,6 @@ public class SxcyBotApplication implements CommandLineRunner { jda.awaitReady(); LOGGER.debug("Jda " + jda + " ready"); channelDetailService.setJda(jda); - pvMRoleResolver.updatePvMRoleDiscordNames(); processArgs(jda, args); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/DeletePvmListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/DeletePvmListener.java @@ -8,6 +8,7 @@ import com.wimdupont.sxcybot.services.guild.pvmrole.PvmKcSnapshotService; import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleUserService; import com.wimdupont.sxcybot.util.JdaUtil; import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; import org.springframework.stereotype.Component; @@ -33,15 +34,20 @@ public class DeletePvmListener implements PrivateListener { privateChannel.sendMessage("Type the discord name of the user you want to delete.").queue(); eventWaiterUtil.waitForPrivateChannelEvent(discordNameReceiver -> { String discordName = discordNameReceiver.getMessage().getContentRaw(); - try { - PvmRoleUser pvmRoleUser = pvmRoleUserService.findByDiscordName(discordName); - pvmKcSnapshotService.deleteAll(pvmKcSnapshotService.findAllByPvmRoleUser(pvmRoleUser)); - pvmRoleUserService.delete(pvmRoleUser); - privateChannel.sendMessage(String.format("%s has been succesfully deleted.", pvmRoleUser)).queue(); - event.getChannel().sendMessage(String.format("PvM competitor %s has been deleted by %s", discordName, JdaUtil.getUser(event))).queue(); - } catch (EntityNotFoundException e) { - privateChannel.sendMessage(e.getMessage()).queue(); - } + event.getGuild().loadMembers().onSuccess(members -> { + try { + var userId = JdaUtil.getUserByName(members, discordName) + .map(User::getId) + .orElseThrow(() -> new EntityNotFoundException(String.format("No discord user found with name: %s", discordName))); + PvmRoleUser pvmRoleUser = pvmRoleUserService.findByDiscordId(userId); + pvmKcSnapshotService.deleteAll(pvmKcSnapshotService.findAllByPvmRoleUser(pvmRoleUser)); + pvmRoleUserService.delete(pvmRoleUser); + privateChannel.sendMessage(String.format("%s has been succesfully deleted.", pvmRoleUser)).queue(); + event.getChannel().sendMessage(String.format("PvM competitor %s has been deleted by %s", discordName, JdaUtil.getUser(event))).queue(); + } catch (EntityNotFoundException e) { + privateChannel.sendMessage(e.getMessage()).queue(); + } + }); }, privateMessageReceivedEvent, privateChannel); } } diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/UpdatePvmListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/UpdatePvmListener.java @@ -10,6 +10,7 @@ import com.wimdupont.sxcybot.util.Constants.Commands; import com.wimdupont.sxcybot.util.JdaUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; import org.springframework.dao.DataIntegrityViolationException; @@ -40,40 +41,45 @@ public class UpdatePvmListener implements PrivateListener { embedBuilder.clearFields(); eventWaiterUtil.waitForPrivateChannelEvent(discordNameReceiver -> { String discordName = discordNameReceiver.getMessage().getContentRaw(); - try { - PvmRoleUser pvmRoleUserToUpdate = pvmRoleUserService.findByDiscordName(discordName); - embedBuilder.addField("Confirm by typing ``yes or y``.", - String.format("Is " + System.lineSeparator() + "Discord: %s | RSN: %s " + System.lineSeparator() + "the correct member?" - , pvmRoleUserToUpdate.getDiscordName(), pvmRoleUserToUpdate.getRsn()), false); - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clearFields(); - eventWaiterUtil.waitForPrivateChannelEvent(memberVerifyReceiver -> { - String verifyMessage = memberVerifyReceiver.getMessage().getContentRaw(); - if ("y".equalsIgnoreCase(verifyMessage) || "yes".equalsIgnoreCase(verifyMessage)) { - embedBuilder.addField("Type the new RSN for the update.", "", false); - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clearFields(); - eventWaiterUtil.waitForPrivateChannelEvent(newRsnReceiver -> { - String newRsn = newRsnReceiver.getMessage().getContentRaw(); - pvmRoleUserToUpdate.setRsn(newRsn); - pvmRoleUserToUpdate.setLastModifiedBy(JdaUtil.getName(event).orElse(null)); - try { - PvmRoleUser savedPvmRoleUser = pvmRoleUserService.save(pvmRoleUserToUpdate); - newRsnReceiver.getChannel().sendMessage(savedPvmRoleUser + " edited").queue(); - event.getChannel().sendMessage(String.format("RSN for PvM competitor %s has been changed to %s by %s", - discordName, newRsn, JdaUtil.getUser(event))).queue(); - } catch (DataIntegrityViolationException e) { - if (e.getMessage() != null) - privateChannel.sendMessage(e.getMessage()).queue(); - } - }, privateMessageReceivedEvent, privateChannel); - } else { - privateChannel.sendMessage(String.format("You can check all competitors with the \"%s\" command.", Commands.COMMAND_PREFIX + Command.PVMLIST.name().toLowerCase())).queue(); - } - }, privateMessageReceivedEvent, privateChannel); - } catch (EntityNotFoundException e) { - privateChannel.sendMessage(e.getMessage()).queue(); - } + event.getGuild().loadMembers().onSuccess(members -> { + try { + var userId = JdaUtil.getUserByName(members, discordName) + .map(User::getId) + .orElseThrow(() -> new EntityNotFoundException(String.format("No discord user found with name: %s", discordName))); + PvmRoleUser pvmRoleUserToUpdate = pvmRoleUserService.findByDiscordId(userId); + embedBuilder.addField("Confirm by typing ``yes or y``.", + String.format("Is " + System.lineSeparator() + "Discord: %s | RSN: %s " + System.lineSeparator() + "the correct member?" + , JdaUtil.getUserByName(members, discordName).orElse(null), pvmRoleUserToUpdate.getRsn()), false); + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clearFields(); + eventWaiterUtil.waitForPrivateChannelEvent(memberVerifyReceiver -> { + String verifyMessage = memberVerifyReceiver.getMessage().getContentRaw(); + if ("y".equalsIgnoreCase(verifyMessage) || "yes".equalsIgnoreCase(verifyMessage)) { + embedBuilder.addField("Type the new RSN for the update.", "", false); + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clearFields(); + eventWaiterUtil.waitForPrivateChannelEvent(newRsnReceiver -> { + String newRsn = newRsnReceiver.getMessage().getContentRaw(); + pvmRoleUserToUpdate.setRsn(newRsn); + pvmRoleUserToUpdate.setLastModifiedBy(JdaUtil.getName(event).orElse(null)); + try { + PvmRoleUser savedPvmRoleUser = pvmRoleUserService.save(pvmRoleUserToUpdate); + newRsnReceiver.getChannel().sendMessage(savedPvmRoleUser + " edited").queue(); + event.getChannel().sendMessage(String.format("RSN for PvM competitor %s has been changed to %s by %s", + discordName, newRsn, JdaUtil.getUser(event))).queue(); + } catch (DataIntegrityViolationException e) { + if (e.getMessage() != null) + privateChannel.sendMessage(e.getMessage()).queue(); + } + }, privateMessageReceivedEvent, privateChannel); + } else { + privateChannel.sendMessage(String.format("You can check all competitors with the \"%s\" command.", Commands.COMMAND_PREFIX + Command.PVMLIST.name().toLowerCase())).queue(); + } + }, privateMessageReceivedEvent, privateChannel); + } catch (EntityNotFoundException e) { + privateChannel.sendMessage(e.getMessage()).queue(); + } + }); }, privateMessageReceivedEvent, privateChannel); } } diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/PvmListListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/PvmListListener.java @@ -26,16 +26,19 @@ public class PvmListListener implements Listener { embedBuilder.setColor(Color.red); embedBuilder.setTitle("List of PvM Role competitors:"); List<PvmRoleUser> pvmRoleUsers = pvmRoleUserService.findAll(); - int i = 1; - for (PvmRoleUser pvmRoleUser : pvmRoleUsers) { - embedBuilder.addField(pvmRoleUser.getDiscordName(), - String.format("RSN: %s", pvmRoleUser.getRsn()), - false); - if (JdaUtil.requiresBuild(embedBuilder, pvmRoleUsers.size(), i)) { - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clear(); + event.getGuild().loadMembers().onSuccess(members -> { + int i = 1; + for (PvmRoleUser pvmRoleUser : pvmRoleUsers) { + embedBuilder.addField(JdaUtil.getNameById(members, pvmRoleUser.getDiscordId()) + .orElse("UNKNOWN"), + String.format("RSN: %s", pvmRoleUser.getRsn()), + true); + if (JdaUtil.requiresBuild(embedBuilder, pvmRoleUsers.size(), i)) { + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clear(); + } + i++; } - i++; - } + }); } } diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/PvmRoleUserRepository.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/PvmRoleUserRepository.java @@ -9,6 +9,5 @@ import java.util.Optional; @Repository public interface PvmRoleUserRepository extends JpaRepository<PvmRoleUser, String> { - Optional<PvmRoleUser> findByDiscordName(String discordName); Optional<PvmRoleUser> findByDiscordId(String discordId); } diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/dao/PvmRoleUser.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/dao/PvmRoleUser.java @@ -19,7 +19,6 @@ public class PvmRoleUser { @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid") private String id; - private String discordName; private String rsn; private String discordId; @CreatedDate @@ -43,7 +42,6 @@ public class PvmRoleUser { private PvmRoleUser(Builder builder) { setId(builder.id); - setDiscordName(builder.discordName); setRsn(builder.rsn); setDiscordId(builder.discordId); setCreatedDate(builder.createdDate); @@ -60,14 +58,6 @@ public class PvmRoleUser { this.id = id; } - public String getDiscordName() { - return discordName; - } - - public void setDiscordName(String discordName) { - this.discordName = discordName; - } - public String getRsn() { return rsn; } @@ -174,7 +164,6 @@ public class PvmRoleUser { public String toString() { return "PvmRoleUser{" + "id='" + id + '\'' + - ", discordName='" + discordName + '\'' + ", rsn='" + rsn + '\'' + ", discordId='" + discordId + '\'' + ", createdDate=" + createdDate + diff --git a/src/main/java/com/wimdupont/sxcybot/services/CleanupScheduler.java b/src/main/java/com/wimdupont/sxcybot/services/CleanupScheduler.java @@ -48,7 +48,7 @@ public class CleanupScheduler { .sorted(Comparator.comparing(PvmKcSnapshot::getCreatedDate).reversed()) .skip(2) .toList(); - LOGGER.info("deleted {} from {}", pvmKcSnapshotList.size(), pvmRoleUser.getDiscordName()); + LOGGER.info("deleted {} from RSN: {}, discordId: {}", pvmKcSnapshotList.size(), pvmRoleUser.getRsn(), pvmRoleUser.getDiscordId()); pvmKcSnapshotService.deleteAll(pvmKcSnapshotList); } } diff --git a/src/main/java/com/wimdupont/sxcybot/services/OsrsMonitoringService.java b/src/main/java/com/wimdupont/sxcybot/services/OsrsMonitoringService.java @@ -75,9 +75,9 @@ public class OsrsMonitoringService { embedBuilder.setColor(Color.red); embedBuilder.setTitle("PvM competitor check"); if (!unfound.isEmpty()) { - embedBuilder.setDescription("No hiscores found for following competitors:"); + embedBuilder.setDescription("No hiscores found for following competitor RSN's:"); unfound.forEach(competitor -> - embedBuilder.addField(competitor.getRsn(), String.format("Discord: %s", competitor.getDiscordName()), true)); + embedBuilder.addField(competitor.getRsn(), "", true)); } else { embedBuilder.setDescription("All PvM role competitors have been found in the hiscores."); } diff --git a/src/main/java/com/wimdupont/sxcybot/services/PvMRoleResolver.java b/src/main/java/com/wimdupont/sxcybot/services/PvMRoleResolver.java @@ -8,9 +8,7 @@ import com.wimdupont.sxcybot.services.guild.ChannelDetailService; import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleAssignerService; import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleSnapshotComparatorService; import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleUserService; -import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.entities.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; @@ -49,50 +47,6 @@ public class PvMRoleResolver { resolvePvMRoles(true, null); } - @Scheduled(cron = "${pvm.role.schedule.discord}") - public void updatePvMRoleDiscordNames() { - LOGGER.info("STARTING - Update discord names of PvmRoleUsers."); - channelDetailService.getJda().getGuilds().forEach(guild -> - guild.loadMembers().onSuccess(members -> { - List<PvmRoleUser> pvmRoleUsers = pvmRoleUserService.findAll(); - LOGGER.debug("Updating discordIds"); - pvmRoleUsers.stream() - .filter(f -> f.getDiscordId() == null) - .forEach(roleUser -> { - roleUser.setDiscordId(members.stream().filter(f -> roleUser.getDiscordName().equals(f.getUser().getName()) - || roleUser.getDiscordName().equals(f.getNickname()) - || roleUser.getDiscordName().equals(f.getEffectiveName())) - .findFirst() - .map(Member::getUser) - .map(User::getId) - .stream().findAny().orElse(null)); - pvmRoleUserService.save(roleUser); - LOGGER.debug("Updated discordId: {}", roleUser); - }); - LOGGER.debug("Updating discordNames"); - pvmRoleUsers.stream() - .filter(f -> f.getDiscordId() != null) - .forEach(roleUser -> { - members.stream() - .map(Member::getUser) - .map(User::getId) - .filter(f -> f.equals(roleUser.getDiscordId())) - .findAny() - .ifPresent(discordId -> { - roleUser.setDiscordName(members.stream() - .filter(f -> f.getUser().getId().equals(discordId)) - .findAny() - .map(Member::getEffectiveName) - .orElse(roleUser.getDiscordName())); - pvmRoleUserService.save(roleUser); - LOGGER.debug("Updated discordName: {}", roleUser); - }); - }); - } - )); - LOGGER.info("FINISHED - Update discord names of PvmRoleUsers."); - } - public void resolvePvMRoles(boolean persist, PrivateChannel privateChannel) { Map<PvmRole, LinkedHashMap<PvmRoleUser, BigDecimal>> scoreBoard = new HashMap<>(); for (PvmRole pvmRole : PvmRole.values()) { diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleAssignerService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleAssignerService.java @@ -3,6 +3,7 @@ package com.wimdupont.sxcybot.services.guild.pvmrole; import com.wimdupont.sxcybot.enums.PvmRole; import com.wimdupont.sxcybot.repository.guild.dao.ChannelDetail; import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import com.wimdupont.sxcybot.util.JdaUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; @@ -66,8 +67,12 @@ public class PvmRoleAssignerService { } } else { if (i == winningRank) winningRank++; - embedBuilder.addField(String.format("#%s %s", i, entry.getKey().getRsn()), String.format("%s with a score of %s!", entry.getKey().getDiscordName(), entry.getValue()), false); - textChannel.sendMessage(String.format("No guildmember found for discordname %s. User did not receive any awards.", entry.getKey().getDiscordName())).queue(); + embedBuilder.addField(String.format("#%s %s", i, entry.getKey().getRsn()), String.format("%s with a score of %s!", + JdaUtil.getNameById(memberlist, entry.getKey().getDiscordId()) + .orElse("UNKNOWN"), entry.getValue()), false); + textChannel.sendMessage(String.format("No guildmember found for discordname %s. User did not receive any awards.", + JdaUtil.getNameById(memberlist, entry.getKey().getDiscordId()) + .orElse("UNKNOWN"))).queue(); } i++; } diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleUserService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleUserService.java @@ -3,6 +3,8 @@ package com.wimdupont.sxcybot.services.guild.pvmrole; import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; import com.wimdupont.sxcybot.repository.guild.pvmrole.PvmRoleUserRepository; import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.List; @@ -13,6 +15,7 @@ import static com.wimdupont.sxcybot.util.Constants.Commands.COMMAND_PREFIX; @Service public class PvmRoleUserService { + private static final Logger LOGGER = LoggerFactory.getLogger(PvmRoleUserService.class); private final PvmRoleUserRepository pvmRoleUserRepository; public PvmRoleUserService(PvmRoleUserRepository pvmRoleUserRepository) { @@ -27,10 +30,11 @@ public class PvmRoleUserService { return pvmRoleUserRepository.save(pvmRoleUser); } - public PvmRoleUser findByDiscordName(String discordName) throws EntityNotFoundException { - return pvmRoleUserRepository.findByDiscordName(discordName).orElseThrow(() - -> new EntityNotFoundException(String.format("No discord user found with name %s in the PvM competition.%sYou can check all competitors with the \"%s\" command." - , discordName, System.lineSeparator(), COMMAND_PREFIX + PVMLIST.name().toLowerCase()))); + public PvmRoleUser findByDiscordId(String discordId) throws EntityNotFoundException { + LOGGER.debug("Searching pvmRoleUser by id: {}", discordId); + return pvmRoleUserRepository.findByDiscordId(discordId).orElseThrow(() + -> new EntityNotFoundException(String.format("No such discord user found in the PvM competition.%sYou can check all competitors with the \"%s\" command." + , System.lineSeparator(), COMMAND_PREFIX + PVMLIST.name().toLowerCase()))); } public void delete(PvmRoleUser pvmRoleUser) { diff --git a/src/main/java/com/wimdupont/sxcybot/util/JdaUtil.java b/src/main/java/com/wimdupont/sxcybot/util/JdaUtil.java @@ -7,6 +7,7 @@ import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent; import org.springframework.stereotype.Component; +import java.util.List; import java.util.Optional; @Component @@ -27,10 +28,26 @@ public class JdaUtil { .map(User::getName); } + public static Optional<String> getNameById(List<Member> members, String discordId) { + return members.stream() + .filter(f -> f.getUser().getId().equals(discordId)) + .findAny() + .map(Member::getEffectiveName); + } + public static User getUser(MessageReceivedEvent event) { return event.getMember() != null ? event.getMember().getUser() : null; } + public static Optional<User> getUserByName(List<Member> members, String discordName) { + return members.stream() + .filter(member -> member.getEffectiveName().equalsIgnoreCase(discordName) + || (member.getNickname() != null && member.getNickname().equalsIgnoreCase(discordName)) + || member.getUser().getName().equalsIgnoreCase(discordName)) + .findAny() + .map(Member::getUser); + } + public static boolean requiresBuild(EmbedBuilder embedBuilder, int size, int count) { return (embedBuilder.length() > 5000 || embedBuilder.getFields().size() == 25 || size == count); } diff --git a/src/main/resources/db/migration/V1_12__remove_discordname_from_pvmroleuser.sql b/src/main/resources/db/migration/V1_12__remove_discordname_from_pvmroleuser.sql @@ -0,0 +1,2 @@ +ALTER TABLE pvm_role_user MODIFY discord_id VARCHAR(30) UNIQUE NOT NULL; +ALTER TABLE pvm_role_user DROP COLUMN IF EXISTS discord_name; diff --git a/src/main/resources/releasenotes.csv b/src/main/resources/releasenotes.csv @@ -1,2 +1 @@ -Discord names of PvM Competitors are now updated daily;Discord ID's are now saved alongside discord names for PvM competitors. These ID's are used to update the saved discord names to prevent issues in case of name changes. Names will probably be removed in the future to do all searches based on these ID's. -Improved sb-pvmlist readability;Removed the hidden texts containing auditing info to make it more readable. +Discord names of PvM Competitors are removed;This is a follow-up on the previous update to always search PvM competitors on their unique discord ID instead of discord name. This way it is unaffected by namechanges.