From 24d21d14f282c05f4bcc7a42edb2ba4582a3f130 Mon Sep 17 00:00:00 2001 From: zBinFinn Date: Thu, 2 Apr 2026 23:21:50 +0200 Subject: [PATCH 1/3] feat: make vip star roles lazily created --- .../helpbot/sys/tasks/impl/VIPStarTask.java | 18 ++++++-- .../helpbot/sys/vip/VIPRoleHandler.java | 46 ++++++++----------- 2 files changed, 35 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java b/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java index 93207b64..f146c850 100644 --- a/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java +++ b/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java @@ -28,24 +28,36 @@ public void run() { Guild guild = HelpBotInstance.getJda().getGuildById(HelpBotInstance.DF_GUILD); Set vipIds = VIPRoleHandler.retrieveVIPs(); - guild.loadMembers((member) -> { + guild.loadMembers(member -> { Role role = VIPRoleHandler.getRole(member.getColorRaw()); if (role == null) { return; } + if (vipIds.contains(member.getIdLong()) && !member.getRoles().contains(role)) { guild.addRoleToMember(member, role) .reason("User has VIP Pass") .queue(); return; } + if (!vipIds.contains(member.getIdLong()) && member.getRoles().contains(role)) { guild.removeRoleFromMember(member, role) .reason("User's VIP Pass has expired") .queue(); } }); - + + for (Role role : guild.getRoles()) { + if (!VIPRoleHandler.isVipRole(role)) { + continue; + } + + if (guild.getMembersWithRoles(role).isEmpty()) { + role.delete() + .reason("Noone with this vip role is currently on the discord") + .queue(); + } + } } - } diff --git a/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java b/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java index 2743407f..c1d53cd7 100644 --- a/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java +++ b/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java @@ -28,30 +28,6 @@ public class VIPRoleHandler { static { try { cacheJson(); - - Guild guild = HelpBotInstance.getJda().getGuildById(HelpBotInstance.DF_GUILD); - for (Role role : guild.getRoles()) { - int color = role.getColorRaw(); - if (color == Role.DEFAULT_COLOR_RAW) { - continue; - } - if (role.getIcon() != null) { - continue; - } - if (!COLOR_ROLE_MAP.containsKey(color)) { - // Create the coloured star and register it on discord. - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ImageIO.write(StarUtil.create(new Color(color)), "png", baos); - baos.flush(); - role = guild.createRole() - .setName(ROLE_NAME) - .setIcon(Icon.from(baos.toByteArray())) - .setPermissions(0L) - .complete(); - COLOR_ROLE_MAP.put(color, role.getIdLong()); - } - } - save(); } catch (IOException e) { e.printStackTrace(); } @@ -105,10 +81,28 @@ public static Role getRole(int color) { } Guild guild = HelpBotInstance.getJda().getGuildById(HelpBotInstance.DF_GUILD); if (!COLOR_ROLE_MAP.containsKey(color)) { - return null; + try { + // Create the coloured star and register it on discord. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ImageIO.write(StarUtil.create(new Color(color)), "png", baos); + baos.flush(); + Role role = guild.createRole() + .setName(ROLE_NAME) + .setIcon(Icon.from(baos.toByteArray())) + .setPermissions(0L) + .complete(); + COLOR_ROLE_MAP.put(color, role.getIdLong()); + save(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } } return guild.getRoleById(COLOR_ROLE_MAP.get(color)); } - + + public static boolean isVipRole(Role role) { + return COLOR_ROLE_MAP.containsValue(role.getIdLong()); + } } From 0a642b957671b025c9229ff784ed2d2a5daffda0 Mon Sep 17 00:00:00 2001 From: zBinFinn Date: Thu, 2 Apr 2026 23:28:38 +0200 Subject: [PATCH 2/3] fix: remove it from the map aswell --- .../helpbot/sys/tasks/impl/VIPStarTask.java | 4 +--- .../helpbot/sys/vip/VIPRoleHandler.java | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java b/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java index f146c850..e672edc5 100644 --- a/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java +++ b/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java @@ -54,9 +54,7 @@ public void run() { } if (guild.getMembersWithRoles(role).isEmpty()) { - role.delete() - .reason("Noone with this vip role is currently on the discord") - .queue(); + VIPRoleHandler.deleteRole(role); } } } diff --git a/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java b/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java index c1d53cd7..b611c8aa 100644 --- a/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java +++ b/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java @@ -4,11 +4,13 @@ import com.diamondfire.helpbot.sys.database.impl.DatabaseQuery; import com.diamondfire.helpbot.sys.database.impl.queries.BasicQuery; import com.diamondfire.helpbot.sys.externalfile.ExternalFiles; +import com.diamondfire.helpbot.sys.tasks.TaskRegistry; import com.diamondfire.helpbot.util.StarUtil; import com.google.gson.*; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Icon; import net.dv8tion.jda.api.entities.Role; +import okhttp3.internal.concurrent.Task; import javax.imageio.ImageIO; import java.awt.*; @@ -105,4 +107,17 @@ public static Role getRole(int color) { public static boolean isVipRole(Role role) { return COLOR_ROLE_MAP.containsValue(role.getIdLong()); } + + public static void deleteRole(Role role) { + COLOR_ROLE_MAP.values().removeIf(id -> id == role.getIdLong()); + role.delete() + .reason("Noone with this vip role is currently on the discord") + .queue(); + + try { + save(); + } catch (IOException e) { + e.printStackTrace(); + } + } } From b9df5b73cffd2243fd37afb79931a963435fb929 Mon Sep 17 00:00:00 2001 From: Owen1212055 <23108066+Owen1212055@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:49:36 -0500 Subject: [PATCH 3/3] Fix VIP star roles: only create for VIPs, delete unused after a full member load, keep mapping in the database, adopt existing star roles --- .../sys/externalfile/ExternalFiles.java | 5 - .../helpbot/sys/tasks/impl/VIPStarTask.java | 137 +++++++++--- .../helpbot/sys/vip/VIPRoleHandler.java | 204 +++++++++++------- 3 files changed, 230 insertions(+), 116 deletions(-) diff --git a/src/main/java/com/diamondfire/helpbot/sys/externalfile/ExternalFiles.java b/src/main/java/com/diamondfire/helpbot/sys/externalfile/ExternalFiles.java index 2b4a826c..853f2d4c 100644 --- a/src/main/java/com/diamondfire/helpbot/sys/externalfile/ExternalFiles.java +++ b/src/main/java/com/diamondfire/helpbot/sys/externalfile/ExternalFiles.java @@ -55,11 +55,6 @@ public interface ExternalFiles { .setFileType("png") .buildFile(); - File VIP_ROLES = new ExternalFileBuilder() - .isDirectory(false) - .setName("vip_roles") - .setFileType("json") - .buildFile(); File SAM_QUOTES = new ExternalFileBuilder() .isDirectory(false) diff --git a/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java b/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java index e672edc5..03fa8514 100644 --- a/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java +++ b/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java @@ -3,59 +3,136 @@ import com.diamondfire.helpbot.bot.HelpBotInstance; import com.diamondfire.helpbot.sys.tasks.LoopingTask; import com.diamondfire.helpbot.sys.vip.VIPRoleHandler; -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.entities.*; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.concurrent.TimeUnit; +/** + * Gives every VIP the star role for their name color, takes stars from everyone else, + * and deletes star roles that no VIP needs. + */ public class VIPStarTask implements LoopingTask { - + @Override public long getInitialStart() { return 0; } - + @Override public long getNextLoop() { return TimeUnit.MINUTES.toMillis(30L); } - + + private record Seen(long id, boolean vip, int color, Set stars) { + + } + @Override public void run() { Guild guild = HelpBotInstance.getJda().getGuildById(HelpBotInstance.DF_GUILD); + if (guild == null) { + return; + } + Set vipIds = VIPRoleHandler.retrieveVIPs(); + if (vipIds.isEmpty()) { + // Most likely a failed lookup; acting on it would strip every star. + System.out.println("No VIPs found, skipping VIP star update."); + return; + } + + VIPRoleHandler.syncWithGuild(guild); + + // Only VIPs and members holding a star matter, so only those are kept while members load. + List relevant = Collections.synchronizedList(new ArrayList<>()); + try { + guild.loadMembers(member -> { + Set stars = new HashSet<>(); + for (Role role : member.getRoles()) { + if (VIPRoleHandler.isStarRole(role)) { + stars.add(role.getIdLong()); + } + } + + boolean vip = vipIds.contains(member.getIdLong()); + if (vip || !stars.isEmpty()) { + relevant.add(new Seen(member.getIdLong(), vip, VIPRoleHandler.getNameColor(member), stars)); + } + }).get(); + } catch (Exception e) { + // Without every member, a star in use can't be told apart from an unused one. + System.out.println("Could not load members, skipping VIP star update: " + e); + return; + } + + // The colors VIPs need, and the existing roles that serve them. + Set neededColors = new HashSet<>(); + for (Seen member : relevant) { + if (member.vip() && member.color() != Role.DEFAULT_COLOR_RAW) { + neededColors.add(member.color()); + } + } + + Set keep = new HashSet<>(); + for (int color : neededColors) { + Role role = VIPRoleHandler.getRole(guild, color); + if (role != null) { + keep.add(role.getIdLong()); + } + } - guild.loadMembers(member -> { - Role role = VIPRoleHandler.getRole(member.getColorRaw()); + // Delete unused star roles first: that takes the star from anyone still holding one, and frees room for new roles. + int deleted = 0; + for (Role role : guild.getRoles()) { + if (VIPRoleHandler.isStarRole(role) && !keep.contains(role.getIdLong())) { + VIPRoleHandler.deleteRole(role); + deleted++; + } + } + + int created = 0; + Map roles = new HashMap<>(); + for (int color : neededColors) { + Role role = VIPRoleHandler.getRole(guild, color); if (role == null) { - return; + role = VIPRoleHandler.createRole(guild, color); + if (role != null) { + created++; + } } - - if (vipIds.contains(member.getIdLong()) && !member.getRoles().contains(role)) { - guild.addRoleToMember(member, role) - .reason("User has VIP Pass") - .queue(); - return; + if (role != null) { + roles.put(color, role); } - - if (!vipIds.contains(member.getIdLong()) && member.getRoles().contains(role)) { - guild.removeRoleFromMember(member, role) - .reason("User's VIP Pass has expired") + } + + for (Seen member : relevant) { + UserSnowflake user = UserSnowflake.fromId(member.id()); + Role wanted = member.vip() ? roles.get(member.color()) : null; + + if (wanted != null && !member.stars().contains(wanted.getIdLong())) { + guild.addRoleToMember(user, wanted) + .reason("User has VIP Pass") .queue(); } - }); - - for (Role role : guild.getRoles()) { - if (!VIPRoleHandler.isVipRole(role)) { - continue; - } - - if (guild.getMembersWithRoles(role).isEmpty()) { - VIPRoleHandler.deleteRole(role); + + for (long roleId : member.stars()) { + if (!keep.contains(roleId) || (wanted != null && roleId == wanted.getIdLong())) { + // Deleted above, or the one they should have. + continue; + } + + Role role = guild.getRoleById(roleId); + if (role != null) { + guild.removeRoleFromMember(user, role) + .reason(member.vip() ? "User's name color changed" : "User's VIP Pass has expired") + .queue(); + } } } + + if (deleted > 0 || created > 0) { + System.out.printf("VIP stars: %s VIPs, %s colors, %s roles deleted, %s created%n", vipIds.size(), neededColors.size(), deleted, created); + } } } diff --git a/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java b/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java index b611c8aa..f5ea8458 100644 --- a/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java +++ b/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java @@ -1,123 +1,165 @@ package com.diamondfire.helpbot.sys.vip; -import com.diamondfire.helpbot.bot.HelpBotInstance; +import com.diamondfire.helpbot.sys.database.ConnectionProvider; import com.diamondfire.helpbot.sys.database.impl.DatabaseQuery; import com.diamondfire.helpbot.sys.database.impl.queries.BasicQuery; -import com.diamondfire.helpbot.sys.externalfile.ExternalFiles; -import com.diamondfire.helpbot.sys.tasks.TaskRegistry; import com.diamondfire.helpbot.util.StarUtil; -import com.google.gson.*; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Icon; -import net.dv8tion.jda.api.entities.Role; -import okhttp3.internal.concurrent.Task; +import net.dv8tion.jda.api.entities.*; +import org.jetbrains.annotations.Nullable; import javax.imageio.ImageIO; -import java.awt.*; -import java.io.*; -import java.nio.file.Files; -import java.nio.file.StandardOpenOption; -import java.sql.ResultSet; +import java.awt.Color; +import java.io.ByteArrayOutputStream; +import java.sql.*; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +/** + * Star roles for VIPs: one role per name color, with a star icon in that color. + * Which role belongs to which color is kept in {@code owen.vip_roles}, so it survives redeploys. + */ public class VIPRoleHandler { private static final String ROLE_NAME = "VIP"; - - private static final File FILE = ExternalFiles.VIP_ROLES; - private static final Map COLOR_ROLE_MAP = new HashMap<>(); - static { - try { - cacheJson(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static void cacheJson() throws IOException { - String content = new String(Files.readAllBytes(FILE.toPath())); - - if (content.isEmpty()) { - content = "{}"; - } - - JsonObject obj = JsonParser.parseString(content).getAsJsonObject(); - - for (String key : obj.keySet()) { - long roleId = obj.get(key).getAsLong(); - COLOR_ROLE_MAP.put(Integer.parseInt(key), roleId); - } - } + private static final Map COLOR_ROLE_MAP = new ConcurrentHashMap<>(); - public static void save() throws IOException { - JsonObject json = new JsonObject(); + static { + try (Connection connection = ConnectionProvider.getConnection(); + Statement statement = connection.createStatement()) { + statement.executeUpdate(""" + CREATE TABLE IF NOT EXISTS owen.vip_roles ( + color INT NOT NULL PRIMARY KEY, + role_id BIGINT NOT NULL + )"""); - for (int color : COLOR_ROLE_MAP.keySet()) { - json.addProperty(String.valueOf(color), COLOR_ROLE_MAP.get(color)); + try (ResultSet set = statement.executeQuery("SELECT color, role_id FROM owen.vip_roles")) { + while (set.next()) { + COLOR_ROLE_MAP.put(set.getInt("color"), set.getLong("role_id")); + } + } + } catch (SQLException e) { + e.printStackTrace(); } - - FILE.delete(); - FILE.createNewFile(); - Files.write(FILE.toPath(), json.toString().getBytes(), StandardOpenOption.WRITE); } public static Set retrieveVIPs() { Set vips = new HashSet<>(); new DatabaseQuery() - .query(new BasicQuery("SELECT linked_accounts.discord_id FROM linked_accounts, hypercube.ranks " + + .query(new BasicQuery("SELECT linked_accounts.discord_id FROM linked_accounts, hypercube.ranks " + "WHERE linked_accounts.player_uuid = ranks.uuid AND ranks.vip = 1")) .compile() .run(result -> { - ResultSet set = result.getResult(); - while (set.next()) { + for (ResultSet set : result) { vips.add(set.getLong("discord_id")); } }); return vips; } - public static Role getRole(int color) { - if (color == Role.DEFAULT_COLOR_RAW) { - return null; + /** + * Whether a role is one of the bot's star roles: named "VIP", with an icon and no permissions. + */ + public static boolean isStarRole(Role role) { + return role.getName().equals(ROLE_NAME) + && role.getIcon() != null + && role.getPermissionsRaw() == 0 + && !role.isManaged(); + } + + /** + * A member's name color from their other roles, so a star role never decides it. + */ + public static int getNameColor(Member member) { + for (Role role : member.getRoles()) { + if (!isStarRole(role) && role.getColorRaw() != Role.DEFAULT_COLOR_RAW) { + return role.getColorRaw(); + } } - Guild guild = HelpBotInstance.getJda().getGuildById(HelpBotInstance.DF_GUILD); - if (!COLOR_ROLE_MAP.containsKey(color)) { - try { - // Create the coloured star and register it on discord. - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ImageIO.write(StarUtil.create(new Color(color)), "png", baos); - baos.flush(); - Role role = guild.createRole() - .setName(ROLE_NAME) - .setIcon(Icon.from(baos.toByteArray())) - .setPermissions(0L) - .complete(); - COLOR_ROLE_MAP.put(color, role.getIdLong()); - save(); - } catch (IOException e) { - e.printStackTrace(); - return null; + return Role.DEFAULT_COLOR_RAW; + } + + /** + * Drops mappings to roles that no longer exist, and adopts older star roles that carry their color, + * so they are reused instead of created again. + */ + public static void syncWithGuild(Guild guild) { + COLOR_ROLE_MAP.entrySet().removeIf(entry -> { + if (guild.getRoleById(entry.getValue()) != null) { + return false; + } + forget(entry.getValue()); + return true; + }); + + for (Role role : guild.getRoles()) { + int color = role.getColorRaw(); + if (isStarRole(role) && color != Role.DEFAULT_COLOR_RAW && !COLOR_ROLE_MAP.containsKey(color)) { + remember(color, role.getIdLong()); } } - return guild.getRoleById(COLOR_ROLE_MAP.get(color)); } - - - public static boolean isVipRole(Role role) { - return COLOR_ROLE_MAP.containsValue(role.getIdLong()); + + /** + * @return the existing star role for this color, or null + */ + public static @Nullable Role getRole(Guild guild, int color) { + Long roleId = COLOR_ROLE_MAP.get(color); + return roleId == null ? null : guild.getRoleById(roleId); + } + + /** + * Creates the star role for a color. Blocks, so it must not be called from a JDA callback thread. + * + * @return the new role, or null if it could not be created + */ + public static @Nullable Role createRole(Guild guild, int color) { + try { + ByteArrayOutputStream image = new ByteArrayOutputStream(); + ImageIO.write(StarUtil.create(new Color(color)), "png", image); + Role role = guild.createRole() + .setName(ROLE_NAME) + .setIcon(Icon.from(image.toByteArray())) + .setPermissions(0L) + .reason("A VIP has this name color") + .complete(); + remember(color, role.getIdLong()); + return role; + } catch (Exception e) { + e.printStackTrace(); + return null; + } } - + + /** + * Deletes a star role and forgets it. Blocks until Discord confirms. + */ public static void deleteRole(Role role) { COLOR_ROLE_MAP.values().removeIf(id -> id == role.getIdLong()); - role.delete() - .reason("Noone with this vip role is currently on the discord") - .queue(); - + forget(role.getIdLong()); + try { - save(); - } catch (IOException e) { + role.delete() + .reason("No VIP uses this star role") + .complete(); + } catch (Exception e) { e.printStackTrace(); } } + + private static void remember(int color, long roleId) { + COLOR_ROLE_MAP.put(color, roleId); + new DatabaseQuery() + .query(new BasicQuery("REPLACE INTO owen.vip_roles (color, role_id) VALUES (?, ?)", (statement) -> { + statement.setInt(1, color); + statement.setLong(2, roleId); + })) + .compile(); + } + + private static void forget(long roleId) { + new DatabaseQuery() + .query(new BasicQuery("DELETE FROM owen.vip_roles WHERE role_id = ?", (statement) -> statement.setLong(1, roleId))) + .compile(); + } }