From 2bb80e1db0f77cd08645defd61e3c0328c9a0a05 Mon Sep 17 00:00:00 2001 From: theonlytails Date: Sun, 19 Jun 2022 17:03:11 +0300 Subject: [PATCH 01/15] feat(localization): created the new localization system chore(localization): added localization to the automation, economy, fun, and greeting categories chore(deps): updated deps --- pom.xml | 6 +- .../commands/automation/AutoRoleCommand.java | 30 ++- .../commands/economy/BalanceCommand.java | 12 +- .../commands/economy/CrimeCommand.java | 6 +- .../commands/economy/DepositCommand.java | 16 +- .../commands/economy/PayCommand.java | 21 +- .../commands/economy/RobCommand.java | 8 +- .../commands/economy/WithdrawCommand.java | 12 +- .../commands/economy/WorkCommand.java | 6 +- .../technobot/commands/fun/ActionCommand.java | 47 ++-- .../technobot/commands/fun/CuteCommand.java | 4 +- .../commands/fun/EightBallCommand.java | 28 +-- .../technobot/commands/fun/EmoteCommand.java | 43 ++-- .../technobot/commands/fun/GoogleCommand.java | 6 +- .../technobot/commands/fun/JokeCommand.java | 14 +- .../technobot/commands/fun/MemeCommand.java | 4 +- .../technobot/commands/fun/NsfwCommand.java | 4 +- .../technobot/commands/fun/RedditCommand.java | 4 +- .../commands/fun/SurpriseCommand.java | 4 +- .../commands/greetings/FarewellCommand.java | 6 +- .../commands/greetings/GreetCommand.java | 6 +- .../commands/greetings/GreetingsCommand.java | 42 ++-- .../commands/greetings/JoinDMCommand.java | 6 +- .../java/technobot/data/cache/Config.java | 12 + .../technobot/data/json/EconomyResponses.java | 32 --- .../handlers/economy/EconomyHandler.java | 44 ++-- .../handlers/economy/EconomyLocalization.java | 57 +++-- .../util/localization/Localization.java | 116 ++++++++++ .../util/localization/LocalizationSchema.java | 165 ++++++++++++++ src/main/resources/localization/economy.json | 47 ---- src/main/resources/localization/en_us.json | 213 ++++++++++++++++++ 31 files changed, 741 insertions(+), 280 deletions(-) delete mode 100644 src/main/java/technobot/data/json/EconomyResponses.java create mode 100644 src/main/java/technobot/util/localization/Localization.java create mode 100644 src/main/java/technobot/util/localization/LocalizationSchema.java delete mode 100644 src/main/resources/localization/economy.json create mode 100644 src/main/resources/localization/en_us.json diff --git a/pom.xml b/pom.xml index 054033f..2619855 100644 --- a/pom.xml +++ b/pom.xml @@ -37,13 +37,13 @@ org.mongodb mongo-java-driver - 3.12.10 + 3.12.11 io.github.cdimascio dotenv-java - 2.2.3 + 2.2.4 @@ -61,7 +61,7 @@ com.squareup.okhttp3 okhttp - 4.9.3 + 4.10.0 diff --git a/src/main/java/technobot/commands/automation/AutoRoleCommand.java b/src/main/java/technobot/commands/automation/AutoRoleCommand.java index 93d6bb8..7cda5fb 100644 --- a/src/main/java/technobot/commands/automation/AutoRoleCommand.java +++ b/src/main/java/technobot/commands/automation/AutoRoleCommand.java @@ -17,6 +17,8 @@ import java.util.Set; +import static technobot.util.localization.Localization.get; + /** * Command that sets roles to be given on user join. * @@ -48,27 +50,35 @@ public void execute(SlashCommandInteractionEvent event) { case "add" -> { Role role = event.getOption("role").getAsRole(); if (role.isManaged() || role.isPublicRole() || role.getPosition() >= event.getGuild().getBotRole().getPosition()) { - event.replyEmbeds(EmbedUtils.createError("I cannot give out roles that have a higher position than me!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.automation().autoRole().add().higherLevel()) + )).setEphemeral(true).queue(); return; } if (configHandler.getConfig().getAutoRoles().size() >= 1 && !configHandler.isPremium()) { - event.replyEmbeds(EmbedUtils.createError("You can set multiple auto-roles with premium! For more info, use `/premium`.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.automation().autoRole().add().premium()) + )).setEphemeral(true).queue(); return; } if (configHandler.getConfig().getAutoRoles().size() == MAX_AUTO_ROLES) { - event.replyEmbeds(EmbedUtils.createError("You have hit the maximum number of auto-roles for this guild!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.automation().autoRole().add().maxRolesReached()) + )).setEphemeral(true).queue(); return; } - embed = EmbedUtils.createDefault(EmbedUtils.BLUE_TICK + " The <@&"+role.getId()+"> role will be given to all new members when they join the server."); + embed = EmbedUtils.createDefault(get(s -> s.automation().autoRole().add().roleAdded(), role.getId())); configHandler.addAutoRole(role.getIdLong()); } case "remove" -> { Role role = event.getOption("role").getAsRole(); if (!configHandler.getConfig().getAutoRoles().contains(role.getIdLong())) { - event.replyEmbeds(EmbedUtils.createError("The <@&"+role.getId()+"> role is not set as an auto-role.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.automation().autoRole().remove().roleNotSet(), role.getId()) + )).setEphemeral(true).queue(); return; } - embed = EmbedUtils.createDefault(EmbedUtils.BLUE_X + " The <@&"+role.getId()+"> role will no longer be given to new members when they join the server."); + embed = EmbedUtils.createDefault(get(s -> s.automation().autoRole().remove().roleRemoved(), role.getId())); if (!configHandler.isPremium()) { configHandler.clearAutoRoles(); } else { @@ -79,19 +89,19 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embedBuilder = new EmbedBuilder().setTitle("Auto Roles").setColor(EmbedColor.DEFAULT.color); Set roles = configHandler.getConfig().getAutoRoles(); if (roles == null || roles.isEmpty()) { - embedBuilder.setDescription("Use `/auto-role add ` to set your first auto role!"); + embedBuilder.setDescription(get(s -> s.automation().autoRole().list().noAutoRoles())); } else { int max = configHandler.isPremium() ? MAX_AUTO_ROLES : 1; if (max == 1) { - embedBuilder.appendDescription("Add additional roles with `/premium`\n"); + embedBuilder.appendDescription(get(s -> s.automation().autoRole().list().premium()) + "\n"); } else { - embedBuilder.appendDescription("There are "+roles.size()+" auto roles given to new members:\n"); + embedBuilder.appendDescription(get(s -> s.automation().autoRole().list().roleCount(), roles.size()) + "\n"); } int count = 0; for (long roleID : roles) { if (event.getGuild().getRoleById(roleID) != null) { count++; - embedBuilder.appendDescription("\n**"+count+".** <@&"+roleID+">"); + embedBuilder.appendDescription("\n" + get(s -> s.automation().autoRole().list().role(), count, roleID)); if (count == max) break; } } diff --git a/src/main/java/technobot/commands/economy/BalanceCommand.java b/src/main/java/technobot/commands/economy/BalanceCommand.java index f21928f..903fe01 100644 --- a/src/main/java/technobot/commands/economy/BalanceCommand.java +++ b/src/main/java/technobot/commands/economy/BalanceCommand.java @@ -13,6 +13,10 @@ import technobot.data.cache.Economy; import technobot.handlers.economy.EconomyHandler; import technobot.util.embeds.EmbedColor; +import technobot.util.localization.Localization; +import technobot.util.localization.LocalizationSchema; + +import static technobot.util.localization.Localization.get; /** * Command that shows your current cash and bank balance on the server. @@ -55,10 +59,10 @@ public void execute(SlashCommandInteractionEvent event) { String currency = economyHandler.getCurrency(); EmbedBuilder embed = new EmbedBuilder() .setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()) - .setDescription("Leaderboard Rank: #" + economyHandler.getRank(user.getIdLong())) - .addField("Cash:", currency + " " + EconomyHandler.FORMATTER.format(balance), true) - .addField("Bank:", currency + " " + EconomyHandler.FORMATTER.format(bank), true) - .addField("Total:", currency + " " + EconomyHandler.FORMATTER.format(total), true) + .setDescription(get(s -> s.economy().balance().leaderboardRank(), economyHandler.getRank(user.getIdLong()))) + .addField(get(s -> s.economy().balance().cash()), currency + " " + EconomyHandler.FORMATTER.format(balance), true) + .addField(get(s -> s.economy().balance().bank()), currency + " " + EconomyHandler.FORMATTER.format(bank), true) + .addField(get(s -> s.economy().balance().total()), currency + " " + EconomyHandler.FORMATTER.format(total), true) .setColor(EmbedColor.DEFAULT.color); event.replyEmbeds(embed.build()).queue(); } diff --git a/src/main/java/technobot/commands/economy/CrimeCommand.java b/src/main/java/technobot/commands/economy/CrimeCommand.java index 7eb97ec..8a03820 100644 --- a/src/main/java/technobot/commands/economy/CrimeCommand.java +++ b/src/main/java/technobot/commands/economy/CrimeCommand.java @@ -10,6 +10,8 @@ import technobot.handlers.economy.EconomyReply; import technobot.util.embeds.EmbedColor; +import static technobot.util.localization.Localization.get; + /** * Command that risks losing money for a greater potential reward. * @@ -34,7 +36,7 @@ public void execute(SlashCommandInteractionEvent event) { if (timeout != null && System.currentTimeMillis() < timeout) { // On timeout String timestamp = economyHandler.formatTimeout(timeout); - embed.setDescription(":stopwatch: You can next commit a crime " + timestamp + "."); + embed.setDescription(get(s -> s.economy().crime().timeout(), timestamp)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); } else { @@ -43,7 +45,7 @@ public void execute(SlashCommandInteractionEvent event) { int color = reply.isSuccess() ? EmbedColor.SUCCESS.color : EmbedColor.ERROR.color; embed.setDescription(reply.getResponse()); embed.setColor(color); - embed.setFooter("Reply #" + reply.getId()); + embed.setFooter(get(s -> s.economy().replyId(), reply.getId())); event.replyEmbeds(embed.build()).queue(); } } diff --git a/src/main/java/technobot/commands/economy/DepositCommand.java b/src/main/java/technobot/commands/economy/DepositCommand.java index 41a5f70..1e8c2d3 100644 --- a/src/main/java/technobot/commands/economy/DepositCommand.java +++ b/src/main/java/technobot/commands/economy/DepositCommand.java @@ -14,6 +14,8 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import static technobot.util.localization.Localization.get; + /** * Command that deposits cash into user's bank. * @@ -38,7 +40,7 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()); if (balance <= 0) { // Balance is at 0 - embed.setDescription(EmbedUtils.RED_X + " You don't have any money to deposit!"); + embed.setDescription(get(s -> s.economy().deposit().noMoney())); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -50,8 +52,10 @@ public void execute(SlashCommandInteractionEvent event) { amount = amountOption.getAsLong(); if (amount > balance) { // Amount is higher than balance - String value = currency + " " + EconomyHandler.FORMATTER.format(balance); - embed.setDescription(EmbedUtils.RED_X + " You cannot deposit more than " + value + "!"); + embed.setDescription(get( + s -> s.economy().deposit().notEnough(), + EconomyHandler.FORMATTER.format(balance) + )); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -62,8 +66,10 @@ public void execute(SlashCommandInteractionEvent event) { economyHandler.deposit(user.getIdLong(), amount); // Send embed message - String value = currency + " " + EconomyHandler.FORMATTER.format(amount); - embed.setDescription(EmbedUtils.GREEN_TICK + " Deposited " + value + " to your bank!"); + embed.setDescription(get( + s -> s.economy().deposit().success(), + EconomyHandler.FORMATTER.format(amount) + )); embed.setColor(EmbedColor.SUCCESS.color); event.replyEmbeds(embed.build()).queue(); } diff --git a/src/main/java/technobot/commands/economy/PayCommand.java b/src/main/java/technobot/commands/economy/PayCommand.java index 3283ea1..fac4c91 100644 --- a/src/main/java/technobot/commands/economy/PayCommand.java +++ b/src/main/java/technobot/commands/economy/PayCommand.java @@ -13,6 +13,8 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import static technobot.util.localization.Localization.get; + /** * Command that transfer cash from one user to another. * @@ -36,14 +38,14 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()); if (user.getIdLong() == target.getIdLong()) { // Check for invalid target - embed.setDescription(EmbedUtils.RED_X + " You cannot pay yourself!"); + embed.setDescription(get(s -> s.economy().pay().paySelf())); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; } if (target.isBot()) { // Check if target is a bot - embed.setDescription(EmbedUtils.RED_X + " You cannot pay bots!"); + embed.setDescription(get(s -> s.economy().pay().payBots())); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -51,14 +53,14 @@ public void execute(SlashCommandInteractionEvent event) { long amount = event.getOption("amount").getAsLong(); EconomyHandler economyHandler = GuildData.get(event.getGuild()).economyHandler; - String currency = economyHandler.getCurrency(); // Check that user has necessary funds long balance = economyHandler.getBalance(user.getIdLong()); if (amount > balance) { - String value = currency + " " + EconomyHandler.FORMATTER.format(balance); - String text = "You don't have that much money to give. You currently have " + value + " on hand."; - embed.setDescription(EmbedUtils.RED_X + text); + embed.setDescription(get( + s -> s.economy().pay().notEnough(), + EconomyHandler.FORMATTER.format(balance) + )); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -66,10 +68,13 @@ public void execute(SlashCommandInteractionEvent event) { // Pay target economyHandler.pay(user.getIdLong(), target.getIdLong(), amount); - String value = currency + " " + EconomyHandler.FORMATTER.format(amount); // Send embed message - embed.setDescription(EmbedUtils.GREEN_TICK + " <@" + target.getId() + "> has received your " + value + "."); + embed.setDescription(get( + s -> s.economy().pay().success(), + target.getId(), + EconomyHandler.FORMATTER.format(amount) + )); embed.setColor(EmbedColor.SUCCESS.color); event.replyEmbeds(embed.build()).queue(); } diff --git a/src/main/java/technobot/commands/economy/RobCommand.java b/src/main/java/technobot/commands/economy/RobCommand.java index 8f03edf..cd5e7a5 100644 --- a/src/main/java/technobot/commands/economy/RobCommand.java +++ b/src/main/java/technobot/commands/economy/RobCommand.java @@ -14,6 +14,8 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import static technobot.util.localization.Localization.get; + /** * Command that steals money from another user. * @@ -35,14 +37,14 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()); if (user.getIdLong() == target.getIdLong()) { // Check for invalid target - embed.setDescription(EmbedUtils.RED_X + " You cannot rob yourself!"); + embed.setDescription(get(s -> s.economy().rob().robSelf())); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; } if (target.isBot()) { // Check if target is a bot - embed.setDescription(EmbedUtils.RED_X + " You cannot rob bots, they are too powerful for you!"); + embed.setDescription(get(s -> s.economy().rob().robBots())); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -54,7 +56,7 @@ public void execute(SlashCommandInteractionEvent event) { if (timeout != null && System.currentTimeMillis() < timeout) { // On timeout String timestamp = economyHandler.formatTimeout(timeout); - embed.setDescription(":stopwatch: You can attempt to rob another member " + timestamp + "."); + embed.setDescription(get(s -> s.economy().rob().timeout(), timestamp)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); } else { diff --git a/src/main/java/technobot/commands/economy/WithdrawCommand.java b/src/main/java/technobot/commands/economy/WithdrawCommand.java index d4d082b..0570103 100644 --- a/src/main/java/technobot/commands/economy/WithdrawCommand.java +++ b/src/main/java/technobot/commands/economy/WithdrawCommand.java @@ -12,7 +12,8 @@ import technobot.data.GuildData; import technobot.handlers.economy.EconomyHandler; import technobot.util.embeds.EmbedColor; -import technobot.util.embeds.EmbedUtils; + +import static technobot.util.localization.Localization.get; /** * Command that withdraws cash from the user's bank. @@ -32,13 +33,12 @@ public WithdrawCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { User user = event.getUser(); EconomyHandler economyHandler = GuildData.get(event.getGuild()).economyHandler; - String currency = economyHandler.getCurrency(); long bank = economyHandler.getBank(user.getIdLong()); EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()); if (bank <= 0) { // Bank is at 0 - embed.setDescription(EmbedUtils.RED_X + " You don't have any money in your bank to withdraw!"); + embed.setDescription(get(s -> s.economy().withdraw().noMoney())); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -50,8 +50,7 @@ public void execute(SlashCommandInteractionEvent event) { amount = amountOption.getAsLong(); if (amount > bank) { // Amount is higher than balance - String value = currency + " " + EconomyHandler.FORMATTER.format(bank); - embed.setDescription(EmbedUtils.RED_X + " You cannot withdraw more than " + value + "!"); + embed.setDescription(get(s -> s.economy().withdraw().tooMuch(), bank)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -62,8 +61,7 @@ public void execute(SlashCommandInteractionEvent event) { economyHandler.withdraw(user.getIdLong(), amount); // Send embed message - String value = currency + " " + EconomyHandler.FORMATTER.format(amount); - embed.setDescription(EmbedUtils.GREEN_TICK + " Withdrew " + value + " from your bank!"); + embed.setDescription(get(s -> s.economy().withdraw().success(), amount)); embed.setColor(EmbedColor.SUCCESS.color); event.replyEmbeds(embed.build()).queue(); } diff --git a/src/main/java/technobot/commands/economy/WorkCommand.java b/src/main/java/technobot/commands/economy/WorkCommand.java index 338eca0..d752bc5 100644 --- a/src/main/java/technobot/commands/economy/WorkCommand.java +++ b/src/main/java/technobot/commands/economy/WorkCommand.java @@ -10,6 +10,8 @@ import technobot.handlers.economy.EconomyReply; import technobot.util.embeds.EmbedColor; +import static technobot.util.localization.Localization.get; + /** * Command that adds money to your balance. * @@ -34,7 +36,7 @@ public void execute(SlashCommandInteractionEvent event) { if (timeout != null && System.currentTimeMillis() < timeout) { // On timeout String timestamp = economyHandler.formatTimeout(timeout); - embed.setDescription(":stopwatch: You can next work " + timestamp + "."); + embed.setDescription(get(s -> s.economy().work().timeout(), timestamp)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); } else { @@ -42,7 +44,7 @@ public void execute(SlashCommandInteractionEvent event) { EconomyReply reply = economyHandler.work(user); embed.setDescription(reply.getResponse()); embed.setColor(EmbedColor.SUCCESS.color); - embed.setFooter("Reply #"+reply.getId()); + embed.setFooter(get(s -> s.economy().replyId(), reply.getId())); event.replyEmbeds(embed.build()).queue(); } } diff --git a/src/main/java/technobot/commands/fun/ActionCommand.java b/src/main/java/technobot/commands/fun/ActionCommand.java index 3c3b1ce..a5569fd 100644 --- a/src/main/java/technobot/commands/fun/ActionCommand.java +++ b/src/main/java/technobot/commands/fun/ActionCommand.java @@ -17,6 +17,8 @@ import java.io.IOException; +import static technobot.util.localization.Localization.get; + /** * Command that generates an image to match an emotion with another user * @@ -59,28 +61,27 @@ public void execute(SlashCommandInteractionEvent event) { url += emote; String target = event.getOption("user").getAsUser().getName(); - String text = event.getUser().getName() + " "; - switch (emote) { - case "bite" -> text += "takes a bite out of "+target+"."; - case "brofist" -> text += "and "+target+" brofist!"; - case "cuddle" -> text += "cuddles with "+target+"."; - case "handhold" -> text += "and "+target+" hold hands. How sweet <3"; - case "hug" -> text += "gives "+target+" a big hug!"; - case "kiss" -> text += "kisses "+target+"."; - case "lick" -> text += "licks "+target+"... gross!"; - case "pat" -> text += "gives "+target+" a little pat on the head"; - case "pinch" -> text += "pinches "+target+". Ouch!"; - case "poke" -> text += "gives "+target+" a little poke."; - case "punch" -> text += "punches "+target+" right in the face!"; - case "slap" -> text += "slaps "+target+". They deserved it!"; - case "smack" -> text += "gives "+target+" a smack they will remember."; - case "sorry" -> text += "apologizes to "+target+"."; - case "stare" -> text += "won't stop starting at "+target+"..."; - case "thumbsup" -> text += "gives "+target+" two thumbs up!"; - case "tickle" -> text += "tickles "+target+"."; - case "wave" -> text += "waves at "+target+"."; - case "wink" -> text += "winks at "+target+"."; - } + String text = event.getUser().getName() + " " + switch (emote) { + case "bite" -> get(s -> s.fun().action().bite(), target); + case "brofist" -> get(s -> s.fun().action().brofist(), target); + case "cuddle" -> get(s -> s.fun().action().cuddle(), target); + case "handhold" -> get(s -> s.fun().action().handhold(), target); + case "hug" -> get(s -> s.fun().action().hug(), target); + case "kiss" -> get(s -> s.fun().action().kiss(), target); + case "lick" -> get(s -> s.fun().action().lick(), target); + case "pat" -> get(s -> s.fun().action().pat(), target); + case "pinch" -> get(s -> s.fun().action().pinch(), target); + case "poke" -> get(s -> s.fun().action().poke(), target); + case "punch" -> get(s -> s.fun().action().punch(), target); + case "slap" -> get(s -> s.fun().action().slap(), target); + case "smack" -> get(s -> s.fun().action().smack(), target); + case "sorry" -> get(s -> s.fun().action().sorry(), target); + case "stare" -> get(s -> s.fun().action().stare(), target); + case "thumbsup" -> get(s -> s.fun().action().thumbsup(), target); + case "tickle" -> get(s -> s.fun().action().tickle(), target); + case "wave" -> get(s -> s.fun().action().wave(), target); + case "wink" -> get(s -> s.fun().action().wink(), target); + }; // Asynchronous API call Request request = new Request.Builder().url(url).build(); @@ -88,7 +89,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = "I was unable to fetch that emote!"; + String text = get(s -> s.fun().action().failure()); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); } diff --git a/src/main/java/technobot/commands/fun/CuteCommand.java b/src/main/java/technobot/commands/fun/CuteCommand.java index cafd14a..4e07024 100644 --- a/src/main/java/technobot/commands/fun/CuteCommand.java +++ b/src/main/java/technobot/commands/fun/CuteCommand.java @@ -18,6 +18,8 @@ import java.io.IOException; +import static technobot.util.localization.Localization.get; + /** * Command that generates a cute picture from reddit. * @@ -54,7 +56,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = "I was unable to fetch any cute pictures!"; + String text = get(s -> s.fun().cute().failure()); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } diff --git a/src/main/java/technobot/commands/fun/EightBallCommand.java b/src/main/java/technobot/commands/fun/EightBallCommand.java index b891031..171c516 100644 --- a/src/main/java/technobot/commands/fun/EightBallCommand.java +++ b/src/main/java/technobot/commands/fun/EightBallCommand.java @@ -14,6 +14,8 @@ import java.util.List; import java.util.concurrent.ThreadLocalRandom; +import static technobot.util.localization.Localization.get; + /** * Command that generates a cute picture from reddit. * @@ -21,22 +23,6 @@ */ public class EightBallCommand extends Command { - private static final List responses = Arrays.asList( - "I can tell you certainly, no.", - "I'm not sure but ur def stupid.", - "It is certain.", - "Without a doubt.", - "You may rely on it.", - "As I see it, yes.", - "Most likely.", - "Signs point to yes.", - "Reply hazy try again.", - "Better not tell you now.", - "Hmm imma just let u figure it out.", - "Don't count on it.", - "Outlook not so good.", - "My sources say no."); - public EightBallCommand(TechnoBot bot) { super(bot); this.name = "8ball"; @@ -49,15 +35,19 @@ public EightBallCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { String question = event.getOption("question").getAsString(); if (question.length() > 250) { - event.replyEmbeds(EmbedUtils.createError("The 8ball doesn't like questions longer than 250 characters!")).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.fun().eightBall().tooLong()) + )).queue(); return; } - int index = ThreadLocalRandom.current().nextInt(responses.size()); + String[] responses = get(s -> s.fun().eightBall().responses()); + + int index = ThreadLocalRandom.current().nextInt(responses.length); EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) .setTitle(question) - .setDescription(":8ball: " + responses.get(index)); + .setDescription(":8ball: " + responses[index]); event.replyEmbeds(embed.build()).queue(); } } diff --git a/src/main/java/technobot/commands/fun/EmoteCommand.java b/src/main/java/technobot/commands/fun/EmoteCommand.java index a62063a..eab5ef5 100644 --- a/src/main/java/technobot/commands/fun/EmoteCommand.java +++ b/src/main/java/technobot/commands/fun/EmoteCommand.java @@ -17,6 +17,8 @@ import java.io.IOException; +import static technobot.util.localization.Localization.get; + /** * Command that generates an image to match an emotion. * @@ -56,27 +58,26 @@ public void execute(SlashCommandInteractionEvent event) { String emote = event.getOption("emote").getAsString(); url += emote; - String text = event.getUser().getName() + " "; - switch (emote) { - case "mad" -> text += "doesn't like that."; - case "blush" -> text += "has turned into a tomato."; - case "celebrate" -> text += "is ready to celebrate!"; - case "clap" -> text += "claps excitedly."; - case "confused" -> text += "is really confused."; - case "cry" -> text += "needs a hug..."; - case "dance" -> text += "is dancing!"; - case "facepalm" -> text += "is in disbelief."; - case "happy" -> text += "smiles."; - case "laugh" -> text += "laughs out loud."; - case "pout" -> text += "is in a bad mood."; - case "shrug" -> text += "doesn't care..."; - case "shy" -> text += "is feeling timid."; - case "sigh" -> text += "is disappointed."; - case "slowclap" -> text += "is not amused."; - case "scared" -> text += "fears for their life."; - case "sleep" -> text += "falls into a deep sleep."; - case "yawn" -> text += "is getting very sleepy."; - } + String text = event.getUser().getName() + switch (emote) { + case "mad" -> get(s -> s.fun().emote().mad()); + case "blush" -> get(s -> s.fun().emote().blush()); + case "celebrate" -> get(s -> s.fun().emote().celebrate()); + case "clap" -> get(s -> s.fun().emote().clap()); + case "confused" -> get(s -> s.fun().emote().confused()); + case "cry" -> get(s -> s.fun().emote().cry()); + case "dance" -> get(s -> s.fun().emote().dance()); + case "facepalm" -> get(s -> s.fun().emote().facepalm()); + case "happy" -> get(s -> s.fun().emote().happy()); + case "laugh" -> get(s -> s.fun().emote().laugh()); + case "pout" -> get(s -> s.fun().emote().pout()); + case "shrug" -> get(s -> s.fun().emote().shrug()); + case "shy" -> get(s -> s.fun().emote().shy()); + case "sigh" -> get(s -> s.fun().emote().sigh()); + case "slowclap" -> get(s -> s.fun().emote().slowClap()); + case "scared" -> get(s -> s.fun().emote().scared()); + case "sleep" -> get(s -> s.fun().emote().sleep()); + case "yawn" -> get(s -> s.fun().emote().yawn()); + }; // Asynchronous API call Request request = new Request.Builder().url(url).build(); diff --git a/src/main/java/technobot/commands/fun/GoogleCommand.java b/src/main/java/technobot/commands/fun/GoogleCommand.java index 5d2c775..e8986d9 100644 --- a/src/main/java/technobot/commands/fun/GoogleCommand.java +++ b/src/main/java/technobot/commands/fun/GoogleCommand.java @@ -11,6 +11,8 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; +import static technobot.util.localization.Localization.get; + /** * Command that googles something for the user. * @@ -30,7 +32,9 @@ public GoogleCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { String question = event.getOption("question").getAsString(); if (question.length() > 250) { - event.replyEmbeds(EmbedUtils.createError("google doesn't like questions longer than 250 characters!")).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.fun().google().tooLong()) + )).queue(); return; } String query = URLEncoder.encode(question, StandardCharsets.UTF_8); diff --git a/src/main/java/technobot/commands/fun/JokeCommand.java b/src/main/java/technobot/commands/fun/JokeCommand.java index 0189f0e..4f0cb03 100644 --- a/src/main/java/technobot/commands/fun/JokeCommand.java +++ b/src/main/java/technobot/commands/fun/JokeCommand.java @@ -9,6 +9,8 @@ import java.io.IOException; +import static technobot.util.localization.Localization.get; + /** * Command that generates a joke from a joke API. * @@ -35,7 +37,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = "I was unable to fetch any jokes!"; + String text = get(s -> s.fun().joke().failure()); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } @@ -43,7 +45,7 @@ public void onFailure(Call call, IOException e) { public void onResponse(Call call, final Response response) throws IOException { if (!response.isSuccessful()) throw new IOException(); Joke entity = bot.gson.fromJson(response.body().string(), Joke.class); - event.getHook().sendMessage(entity.joke).queue(); + event.getHook().sendMessage(entity.joke()).queue(); } }); } @@ -52,12 +54,6 @@ public void onResponse(Call call, final Response response) throws IOException { * Represents a joke retrieved from the joke api. * Used by OkHttp and Gson to convert JSON to java code. */ - private class Joke { - - public String joke; - - public Joke(String joke) { - this.joke = joke; - } + private record Joke(String joke) { } } diff --git a/src/main/java/technobot/commands/fun/MemeCommand.java b/src/main/java/technobot/commands/fun/MemeCommand.java index 5201ed7..2c78a9e 100644 --- a/src/main/java/technobot/commands/fun/MemeCommand.java +++ b/src/main/java/technobot/commands/fun/MemeCommand.java @@ -16,6 +16,8 @@ import java.io.IOException; import java.util.concurrent.ThreadLocalRandom; +import static technobot.util.localization.Localization.get; + /** * Command that generates a meme from the r/dankmemes subreddit. * @@ -55,7 +57,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = "I was unable to fetch any memes!"; + String text = get(s -> s.fun().meme().failure()); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } diff --git a/src/main/java/technobot/commands/fun/NsfwCommand.java b/src/main/java/technobot/commands/fun/NsfwCommand.java index eff5744..ddb5cab 100644 --- a/src/main/java/technobot/commands/fun/NsfwCommand.java +++ b/src/main/java/technobot/commands/fun/NsfwCommand.java @@ -18,6 +18,8 @@ import java.io.IOException; +import static technobot.util.localization.Localization.get; + /** * Command that generates a nsfw picture from reddit. * @@ -58,7 +60,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = "I was unable to fetch any nsfw pictures!"; + String text = get(s -> s.fun().nsfw().failure()); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } diff --git a/src/main/java/technobot/commands/fun/RedditCommand.java b/src/main/java/technobot/commands/fun/RedditCommand.java index b3add6a..ea37736 100644 --- a/src/main/java/technobot/commands/fun/RedditCommand.java +++ b/src/main/java/technobot/commands/fun/RedditCommand.java @@ -17,6 +17,8 @@ import java.io.IOException; +import static technobot.util.localization.Localization.get; + /** * Command that generates a post from various subreddits. * @@ -47,7 +49,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = "I was unable to fetch any posts from that subreddit!"; + String text = get(s -> s.fun().reddit().failure()); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } diff --git a/src/main/java/technobot/commands/fun/SurpriseCommand.java b/src/main/java/technobot/commands/fun/SurpriseCommand.java index 8159372..8d74299 100644 --- a/src/main/java/technobot/commands/fun/SurpriseCommand.java +++ b/src/main/java/technobot/commands/fun/SurpriseCommand.java @@ -14,6 +14,8 @@ import java.util.List; import java.util.concurrent.ThreadLocalRandom; +import static technobot.util.localization.Localization.get; + /** * Command that generates a link from uselessweb. * @@ -39,7 +41,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = "I was unable to fetch any surprises!"; + String text = get(s -> s.fun().surprise().failure()); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } diff --git a/src/main/java/technobot/commands/greetings/FarewellCommand.java b/src/main/java/technobot/commands/greetings/FarewellCommand.java index d21382f..6ac8df6 100644 --- a/src/main/java/technobot/commands/greetings/FarewellCommand.java +++ b/src/main/java/technobot/commands/greetings/FarewellCommand.java @@ -12,6 +12,8 @@ import technobot.handlers.GreetingHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.localization.Localization.get; + /** * Command that configures auto farewells. * @@ -37,14 +39,14 @@ public void execute(SlashCommandInteractionEvent event) { // Remove farewell message if (farewellOption == null) { greetingHandler.removeFarewell(); - String text = EmbedUtils.BLUE_X + " Farewell message successfully removed!"; + String text = get(s -> s.greeting().farewell().removed()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } // Set greeting message greetingHandler.setFarewell(farewellOption.getAsString()); - String text = EmbedUtils.BLUE_TICK + " Farewell message successfully updated!"; + String text = get(s -> s.greeting().farewell().set()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } } diff --git a/src/main/java/technobot/commands/greetings/GreetCommand.java b/src/main/java/technobot/commands/greetings/GreetCommand.java index c65a568..46143b3 100644 --- a/src/main/java/technobot/commands/greetings/GreetCommand.java +++ b/src/main/java/technobot/commands/greetings/GreetCommand.java @@ -12,6 +12,8 @@ import technobot.handlers.GreetingHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.localization.Localization.get; + /** * Command that configures auto greetings. * @@ -37,14 +39,14 @@ public void execute(SlashCommandInteractionEvent event) { // Remove greeting message if (greetingOption == null) { greetingHandler.removeGreet(); - String text = EmbedUtils.BLUE_X + " Greeting message successfully removed!"; + String text = get(s -> s.greeting().greet().removed()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } // Set greeting message greetingHandler.setGreet(greetingOption.getAsString()); - String text = EmbedUtils.BLUE_TICK + " Greeting message successfully updated!"; + String text = get(s -> s.greeting().greet().removed()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } } diff --git a/src/main/java/technobot/commands/greetings/GreetingsCommand.java b/src/main/java/technobot/commands/greetings/GreetingsCommand.java index 1252dbf..e05c86c 100644 --- a/src/main/java/technobot/commands/greetings/GreetingsCommand.java +++ b/src/main/java/technobot/commands/greetings/GreetingsCommand.java @@ -18,6 +18,8 @@ import technobot.listeners.ButtonListener; import technobot.util.embeds.EmbedUtils; +import static technobot.util.localization.Localization.get; + /** * Command that displays and modifies greetings config. * @@ -44,18 +46,18 @@ public void execute(SlashCommandInteractionEvent event) { GreetingHandler greetingHandler = GuildData.get(event.getGuild()).greetingHandler; String text = ""; - switch(event.getSubcommandName()) { + switch (event.getSubcommandName()) { case "channel" -> { OptionMapping channelOption = event.getOption("channel"); if (channelOption == null) { // Remove welcome channel if not specified greetingHandler.removeChannel(); - text = EmbedUtils.BLUE_X + " Welcome channel successfully removed!"; + text = get(s -> s.greeting().greetings().removed()); } else { // Set welcome channel Long channelID = channelOption.getAsGuildChannel().getIdLong(); greetingHandler.setChannel(channelID); - text = EmbedUtils.BLUE_X + " Welcome channel set to <#" + channelID + ">"; + text = get(s -> s.greeting().greetings().set(), channelID); } } case "config" -> { @@ -64,7 +66,7 @@ public void execute(SlashCommandInteractionEvent event) { return; } case "reset" -> { - text = "Would you like to reset the greeting system?\nThis will delete **ALL** data!"; + text = get(s -> s.greeting().greetings().reset()); WebhookMessageAction action = event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)); ButtonListener.sendResetMenu(event.getUser().getId(), "Greeting", action); return; @@ -81,26 +83,18 @@ public void execute(SlashCommandInteractionEvent event) { */ private String configToString(Greetings greetings) { String text = ""; - if (greetings.getWelcomeChannel() == null) { - text += "**Welcome Channel:** none\n"; - } else { - text += "**Welcome Channel:** <#" + greetings.getWelcomeChannel() + ">\n"; - } - if (greetings.getGreeting() == null) { - text += "**Greeting:** none\n"; - } else { - text += "**Greeting:** " + greetings.getGreeting() + "\n"; - } - if (greetings.getFarewell() == null) { - text += "**Farewell:** none\n"; - } else { - text += "**Farewell:** " + greetings.getFarewell() + "\n"; - } - if (greetings.getJoinDM() == null) { - text += "**Join DM:** none\n"; - } else { - text += "**Join DM:** " + greetings.getJoinDM() + "\n"; - } + text += get(s -> s.greeting().greetings().welcomeConfig(), + greetings.getWelcomeChannel() == null ? "none" : "<#" + greetings.getWelcomeChannel() + ">") + "\n"; + + text += get(s -> s.greeting().greetings().greetingConfig(), + greetings.getGreeting() == null ? "none" : greetings.getGreeting()) + "\n"; + + text += get(s -> s.greeting().greetings().farewellConfig(), + greetings.getFarewell() == null ? "none" : greetings.getFarewell()) + "\n"; + + text += get(s -> s.greeting().greetings().joinDmConfig(), + greetings.getJoinDM() == null ? "none" : greetings.getJoinDM()) + "\n"; + return text; } } diff --git a/src/main/java/technobot/commands/greetings/JoinDMCommand.java b/src/main/java/technobot/commands/greetings/JoinDMCommand.java index a27a502..9c909b7 100644 --- a/src/main/java/technobot/commands/greetings/JoinDMCommand.java +++ b/src/main/java/technobot/commands/greetings/JoinDMCommand.java @@ -12,6 +12,8 @@ import technobot.handlers.GreetingHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.localization.Localization.get; + /** * Command that configures auto join DMs. * @@ -37,14 +39,14 @@ public void execute(SlashCommandInteractionEvent event) { // Remove farewell message if (farewellOption == null) { greetingHandler.removeJoinDM(); - String text = EmbedUtils.BLUE_X + " Join DM message successfully removed!"; + String text = get(s -> s.greeting().joinDm().removed()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } // Set greeting message greetingHandler.setJoinDM(farewellOption.getAsString()); - String text = EmbedUtils.BLUE_TICK + " Join DM message successfully updated!"; + String text = get(s -> s.greeting().joinDm().set()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } } diff --git a/src/main/java/technobot/data/cache/Config.java b/src/main/java/technobot/data/cache/Config.java index 03ba1e3..4e823f4 100644 --- a/src/main/java/technobot/data/cache/Config.java +++ b/src/main/java/technobot/data/cache/Config.java @@ -41,6 +41,9 @@ public class Config { @BsonProperty("auto_roles") private Set autoRoles; + @BsonProperty("locale") + private String locale; + public Config() { autoRoles = new HashSet<>(); } @@ -56,6 +59,7 @@ public Config(long guild) { this.levelingBackground = null; this.rewards = new HashMap<>(); this.autoRoles = new HashSet<>(); + this.locale = "en_US"; } public long getGuild() { @@ -149,4 +153,12 @@ public void addAutoRole(long roleID) { } public void removeAutoRole(long roleID) { this.autoRoles.remove(roleID); } + + public String getLocale() { + return locale; + } + + public void setLocale(String locale) { + this.locale = locale; + } } diff --git a/src/main/java/technobot/data/json/EconomyResponses.java b/src/main/java/technobot/data/json/EconomyResponses.java deleted file mode 100644 index 7a88092..0000000 --- a/src/main/java/technobot/data/json/EconomyResponses.java +++ /dev/null @@ -1,32 +0,0 @@ -package technobot.data.json; - -/** - * Represents list of responses to economy commands. - * Used by OkHttp and Gson to convert JSON to java code. - * - * @author TechnoVision - */ -public class EconomyResponses { - - private final String[] work; - private final String[] crimeSuccess; - private final String[] crimeFail; - - public EconomyResponses(String[] work, String[] crimeSuccess, String[] crimeFail) { - this.work = work; - this.crimeSuccess = crimeSuccess; - this.crimeFail = crimeFail; - } - - public String[] getWork() { - return work; - } - - public String[] getCrimeSuccess() { - return crimeSuccess; - } - - public String[] getCrimeFail() { - return crimeFail; - } -} diff --git a/src/main/java/technobot/handlers/economy/EconomyHandler.java b/src/main/java/technobot/handlers/economy/EconomyHandler.java index 4d699e8..45f57f7 100644 --- a/src/main/java/technobot/handlers/economy/EconomyHandler.java +++ b/src/main/java/technobot/handlers/economy/EconomyHandler.java @@ -1,7 +1,6 @@ package technobot.handlers.economy; import com.mongodb.client.AggregateIterable; -import com.mongodb.client.FindIterable; import com.mongodb.client.model.*; import com.mongodb.lang.Nullable; import net.dv8tion.jda.api.entities.Guild; @@ -9,15 +8,14 @@ import org.bson.conversions.Bson; import technobot.TechnoBot; import technobot.data.cache.Economy; -import technobot.util.embeds.EmbedUtils; import java.text.DecimalFormat; import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; -import java.util.stream.StreamSupport; + +import static technobot.util.localization.Localization.get; /** * Handles the server economy backend. @@ -37,7 +35,7 @@ public class EconomyHandler { private final TechnoBot bot; private final Bson guildFilter; private final Map timeouts; - private String currency; + private final String currency; public EconomyHandler(TechnoBot bot, Guild guild) { this.bot = bot; @@ -57,7 +55,7 @@ public EconomyReply work(long userID) { int amount = ThreadLocalRandom.current().nextInt(230) + 20; addMoney(userID, amount); setTimeout(userID, TIMEOUT_TYPE.WORK); - return responses.getWorkResponse(amount, getCurrency()); + return responses.getWorkResponse(amount); } /** @@ -74,12 +72,12 @@ public EconomyReply crime(long userID) { // Crime successful amount = ThreadLocalRandom.current().nextInt(450) + 250; addMoney(userID, amount); - reply = responses.getCrimeSuccessResponse(amount, getCurrency()); + reply = responses.getCrimeSuccessResponse(amount); } else { // Crime failed amount = calculateFine(userID); if (amount > 0) removeMoney(userID, calculateFine(userID)); - reply = responses.getCrimeFailResponse(amount, getCurrency()); + reply = responses.getCrimeFailResponse(amount); } setTimeout(userID, TIMEOUT_TYPE.CRIME); return reply; @@ -88,7 +86,7 @@ public EconomyReply crime(long userID) { /** * Attempt to steal another user's cash. * - * @param userID the user attempting the robbery. + * @param userID the user attempting the robbery. * @param targetID the target being robbed. * @return an EconomyReply object with a response and success boolean. */ @@ -111,15 +109,21 @@ public EconomyReply rob(long userID, long targetID) { if (ThreadLocalRandom.current().nextDouble() > failChance) { // Rob successful pay(targetID, userID, amountStolen); - String value = getCurrency() + " " + EconomyHandler.FORMATTER.format(amountStolen); - String response = EmbedUtils.GREEN_TICK + " You robbed " + value + " from <@" + targetID + ">"; + String response = get( + s -> s.economy().rob().success(), + EconomyHandler.FORMATTER.format(amountStolen), + targetID + ); return new EconomyReply(response, 1, true); } // Rob failed (20-40% fine of net worth) long fine = calculateFine(userID); removeMoney(userID, fine); - String value = getCurrency() + " " + EconomyHandler.FORMATTER.format(fine); - String response = "You were caught attempting to rob <@"+targetID+">, and have been fined " + value + "."; + String response = get( + s -> s.economy().rob().failure(), + EconomyHandler.FORMATTER.format(fine), + targetID + ); return new EconomyReply(response, 1, false); } @@ -169,9 +173,9 @@ public void withdraw(long userID, long amount) { /** * Transfer money from one user to another. * - * @param userID the user to transfer money from. + * @param userID the user to transfer money from. * @param targetID the user to transfer money to. - * @param amount the amount of money to transfer. + * @param amount the amount of money to transfer. */ public void pay(long userID, long targetID, long amount) { removeMoney(userID, amount); @@ -245,7 +249,7 @@ public AggregateIterable getLeaderboard() { return bot.database.economy.aggregate( Arrays.asList( Aggregates.match(Filters.eq("guild", guild.getIdLong())), - Aggregates.addFields(new Field("sum", Filters.eq("$add", Arrays.asList("$balance", Filters.eq("$ifNull", Arrays.asList("$bank", 0)))))), + Aggregates.addFields(new Field<>("sum", Filters.eq("$add", Arrays.asList("$balance", Filters.eq("$ifNull", Arrays.asList("$bank", 0)))))), Aggregates.sort(Sorts.descending("sum")) ) ); @@ -286,7 +290,7 @@ private void removeMoney(long userID, long amount) { * Set a user timeout for a specific economy command. * * @param userID the user to set timeout for. - * @param type the economy command to timeout. + * @param type the economy command to timeout. */ private void setTimeout(long userID, TIMEOUT_TYPE type) { long time = System.currentTimeMillis() + WORK_TIMEOUT; @@ -294,7 +298,7 @@ private void setTimeout(long userID, TIMEOUT_TYPE type) { if (userTimeout == null) { userTimeout = new UserTimeout(userID); } - switch(type) { + switch (type) { case WORK -> userTimeout.setWorkTimeout(time); case CRIME -> userTimeout.setCrimeTimeout(time); case ROB -> userTimeout.setRobTimeout(System.currentTimeMillis() + ROB_TIMEOUT); @@ -306,7 +310,7 @@ private void setTimeout(long userID, TIMEOUT_TYPE type) { * Get a user's timeout for a specific econony command. * * @param userID the user to get the timeout from. - * @param type the economy command that is timed out. + * @param type the economy command that is timed out. * @return time in millis till timeout is up. Null if not set. */ public @Nullable Long getTimeout(long userID, TIMEOUT_TYPE type) { @@ -315,7 +319,7 @@ private void setTimeout(long userID, TIMEOUT_TYPE type) { return null; } Long timeout = null; - switch(type) { + switch (type) { case WORK -> timeout = userTimeout.getWorkTimeout(); case CRIME -> timeout = userTimeout.getCrimeTimeout(); case ROB -> timeout = userTimeout.getRobTimeout(); diff --git a/src/main/java/technobot/handlers/economy/EconomyLocalization.java b/src/main/java/technobot/handlers/economy/EconomyLocalization.java index 6a5242f..e882d23 100644 --- a/src/main/java/technobot/handlers/economy/EconomyLocalization.java +++ b/src/main/java/technobot/handlers/economy/EconomyLocalization.java @@ -1,14 +1,12 @@ package technobot.handlers.economy; -import com.google.gson.Gson; -import technobot.data.json.EconomyResponses; +import technobot.util.localization.Localization; +import technobot.util.localization.LocalizationSchema; -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; import java.util.concurrent.ThreadLocalRandom; +import static technobot.util.localization.Localization.format; + /** * Handles localized responses to economy commands. * @@ -16,22 +14,18 @@ */ public class EconomyLocalization { - private static final String PATH = "localization/economy.json"; - private final String[] work; private final String[] crimeSuccess; - private final String[] crimeFail; + private final String[] crimeFailure; /** - * Reads economy.json responses into local memory + * Reads economy responses into local memory */ public EconomyLocalization() { - InputStream inputStream = getClass().getClassLoader().getResourceAsStream(PATH); - Reader reader = new BufferedReader(new InputStreamReader(inputStream)); - EconomyResponses responses = new Gson().fromJson(reader, EconomyResponses.class); - work = responses.getWork(); - crimeSuccess = responses.getCrimeSuccess(); - crimeFail = responses.getCrimeFail(); + LocalizationSchema.Economy responses = Localization.get(LocalizationSchema::economy); + work = responses.work().success(); + crimeSuccess = responses.crime().success(); + crimeFailure = responses.crime().failure(); } /** @@ -40,11 +34,10 @@ public EconomyLocalization() { * @param amount the amount of money earned. * @return an EconomyReply object with response and ID number. */ - public EconomyReply getWorkResponse(long amount, String currency) { + public EconomyReply getWorkResponse(long amount) { int index = ThreadLocalRandom.current().nextInt(work.length); - String value = currency+" "+EconomyHandler.FORMATTER.format(amount); - String reply = work[index].replace("{amount}", value); - return new EconomyReply(reply, index+1); + + return new EconomyReply(format(work[index], amount), index + 1); } /** @@ -53,11 +46,14 @@ public EconomyReply getWorkResponse(long amount, String currency) { * @param amount the amount of money earned. * @return an EconomyReply object with response and ID number. */ - public EconomyReply getCrimeSuccessResponse(long amount, String currency) { + public EconomyReply getCrimeSuccessResponse(long amount) { int index = ThreadLocalRandom.current().nextInt(crimeSuccess.length); - String value = currency+" "+EconomyHandler.FORMATTER.format(amount); - String reply = crimeSuccess[index].replace("{amount}", value); - return new EconomyReply(reply, index+1, true); + + return new EconomyReply( + format(crimeSuccess[index], amount), + index + 1, + true + ); } /** @@ -66,10 +62,13 @@ public EconomyReply getCrimeSuccessResponse(long amount, String currency) { * @param amount the amount of money list. * @return an EconomyReply object with response and ID number. */ - public EconomyReply getCrimeFailResponse(long amount, String currency) { - int index = ThreadLocalRandom.current().nextInt(crimeFail.length); - String value = currency+" "+EconomyHandler.FORMATTER.format(amount); - String reply = crimeFail[index].replace("{amount}", value); - return new EconomyReply(reply, index+1, false); + public EconomyReply getCrimeFailResponse(long amount) { + int index = ThreadLocalRandom.current().nextInt(crimeFailure.length); + + return new EconomyReply( + format(crimeFailure[index], amount), + index + 1, + false + ); } } diff --git a/src/main/java/technobot/util/localization/Localization.java b/src/main/java/technobot/util/localization/Localization.java new file mode 100644 index 0000000..582dff7 --- /dev/null +++ b/src/main/java/technobot/util/localization/Localization.java @@ -0,0 +1,116 @@ +package technobot.util.localization; + +import com.google.gson.Gson; +import kotlin.text.Regex; +import technobot.handlers.economy.EconomyReply; +import technobot.util.embeds.EmbedUtils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.Locale; +import java.util.function.Function; +import java.util.regex.Pattern; + +/** + * Handles all stuff related to localization. + * + * @author TheOnlyTails + */ +public class Localization { + public static Locale currentLocale = Localization.Locale.EN_US; + + /** + * Fetches a localization value from the localization file, based on the locale. + * + * @param query The query for the localization value. + * @param locale The locale to fetch the value from. + * @return The localization value. + * @throws NullPointerException If no localization file is found for the locale. + */ + public static T get(Function query, Locale locale, Object... args) throws NullPointerException { + try (var inputStream = Localization.class.getClassLoader().getResourceAsStream("localization/" + locale.locale + ".json")) { + if (inputStream == null) throw new IOException(); + + var reader = new BufferedReader(new InputStreamReader(inputStream)); + var schema = new Gson().fromJson(reader, LocalizationSchema.class); + + final var value = query.apply(schema); + if (args.length > 0 && value instanceof String template) { + //noinspection unchecked + return (T) format(template, args); + } else { + return value; + } + } catch (IOException e) { + throw new NullPointerException("Could not load localization file for locale " + locale.locale); + } + } + + /** + * Fetches a localization value from the localization file, based on the current locale. + * + * @param query The query for the localization value. + * @return The localization value. + * @throws NullPointerException If no localization file is found for the locale. + */ + public static T get(Function query, Object... args) throws NullPointerException { + return get(query, currentLocale, args); + } + + public static String format(String template, Object... args) { + // replace all special constants, to save on args + template = template.replaceAll("\\{red_x\\}", EmbedUtils.RED_X) + .replaceAll("\\{green_tick\\}", EmbedUtils.GREEN_TICK) + .replaceAll("\\{blue_x\\}", EmbedUtils.BLUE_X) + .replaceAll("\\{blue_tick\\}", EmbedUtils.BLUE_TICK) + .replaceAll("\\{mention\\}", "<@{}>") + .replaceAll("\\{role\\}", "<@&{}>") + .replaceAll("\\{channel\\}", "<#{}>") + .replaceAll("\\{currency\\}", "\uD83E\uDE99"); + + var argsList = Arrays.stream(args).map(Object::toString).toList(); + var templateArgsCount = Pattern.compile("\\{\\}").matcher(template).groupCount(); + + switch (Integer.compare(argsList.size(), templateArgsCount)) { + case -1 -> { + System.err.printf(""" + Too few arguments (%d) provided for template: %s + All unused template slots will not be filled. + """, argsList.size(), template); + for (final var arg : argsList) { + template = template.replace("{}", arg); + } + } + case 0 -> { + for (final var arg : argsList) { + template = template.replace("{}", arg); + } + } + case 1 -> { + System.err.printf("Too many arguments (%d) provided for template: %s%n", argsList.size(), template); + for (final var arg : argsList.subList(0, templateArgsCount - 1)) { + template = template.replace("{}", arg); + } + } + } + + return template; + } + + public enum Locale { + EN_US("en_US", "English (US)"), + EN_GB("en_GB", "English (UK)"), + HE_IL("he_IL", "Hebrew"), + ; + + public final String locale; + public final String displayName; + + Locale(String locale, String displayName) { + this.locale = locale; + this.displayName = displayName; + } + } +} diff --git a/src/main/java/technobot/util/localization/LocalizationSchema.java b/src/main/java/technobot/util/localization/LocalizationSchema.java new file mode 100644 index 0000000..8aa6c01 --- /dev/null +++ b/src/main/java/technobot/util/localization/LocalizationSchema.java @@ -0,0 +1,165 @@ +package technobot.util.localization; + +public record LocalizationSchema( + Automation automation, + Economy economy, + Fun fun, + Greeting greeting +) { + public record Automation(AutoRole autoRole) { + public record AutoRole(Add add, Remove remove, List list) { + public record Add(String higherLevel, String premium, String maxRolesReached, String roleAdded) { + } + + public record Remove(String roleNotSet, String roleRemoved) { + } + + public record List(String noAutoRoles, String premium, String roleCount, String role) { + } + + } + } + + /** + * Represents list of responses to economy commands. + * + * @author TechnoVision + */ + public record Economy( + String replyId, + Balance balance, + Crime crime, + Deposit deposit, + Pay pay, + Rob rob, + Withdraw withdraw, + Work work + ) { + public record Balance(String leaderboardRank, String cash, String bank, String total) { + } + + public record Crime(String timeout, String[] success, String[] failure) { + } + + public record Deposit(String noMoney, String notEnough, String success) { + } + + public record Pay(String paySelf, String payBots, String notEnough, String success) { + } + + public record Rob(String robSelf, String robBots, String timeout, String failure, String success) { + } + + public record Withdraw(String noMoney, String tooMuch, String success) { + } + + public record Work(String timeout, String[] success) { + } + } + + public record Fun( + Action action, + Cute cute, + EightBall eightBall, + Emote emote, + Google google, + Joke joke, + Meme meme, + Nsfw nsfw, + Reddit reddit, + Surprise surprise + ) { + public record Action( + String failure, + String bite, + String brofist, + String cuddle, + String handhold, + String hug, + String kiss, + String lick, + String pat, + String pinch, + String poke, + String punch, + String slap, + String smack, + String sorry, + String stare, + String thumbsup, + String tickle, + String wave, + String wink + ) { + } + + public record Cute(String failure) { + } + + public record EightBall(String tooLong, String[] responses) { + } + + public record Emote( + String failure, + String mad, + String blush, + String celebrate, + String clap, + String confused, + String cry, + String dance, + String facepalm, + String happy, + String laugh, + String pout, + String shrug, + String shy, + String sigh, + String slowClap, + String scared, + String sleep, + String yawn + ) { + } + + public record Google(String tooLong) { + } + + public record Joke(String failure) { + } + + public record Meme(String failure) { + } + + public record Nsfw(String failure) { + } + + public record Reddit(String failure) { + } + + public record Surprise(String failure) { + } + } + + public record Greeting(Farewell farewell, Greet greet, Greetings greetings, JoinDM joinDm) { + public record Farewell(String set, String removed) { + } + + public record Greet(String set, String removed) { + } + + public record Greetings( + String removed, + String set, + String reset, + String welcomeConfig, + String greetingConfig, + String farewellConfig, + String joinDmConfig + ) { + } + + public record JoinDM(String set, String removed) { + } + } +} diff --git a/src/main/resources/localization/economy.json b/src/main/resources/localization/economy.json deleted file mode 100644 index e02a41c..0000000 --- a/src/main/resources/localization/economy.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "work": [ - "You suggest something good and get rewarded {amount}.", - "You drove the school bus today and were only 5 minutes late, but you still got {amount} for your efforts!", - "You dig up some buried treasure on an island and find {amount} worth of gold jewelry!", - "You work as a teacher and earn {amount} for inspiring young minds.", - "Your boring nine-to-five office job pays you {amount}.", - "You've worked on a farm cultivating wheat from dawn to dusk. The land lord pays you {amount} for your struggles.", - "You discover a cure for a rare disease and earn {amount} in grant money!", - "Your recent novel becomes a hit, earning you {amount} in royalties.", - "You find a rare fossil on the beach and sell it to the museum for {amount}.", - "You invested in the right stocks a the right time, earning {amount}.", - "Your NFT collection surges in price, so you sell them for {amount}.", - "You finished digging in the mines for the day. It's hard work, but they paid you {amount}.", - "Dogecoin went to the moon! Your patient waiting got you {amount}.", - "The lemonade sold well. Your efforts gathered you {amount}.", - "Your dog dug up some cash. Finders keepers! {amount}", - "You decided to buy a lottery ticket. You won {amount}.", - "You made a viral video on the internet and got {amount} from ad revenue.", - "You found a lost cat and were given {amount} as a thanks.", - "You decided to become a web developer (why). Anyway you earned {amount}." - ], - "crimeSuccess": [ - "You work for the Juarez cartel as a brick-presser and earn {amount}! They'll probably kill you and your family tomorrow. Just saying.", - "You rob an orphanage for {amount}.", - "You break into the house next door and sell their gaming PC on E-Bay for {amount}.", - "You work as a scam seller on Amazon selling fake airpods for {amount}.", - "You break into Rapunzel's kingdom, steal her hair, and sell it on the black market for {amount}.", - "You are a high school chemistry teacher diagnosed with lung cancer & turn to selling meth for {amount} to secure your family's future.", - "You punched some random person and they gave you {amount} to stop.", - "You smashed a kid's piggy bank and got {amount} from it.", - "What you did was too horrible to speak of. I can't believe you would do that. Was the {amount} even worth it for those horrible crimes you did? No.", - "You were hired as an assassin and you succeeded, earning {amount}.", - "You need some extra cash for your drug habit. You break into the local dirty video store and rob them of {amount}! You also take a few \"items\" for yourself..." - ], - "crimeFail": [ - "You break into the house next door only to find the whole family eating dinner together. Your bail cost {amount}.", - "You got shot trying to smuggle drugs across the border. The medical bills cost you a whopping {amount}.", - "You get caught shoplifting by the local mall cop, who fines you for {amount}.", - "You tried to do a prank call but called the police instead and were fined {amount}.", - "You tried to rob a McDonalds but Ronald Mcdonald Big Mac'd you in the face and stole {amount} from you.", - "You tried to rob someone but they just mugged you instead. You lost {amount}.", - "You attempted to steal a bar of chocolate from a local store but were caught and had to pay {amount}. It was bad chocolate.", - "You tried to jump the old lady walking down the street. Turns out she had a gun, and robbed you blind of {amount}.", - "You attempted to cook up some drugs to sell on the black market, but the chemicals exploded in your face, costing you {amount} in medical bills." - ] -} diff --git a/src/main/resources/localization/en_us.json b/src/main/resources/localization/en_us.json new file mode 100644 index 0000000..a12bee8 --- /dev/null +++ b/src/main/resources/localization/en_us.json @@ -0,0 +1,213 @@ +{ + "automation": { + "autoRole": { + "add": { + "higherLevel": "I cannot give out roles that have a higher position than me!", + "premium": "You can set multiple auto-roles with premium! For more info, use `/premium`.", + "maxRolesReached": "You have hit the maximum number of auto-roles for this guild!", + "roleAdded": "{blue_tick} The {role} role will be given to all new members when they join the server." + }, + "remove": { + "roleNotSet": "The {role} role is not set as an auto-role.", + "roleRemoved": "{blue_x} The {role} role will no longer be given to new members when they join the server." + }, + "list": { + "noAutoRoles": "Use `/auto-role add ` to set your first auto role!", + "premium": "Add additional roles with `/premium`", + "roleCount": "There are {} auto roles given to new members:", + "role": "**{}**. {role}" + } + } + }, + "economy": { + "replyId": "Reply #{}", + "balance": { + "leaderboardRank": "Leaderboard Rank: #{}", + "cash": "Cash:", + "bank": "Bank:", + "total": "Total:" + }, + "crime": { + "timeout": ":stopwatch: You can next commit a crime {}.", + "success": [ + "You work for the Juarez cartel as a brick-presser and earn {currency} {}! They'll probably kill you and your family tomorrow. Just saying.", + "You rob an orphanage for {currency} {}.", + "You break into the house next door and sell their gaming PC on E-Bay for {currency} {}.", + "You work as a scam seller on Amazon selling fake airpods for {currency} {}.", + "You break into Rapunzel's kingdom, steal her hair, and sell it on the black market for {currency} {}.", + "You are a high school chemistry teacher diagnosed with lung cancer & turn to selling meth for {currency} {} to secure your family's future.", + "You punched some random person and they gave you {currency} {} to stop.", + "You smashed a kid's piggy bank and got {currency} {} from it.", + "What you did was too horrible to speak of. I can't believe you would do that. Was the {currency} {} even worth it for those horrible crimes you did? No.", + "You were hired as an assassin and you succeeded, earning {currency} {}.", + "You need some extra cash for your drug habit. You break into the local dirty video store and rob them of {currency} {}! You also take a few \"items\" for yourself..." + ], + "failure": [ + "You break into the house next door only to find the whole family eating dinner together. Your bail cost {currency} {}.", + "You got shot trying to smuggle drugs across the border. The medical bills cost you a whopping {currency} {}.", + "You get caught shoplifting by the local mall cop, who fines you for {currency} {}.", + "You tried to do a prank call but called the police instead and were fined {currency} {}.", + "You tried to rob a McDonalds but Ronald Mcdonald Big Mac'd you in the face and stole {currency} {} from you.", + "You tried to rob someone but they just mugged you instead. You lost {currency} {}.", + "You attempted to steal a bar of chocolate from a local store but were caught and had to pay {currency} {}. It was bad chocolate.", + "You tried to jump the old lady walking down the street. Turns out she had a gun, and robbed you blind of {currency} {}.", + "You attempted to cook up some drugs to sell on the black market, but the chemicals exploded in your face, costing you {currency} {} in medical bills." + ] + }, + "deposit": { + "noMoney": "{red_x} You don't have any money to deposit!", + "notEnough": "{red_x} You cannot deposit more than {currency} {}!", + "success": "{green_tick} Deposited {currency} {} to your bank!" + }, + "pay": { + "paySelf": "{red_x} You cannot pay yourself!", + "payBots": "{red_x} You cannot pay bots!", + "notEnough": "{red_x} You don't have that much money to give. You currently have {currency} {} on hand.", + "success": "{green_tick} {mention} has received your {currency} {}." + }, + "rob": { + "robSelf": "{red_x} You cannot rob yourself!", + "robBots": "{red_x} You cannot rob bots, they are too powerful for you!", + "timeout": ":stopwatch: You can attempt to rob another member {}.", + "failure": "You were caught attempting to rob {mention}, and have been fined {currency} {}.", + "success": "{green_tick} You robbed {currency} {} from {mention}!" + }, + "withdraw": { + "noMoney": "{red_x} You don't have any money in your bank to withdraw!", + "tooMuch": "{red_x} You cannot withdraw more than {currency} {}!", + "success": "{green_tick} Withdrew {currency} {} from your bank!" + }, + "work": { + "timeout": ":stopwatch: You can next work {}.", + "success": [ + "You suggest something good and get rewarded {currency} {}.", + "You drove the school bus today and were only 5 minutes late, but you still got {currency} {} for your efforts!", + "You dig up some buried treasure on an island and find {currency} {} worth of gold jewelry!", + "You work as a teacher and earn {currency} {} for inspiring young minds.", + "Your boring nine-to-five office job pays you {currency} {}.", + "You've worked on a farm cultivating wheat from dawn to dusk. The land lord pays you {currency} {} for your struggles.", + "You discover a cure for a rare disease and earn {currency} {} in grant money!", + "Your recent novel becomes a hit, earning you {currency} {} in royalties.", + "You find a rare fossil on the beach and sell it to the museum for {currency} {}.", + "You invested in the right stocks a the right time, earning {currency} {}.", + "Your NFT collection surges in price, so you sell them for {currency} {}.", + "You finished digging in the mines for the day. It's hard work, but they paid you {currency} {}.", + "Dogecoin went to the moon! Your patient waiting got you {currency} {}.", + "The lemonade sold well. Your efforts gathered you {currency} {}.", + "Your dog dug up some cash. Finders keepers! {currency} {}", + "You decided to buy a lottery ticket. You won {currency} {}.", + "You made a viral video on the internet and got {currency} {} from ad revenue.", + "You found a lost cat and were given {currency} {} as a thanks.", + "You decided to become a web developer (why). Anyway you earned {currency} {}." + ] + } + }, + "fun": { + "action": { + "failure": "I was unable to fetch that emote!", + "bite":"takes a bit out of {}.", + "brofist":"and {} brofist!", + "cuddle": "cuddles with {}.", + "handhold":"and {} hold hands. How sweet <3", + "hug": "gives {} a big hug!", + "kiss":"kisses {}.", + "lick": "licks {}... gross!", + "pat":"gives {} a little pat on the head", + "pinch": "pinches {}. Ouch!", + "poke":"gives {} a little poke.", + "punch": "punches {} right in the face!", + "slap":"slaps {}. They deserved it!", + "smack": "gives {} a smack they will remember.", + "sorry":"apologizes to {}.", + "stare": "won't stop staring at {}...", + "thumbsup":"gives {} two thumbs up!", + "tickle": "tickles {}.", + "wave":"waves at {}. ", + "wink": "winks at {}." + }, + "cute": { + "failure": "I was unable to fetch any cute pictures!" + }, + "eightBall": { + "tooLong": "The 8ball doesn't like questions longer than 250 characters!", + "responses": [ + "I can tell you certainly, no.", + "I'm not sure but ur def stupid.", + "It is certain.", + "Without a doubt.", + "You may rely on it.", + "As I see it, yes.", + "Most likely.", + "Signs point to yes.", + "Reply hazy try again.", + "Better not tell you now.", + "Hmm imma just let u figure it out.", + "Don't count on it.", + "Outlook not so good.", + "My sources say no." + ] + }, + "emote": { + "failure": "I was unable to fetch that emote!", + "mad": "doesn't like that.", + "blush": "has turned into a tomato.", + "celebrate": "is ready to celebrate!", + "clap": "claps excitedly.", + "confused": "is really confused.", + "cry": "needs a hug...", + "dance": "is dancing!", + "facepalm": "is in disbelief.", + "happy": "smiles.", + "laugh": "laughs out loud.", + "pout": "is in a bad mood.", + "shrug": "doesn't care...", + "shy": "is feeling timid.", + "sigh": "is disappointed.", + "slowClap": "is not amused.", + "scared": "fears for their life.", + "sleep": "falls into a deep sleep.", + "yawn": "is getting very sleepy." + }, + "google":{ + "tooLong": "google doesn't like questions longer than 250 characters!" + }, + "joke": { + "failure": "I was unable to fetch any jokes!" + }, + "meme": { + "failure": "I was unable to fetch any memes!" + }, + "nsfw": { + "failure": "I was unable to fetch any nsfw pictures!" + }, + "reddit": { + "failure": "I was unable to fetch any posts from that subreddit!" + }, + "surprise": { + "failure": "I was unable to fetch any surprises!" + } + }, + "greeting": { + "farewell": { + "removed": "{blue_x} Farewell message successfully removed!", + "set": "{blue_tick} Farewell message successfully updated!" + }, + "greet": { + "removed": "{blue_x} Greeting message successfully removed!", + "set": "{blue_tick} Greeting message successfully updated!" + }, + "greetings": { + "removed": "{blue_x} Welcome channel successfully removed!", + "set": "{blue_x} Welcome channel set to {channel}", + "reset": "Would you like to reset the greeting system?\nThis will delete **ALL** data!", + "welcomeConfig": "**Welcome Channel:** {}", + "greetingConfig": "**Greeting:** {}", + "farewellConfig": "**Farewell:** {}", + "joinDmConfig": "**Join DM:** {}" + }, + "joinDm": { + "removed": "{blue_x} Join DM message successfully removed!", + "set": "{blue_tick} Join DM message successfully updated!" + } + } +} \ No newline at end of file From 0d6fd72e3584e60bbb3b889c91900792fa52dcdf Mon Sep 17 00:00:00 2001 From: TechnoVisionDev Date: Tue, 21 Jun 2022 13:23:33 -0700 Subject: [PATCH 02/15] Add a default case to emote and action command switches --- src/main/java/technobot/commands/fun/ActionCommand.java | 1 + src/main/java/technobot/commands/fun/EmoteCommand.java | 1 + 2 files changed, 2 insertions(+) diff --git a/src/main/java/technobot/commands/fun/ActionCommand.java b/src/main/java/technobot/commands/fun/ActionCommand.java index a5569fd..3c95d2a 100644 --- a/src/main/java/technobot/commands/fun/ActionCommand.java +++ b/src/main/java/technobot/commands/fun/ActionCommand.java @@ -81,6 +81,7 @@ public void execute(SlashCommandInteractionEvent event) { case "tickle" -> get(s -> s.fun().action().tickle(), target); case "wave" -> get(s -> s.fun().action().wave(), target); case "wink" -> get(s -> s.fun().action().wink(), target); + default -> ""; }; // Asynchronous API call diff --git a/src/main/java/technobot/commands/fun/EmoteCommand.java b/src/main/java/technobot/commands/fun/EmoteCommand.java index eab5ef5..11b2dff 100644 --- a/src/main/java/technobot/commands/fun/EmoteCommand.java +++ b/src/main/java/technobot/commands/fun/EmoteCommand.java @@ -77,6 +77,7 @@ public void execute(SlashCommandInteractionEvent event) { case "scared" -> get(s -> s.fun().emote().scared()); case "sleep" -> get(s -> s.fun().emote().sleep()); case "yawn" -> get(s -> s.fun().emote().yawn()); + default -> ""; }; // Asynchronous API call From 59dde332067b1626a6b470a42ddf25630729250a Mon Sep 17 00:00:00 2001 From: theonlytails Date: Tue, 21 Jun 2022 23:56:36 +0300 Subject: [PATCH 03/15] feat(localization): migrated the levels commands to the new system feat(localization): added a bunch of utility records for the `LocalizationSchema` Signed-off-by: theonlytails --- .../commands/automation/AutoRoleCommand.java | 4 +- .../commands/greetings/FarewellCommand.java | 2 +- .../commands/greetings/GreetCommand.java | 4 +- .../commands/greetings/JoinDMCommand.java | 2 +- .../commands/levels/LevelingCommand.java | 93 ++++++----- .../commands/levels/RankCommand.java | 8 +- .../commands/levels/RankcardCommand.java | 21 +-- .../commands/levels/RewardsCommand.java | 16 +- .../technobot/commands/levels/TopCommand.java | 136 ++++++++-------- .../commands/staff/RemoveWarnCommand.java | 6 +- .../technobot/handlers/ConfigHandler.java | 2 +- .../util/localization/Localization.java | 1 + .../util/localization/LocalizationSchema.java | 116 +++++++++----- .../util/localization/SchemaUtils.java | 9 ++ src/main/resources/localization/en_us.json | 147 +++++++++++++----- 15 files changed, 354 insertions(+), 213 deletions(-) create mode 100644 src/main/java/technobot/util/localization/SchemaUtils.java diff --git a/src/main/java/technobot/commands/automation/AutoRoleCommand.java b/src/main/java/technobot/commands/automation/AutoRoleCommand.java index 7cda5fb..c3c7853 100644 --- a/src/main/java/technobot/commands/automation/AutoRoleCommand.java +++ b/src/main/java/technobot/commands/automation/AutoRoleCommand.java @@ -74,11 +74,11 @@ public void execute(SlashCommandInteractionEvent event) { Role role = event.getOption("role").getAsRole(); if (!configHandler.getConfig().getAutoRoles().contains(role.getIdLong())) { event.replyEmbeds(EmbedUtils.createError( - get(s -> s.automation().autoRole().remove().roleNotSet(), role.getId()) + get(s -> s.automation().autoRole().remove().failure(), role.getId()) )).setEphemeral(true).queue(); return; } - embed = EmbedUtils.createDefault(get(s -> s.automation().autoRole().remove().roleRemoved(), role.getId())); + embed = EmbedUtils.createDefault(get(s -> s.automation().autoRole().remove().success(), role.getId())); if (!configHandler.isPremium()) { configHandler.clearAutoRoles(); } else { diff --git a/src/main/java/technobot/commands/greetings/FarewellCommand.java b/src/main/java/technobot/commands/greetings/FarewellCommand.java index 6ac8df6..ced4de5 100644 --- a/src/main/java/technobot/commands/greetings/FarewellCommand.java +++ b/src/main/java/technobot/commands/greetings/FarewellCommand.java @@ -39,7 +39,7 @@ public void execute(SlashCommandInteractionEvent event) { // Remove farewell message if (farewellOption == null) { greetingHandler.removeFarewell(); - String text = get(s -> s.greeting().farewell().removed()); + String text = get(s -> s.greeting().farewell().reset()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } diff --git a/src/main/java/technobot/commands/greetings/GreetCommand.java b/src/main/java/technobot/commands/greetings/GreetCommand.java index 46143b3..e97369a 100644 --- a/src/main/java/technobot/commands/greetings/GreetCommand.java +++ b/src/main/java/technobot/commands/greetings/GreetCommand.java @@ -39,14 +39,14 @@ public void execute(SlashCommandInteractionEvent event) { // Remove greeting message if (greetingOption == null) { greetingHandler.removeGreet(); - String text = get(s -> s.greeting().greet().removed()); + String text = get(s -> s.greeting().greet().reset()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } // Set greeting message greetingHandler.setGreet(greetingOption.getAsString()); - String text = get(s -> s.greeting().greet().removed()); + String text = get(s -> s.greeting().greet().reset()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } } diff --git a/src/main/java/technobot/commands/greetings/JoinDMCommand.java b/src/main/java/technobot/commands/greetings/JoinDMCommand.java index 9c909b7..ace10f8 100644 --- a/src/main/java/technobot/commands/greetings/JoinDMCommand.java +++ b/src/main/java/technobot/commands/greetings/JoinDMCommand.java @@ -39,7 +39,7 @@ public void execute(SlashCommandInteractionEvent event) { // Remove farewell message if (farewellOption == null) { greetingHandler.removeJoinDM(); - String text = get(s -> s.greeting().joinDm().removed()); + String text = get(s -> s.greeting().joinDm().reset()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } diff --git a/src/main/java/technobot/commands/levels/LevelingCommand.java b/src/main/java/technobot/commands/levels/LevelingCommand.java index 031ea30..4311f73 100644 --- a/src/main/java/technobot/commands/levels/LevelingCommand.java +++ b/src/main/java/technobot/commands/levels/LevelingCommand.java @@ -24,6 +24,8 @@ import java.io.IOException; import java.net.URL; +import static technobot.util.localization.Localization.get; + /** * Command that displays and modifies leveling config. * @@ -66,18 +68,18 @@ public void execute(SlashCommandInteractionEvent event) { String text = ""; Bson update = null; - switch(event.getSubcommandName()) { + switch (event.getSubcommandName()) { case "channel" -> { OptionMapping channelOption = event.getOption("channel"); if (channelOption != null) { long channel = channelOption.getAsGuildChannel().getIdLong(); config.setLevelingChannel(channel); update = Updates.set("leveling_channel", channel); - text = EmbedUtils.BLUE_TICK + " Leveling messages will now only display in <#" + channel + ">."; + text = get(s -> s.levels().leveling().channel().specific(), channel); } else { config.setLevelingChannel(null); update = Updates.unset("leveling_channel"); - text = EmbedUtils.BLUE_TICK + " Leveling messages will now display in the channel the user levels up in."; + text = get(s -> s.levels().leveling().channel().specific()); } } case "message" -> { @@ -86,11 +88,11 @@ public void execute(SlashCommandInteractionEvent event) { String msg = messageOption.getAsString(); config.setLevelingMessage(msg); update = Updates.set("leveling_message", msg); - text = EmbedUtils.BLUE_TICK + " Successfully set a custom level-up message."; + text = get(s -> s.levels().leveling().message().set()); } else { config.setLevelingMessage(null); update = Updates.unset("leveling_message"); - text = EmbedUtils.BLUE_TICK + " Reset level-up message to default."; + text = get(s -> s.levels().leveling().message().reset()); } } case "dm" -> { @@ -98,9 +100,9 @@ public void execute(SlashCommandInteractionEvent event) { config.setLevelingDM(isDM); update = Updates.set("leveling_dm", isDM); if (isDM) { - text = EmbedUtils.BLUE_TICK + " Level-up messages will now be sent through DMs."; + text = get(s -> s.levels().leveling().dm().enable()); } else { - text = EmbedUtils.BLUE_X + " Level-up messages will no longer be sent through DMs."; + text = get(s -> s.levels().leveling().dm().disable()); } } case "mod" -> { @@ -108,9 +110,9 @@ public void execute(SlashCommandInteractionEvent event) { int mod = 1; if (modOption != null) { mod = modOption.getAsInt(); - text = EmbedUtils.BLUE_TICK + " Leveling messages will now only display every **" + mod + "** levels."; + text = get(s -> s.levels().leveling().mod().set(), mod); } else { - text = EmbedUtils.BLUE_TICK + " Leveling messages have been reset to display every level."; + text = get(s -> s.levels().leveling().mod().reset()); } config.setLevelingMod(mod); update = Updates.set("leveling_mod", mod); @@ -125,14 +127,14 @@ public void execute(SlashCommandInteractionEvent event) { test.getWidth(); config.setLevelingBackground(urlOption); update = Updates.set("leveling_background", urlOption); - text = EmbedUtils.BLUE_TICK + " Successfully updated the server rankcard background!"; + text = get(s -> s.levels().leveling().serverBackground().set()); } else { config.setLevelingBackground(null); update = Updates.unset("leveling_background"); - text = EmbedUtils.BLUE_TICK + " Reset the server rankcard background to default image!"; + text = get(s -> s.levels().leveling().serverBackground().reset()); } } catch (IOException | NullPointerException | OutOfMemoryError e2) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError("Unable to set that URL as the server rankcard background.")).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels().leveling().serverBackground().failure()))).queue(); return; } } @@ -141,9 +143,9 @@ public void execute(SlashCommandInteractionEvent event) { config.setLevelingMute(isMute); update = Updates.set("leveling_mute", isMute); if (isMute) { - text = EmbedUtils.BLUE_X + " Leveling messages have been muted and will not be displayed!"; + text = get(s -> s.levels().leveling().mute().disable()); } else { - text = EmbedUtils.BLUE_TICK + " Leveling messages will now be displayed!"; + text = get(s -> s.levels().leveling().mute().enable()); } } case "reward" -> { @@ -154,18 +156,18 @@ public void execute(SlashCommandInteractionEvent event) { Role role = event.getGuild().getRoleById(reward); int botPos = event.getGuild().getBotRole().getPosition(); if (role == null || role.getPosition() >= botPos || role.isManaged()) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError("I cannot reward that role! Please check my permissions and role position.")).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels().leveling().reward().failure()))).queue(); return; } Integer x = config.getRewards().get(reward); if (x != null && x == level) { config.removeReward(reward); - update = Updates.unset("rewards."+reward); - text = EmbedUtils.BLUE_TICK + " Successfully removed the <@&"+reward+"> reward role."; + update = Updates.unset("rewards." + reward); + text = get(s -> s.levels().leveling().reward().remove(), role); } else { config.addReward(level, reward); - update = Updates.set("rewards."+reward, level); - text = EmbedUtils.BLUE_TICK + " Users will now receive the <@&"+reward+"> role at level **"+level+"**."; + update = Updates.set("rewards." + reward, level); + text = get(s -> s.levels().leveling().reward().add(), role); } } case "config" -> { @@ -176,12 +178,12 @@ public void execute(SlashCommandInteractionEvent event) { case "reset" -> { User user = event.getOption("user").getAsUser(); data.levelingHandler.resetProfile(user.getIdLong()); - text = EmbedUtils.BLUE_TICK + " All leveling data was reset for **" + user.getName() + "**."; + text = get(s -> s.levels().leveling().reset(), user.getName()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } case "reset-all" -> { - text = "Would you like to reset the leveling system?\nThis will delete **ALL** data!"; + text = get(s -> s.levels().leveling().resetAll()); WebhookMessageAction action = event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)); ButtonListener.sendResetMenu(event.getUser().getId(), "Leveling", action); return; @@ -199,24 +201,37 @@ public void execute(SlashCommandInteractionEvent event) { */ private String configToString(Config config) { String text = ""; - if (config.getLevelingChannel() == null) { - text += "**Level-Up Channel:** none\n"; - } else { - text += "**Level-Up Channel:** <#" + config.getLevelingChannel() + ">\n"; - } - text += "**Leveling Modulus:** " + config.getLevelingMod() + "\n"; - text += "**Is Muted:** " + config.isLevelingMute() + "\n"; - text += "**Level-Up DMs:** " + config.isLevelingDM() + "\n"; - if (config.getLevelingMessage() == null) { - text += "**Custom Message:** none\n"; - } else { - text += "**Custom Message:** '" + config.getLevelingMessage() + "'\n"; - } - if (config.getLevelingBackground() == null) { - text += "**Custom Background:** none\n"; - } else { - text += "**Custom Background:** " + config.getLevelingBackground() + "\n"; - } + text += get( + s -> s.levels().leveling().config().channel(), + config.getLevelingChannel() == null ? "none" : config.getLevelingChannel() + ) + "\n"; + + text += get( + s -> s.levels().leveling().config().modulus(), + config.getLevelingMod() + ) + "\n"; + + + text += get( + s -> s.levels().leveling().config().muted(), + config.isLevelingMute() + ) + "\n"; + + text += get( + s -> s.levels().leveling().config().dms(), + config.isLevelingDM() + ) + "\n"; + + text += get( + s -> s.levels().leveling().config().message(), + config.getLevelingMessage() == null ? "none" : config.getLevelingMessage() + ) + "\n"; + + text += get( + s -> s.levels().leveling().config().background(), + config.getLevelingBackground() == null ? "none" : config.getLevelingBackground() + ) + "\n"; + return text; } } diff --git a/src/main/java/technobot/commands/levels/RankCommand.java b/src/main/java/technobot/commands/levels/RankCommand.java index d997c70..6554727 100644 --- a/src/main/java/technobot/commands/levels/RankCommand.java +++ b/src/main/java/technobot/commands/levels/RankCommand.java @@ -29,6 +29,8 @@ import java.util.NavigableMap; import java.util.TreeMap; +import static technobot.util.localization.Localization.get; + /** * Command that renders and displays a user's rank card. * @@ -67,9 +69,9 @@ public void execute(SlashCommandInteractionEvent event) { if (profile == null) { String text; if (user.getIdLong() == event.getUser().getIdLong()) { - text = "You do not have a rank yet! Send some messages first."; + text = get(s -> s.levels().rank().noRankSelf()); } else { - text = "That user does not have a rank yet!"; + text = get(s -> s.levels().rank().noRankOther()); } event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); return; @@ -185,7 +187,7 @@ public void execute(SlashCommandInteractionEvent event) { event.getHook().sendFile(bytes, "card.png").queue(); } catch (IOException e) { - String text = "An error occurred while trying to access that rankcard!"; + String text = get(s -> s.levels().rank().accessFailure()); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); e.printStackTrace(); } diff --git a/src/main/java/technobot/commands/levels/RankcardCommand.java b/src/main/java/technobot/commands/levels/RankcardCommand.java index 73a2388..a6fb4f2 100644 --- a/src/main/java/technobot/commands/levels/RankcardCommand.java +++ b/src/main/java/technobot/commands/levels/RankcardCommand.java @@ -25,6 +25,8 @@ import java.util.ArrayList; import java.util.List; +import static technobot.util.localization.Localization.get; + /** * Command that allows you to customize your rank card. * @@ -66,7 +68,7 @@ public void execute(SlashCommandInteractionEvent event) { Bson update = null; String text = null; Bson filter = Filters.and(Filters.eq("guild", guild.getIdLong()), Filters.eq("user", user.getIdLong())); - switch(event.getSubcommandName()) { + switch (event.getSubcommandName()) { case "background" -> { try { String urlOption = event.getOption("url").getAsString(); @@ -74,9 +76,9 @@ public void execute(SlashCommandInteractionEvent event) { BufferedImage test = ImageIO.read(url); test.getWidth(); update = Updates.set("background", urlOption); - text = "Successfully updated your background!"; + text = get(s -> s.levels().rankCard().background().success()); } catch (IOException | NullPointerException | OutOfMemoryError e2) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError("Unable to set that URL as your background.")).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels().rankCard().background().failure()))).queue(); return; } } @@ -88,9 +90,10 @@ public void execute(SlashCommandInteractionEvent event) { } Color.decode(color); update = Updates.set("color", color); - text = "Successfully updated your color to **" + color + "**"; + text = get(s -> s.levels().rankCard().color().success(), color); } catch (NumberFormatException e) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError("That is not a valid hex code, please use a valid color.")).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels().rankCard().color().failure()) + )).queue(); return; } } @@ -102,16 +105,16 @@ public void execute(SlashCommandInteractionEvent event) { } Color.decode(accent); update = Updates.set("accent", accent); - text = "Successfully updated your accent color to **" + accent + "**"; + text = get(s -> s.levels().rankCard().accent().success(), accent); } catch (NumberFormatException e) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError("That is not a valid hex code, please use a valid color.")).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels().rankCard().accent().failure()))).queue(); return; } } case "opacity" -> { int opacity = event.getOption("percent").getAsInt(); update = Updates.set("opacity", opacity); - text = "Successfully updated your opacity to **" + opacity + "%**"; + text = get(s -> s.levels().rankCard().opacity(), opacity); } case "reset" -> { List updates = new ArrayList<>(); @@ -120,7 +123,7 @@ public void execute(SlashCommandInteractionEvent event) { updates.add(Updates.set("accent", "#FFFFFF")); updates.add(Updates.set("background", "")); bot.database.leveling.updateOne(filter, updates); - event.getHook().sendMessageEmbeds(EmbedUtils.createDefault("Successfully reset your rank card to default settings!")).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(get(s -> s.levels().rankCard().reset()))).queue(); return; } } diff --git a/src/main/java/technobot/commands/levels/RewardsCommand.java b/src/main/java/technobot/commands/levels/RewardsCommand.java index 2a83466..a7e864b 100644 --- a/src/main/java/technobot/commands/levels/RewardsCommand.java +++ b/src/main/java/technobot/commands/levels/RewardsCommand.java @@ -15,6 +15,8 @@ import java.util.LinkedHashMap; import java.util.Map; +import static technobot.util.localization.Localization.get; + /** * Command that displays leveling rewards. * @@ -39,24 +41,28 @@ public void execute(SlashCommandInteractionEvent event) { .forEachOrdered(x -> rewards.put(x.getKey(), x.getValue())); StringBuilder content = new StringBuilder(); - for (Map.Entry reward : rewards.entrySet()) { + for (Map.Entry reward : rewards.entrySet()) { if (event.getGuild().getRoleById(reward.getKey()) != null) { - content.append("Level ").append(reward.getValue()).append(" ----> <@&").append(reward.getKey()).append(">\n"); + //noinspection StringConcatenationInsideStringBufferAppend + content.append(get( + s -> s.levels().rewards().reward(), + reward.getValue(), reward.getKey() + ) + "").append("\n"); } else { // Remove any deleted roles from database Bson filter = Filters.eq("guild", event.getGuild().getIdLong()); - bot.database.config.updateOne(filter, Updates.unset("rewards."+reward.getKey())); + bot.database.config.updateOne(filter, Updates.unset("rewards." + reward.getKey())); } } if (!content.isEmpty()) { EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setTitle(":crown: Leveling Rewards") + .setTitle(get(s -> s.levels().rewards().title())) .setDescription(content); event.getHook().sendMessageEmbeds(embed.build()).queue(); return; } - event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(EmbedUtils.BLUE_X + " No leveling rewards have been set for this server!")).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(get(s -> s.levels().rewards().noRewards()))).queue(); } } diff --git a/src/main/java/technobot/commands/levels/TopCommand.java b/src/main/java/technobot/commands/levels/TopCommand.java index 8ba5bd8..0552a7f 100644 --- a/src/main/java/technobot/commands/levels/TopCommand.java +++ b/src/main/java/technobot/commands/levels/TopCommand.java @@ -25,6 +25,8 @@ import java.text.DecimalFormat; import java.util.*; +import static technobot.util.localization.Localization.get; + /** * Command that displays various leaderboards. * @@ -36,7 +38,8 @@ public class TopCommand extends Command { private static final String ECONOMY_ICON = "https://images.emojiterra.com/google/noto-emoji/v2.034/512px/1f4b0.png"; private static final String LEVELING_ICON = "https://images.emojiterra.com/twitter/v13.1/512px/1f4c8.png"; private static final String LEADERBOARD_ICON = "https://cdn-icons-png.flaticon.com/512/1657/1657088.png"; - private static final DecimalFormat FORMATTER = new DecimalFormat("#,###");; + private static final DecimalFormat FORMATTER = new DecimalFormat("#,###"); + ; public TopCommand(TechnoBot bot) { super(bot); @@ -66,8 +69,8 @@ public void execute(SlashCommandInteractionEvent event) { if (embeds.isEmpty()) { event.getHook().sendMessageEmbeds(new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setAuthor("Leveling Leaderboard", null, LEVELING_ICON) - .setDescription("Nobody has earned any XP or levels yet!\nSend some messages in chat and use `/rank` to get started!") + .setAuthor(get(s -> s.levels().top().leveling().name()), null, LEVELING_ICON) + .setDescription(get(s -> s.levels().top().leveling().empty())) .build() ).queue(); return; @@ -79,8 +82,8 @@ else if (type.equalsIgnoreCase("Economy")) { if (embeds.isEmpty()) { event.getHook().sendMessageEmbeds(new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setAuthor("Economy Leaderboard", null, ECONOMY_ICON) - .setDescription("Nobody has earned any money yet!\nUse `/work` and `/balance` to get started!") + .setAuthor(get(s -> s.levels().top().economy().name()), null, ECONOMY_ICON) + .setDescription(get(s -> s.levels().top().economy().empty())) .build() ).queue(); return; @@ -88,8 +91,11 @@ else if (type.equalsIgnoreCase("Economy")) { } // Send paginated embeds WebhookMessageAction action = event.getHook().sendMessageEmbeds(embeds.get(0)); - if (embeds.size() == 1) { action.queue(); } - else { ButtonListener.sendPaginatedMenu(String.valueOf(userID), action, embeds); } + if (embeds.size() == 1) { + action.queue(); + } else { + ButtonListener.sendPaginatedMenu(String.valueOf(userID), action, embeds); + } } else { // Top 5 for all leaderboards FindIterable levelLeaderboard = data.levelingHandler.getLeaderboard(); @@ -97,7 +103,7 @@ else if (type.equalsIgnoreCase("Economy")) { EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setAuthor("Guild Leaderboards", null, LEADERBOARD_ICON) + .setAuthor(get(s -> s.levels().top().guild().name()), null, LEADERBOARD_ICON) .setTimestamp(new Date().toInstant()); int counter = 1; @@ -105,37 +111,45 @@ else if (type.equalsIgnoreCase("Economy")) { for (Leveling profile : levelLeaderboard) { if (counter == 6) break; if (counter == 1) levelDesc.append("**"); - levelDesc.append("#").append(counter) - .append(" | <@!") - .append(profile.getUser()) - .append("> XP: `") - .append(FORMATTER.format(profile.getTotalXP())) - .append("`\n"); + levelDesc.append(get( + s -> s.levels().top().leveling().entry(), + counter, + profile.getUser(), + FORMATTER.format(profile.getTotalXP()) + ) + "") + .append("\n"); if (counter == 1) levelDesc.append("**"); counter++; } - levelDesc.append(":sparkles: **More?** `/top leveling`"); - embed.addField("TOP 5 LEVELING :chart_with_upwards_trend:", levelDesc.toString(), true); + levelDesc.append(get(s -> s.levels().top().guild().more(), "leveling") + ""); + embed.addField( + get(s -> s.levels().top().guild().title(), "LEVELING", ":chart_with_upwards_trend:"), + levelDesc.toString(), + true + ); counter = 1; StringBuilder econDesc = new StringBuilder(); for (Economy profile : econLeaderboard) { if (counter == 6) break; if (counter == 1) econDesc.append("**"); - long networth = calculateNetworth(profile.getBalance(), profile.getBank()); - econDesc.append("#").append(counter) - .append(" | <@!") - .append(profile.getUser()) - .append("> ") - .append(data.economyHandler.getCurrency()) - .append(" ") - .append(FORMATTER.format(networth)) + long netWorth = calculateNetWorth(profile.getBalance(), profile.getBank()); + econDesc.append(get( + s -> s.levels().top().economy().entry(), + counter, + profile.getUser(), + FORMATTER.format(netWorth) + ) + "") .append("\n"); if (counter == 1) econDesc.append("**"); counter++; } - econDesc.append(":sparkles: **More?** `/top economy`"); - embed.addField("TOP 5 ECONOMY :moneybag:", econDesc.toString(), true); + econDesc.append(get(s -> s.levels().top().guild().more(), "economy") + ""); + embed.addField( + get(s -> s.levels().top().guild().title(), + "ECONOMY", + "moneybag"), econDesc.toString(), true + ); event.getHook().sendMessageEmbeds(embed.build()).queue(); } @@ -145,8 +159,8 @@ else if (type.equalsIgnoreCase("Economy")) { * Build a economy leaderboard with paginated embeds. * * @param economyHandler the guild's economy handler instance. - * @param guildID the ID of the guild. - * @param userID the ID of the user who ran this command. + * @param guildID the ID of the guild. + * @param userID the ID of the user who ran this command. * @return a list of economy leaderboard pages. */ private List buildEconomyLeaderboard(EconomyHandler economyHandler, long guildID, long userID) { @@ -156,7 +170,6 @@ private List buildEconomyLeaderboard(EconomyHandler economyHandler int currRank = 1; int counter = 0; int page = 1; - String rank = ordinalSuffixOf(economyHandler.getRank(userID)); embed.setAuthor("Economy Leaderboard", null, ECONOMY_ICON); AggregateIterable leaderboard = economyHandler.getLeaderboard(); @@ -164,22 +177,21 @@ private List buildEconomyLeaderboard(EconomyHandler economyHandler if (size % 10 == 0) size--; long maxPages = 1 + (size / 10); for (Economy profile : leaderboard) { - long networth = calculateNetworth(profile.getBalance(), profile.getBank()); + long netWorth = calculateNetWorth(profile.getBalance(), profile.getBank()); if (counter == 0 && page == 1) description.append("**"); - description.append("#").append(currRank) - .append(" | <@!") - .append(profile.getUser()) - .append("> ") - .append(economyHandler.getCurrency()) - .append(" ") - .append(FORMATTER.format(networth)) + description.append(get( + s -> s.levels().top().economy().entry(), + currRank, + profile.getUser(), + FORMATTER.format(netWorth) + ) + "") .append("\n"); if (counter == 0 && page == 1) description.append("**"); counter++; currRank++; if (counter % USERS_PER_PAGE == 0) { embed.setDescription(description); - embed.setFooter("Page "+page+"/"+maxPages + " • Your rank: " + rank); + embed.setFooter("Page " + page + "/" + maxPages + " • Your rank: " + currRank); embeds.add(embed.build()); description = new StringBuilder(); counter = 0; @@ -188,7 +200,7 @@ private List buildEconomyLeaderboard(EconomyHandler economyHandler } if (counter != 0) { embed.setDescription(description); - embed.setFooter("Page "+page+"/"+maxPages + " • Your rank: " + rank); + embed.setFooter("Page " + page + "/" + maxPages + " • Your rank: " + currRank); embeds.add(embed.build()); } return embeds; @@ -198,8 +210,8 @@ private List buildEconomyLeaderboard(EconomyHandler economyHandler * Build a leveling leaderboard with paginated embeds. * * @param levelingHandler the guild's leveling handler instance. - * @param guildID the ID of the guild. - * @param userID the ID of the user who ran this command. + * @param guildID the ID of the guild. + * @param userID the ID of the user who ran this command. * @return a list of leveling leaderboard pages. */ private List buildLevelingLeaderboard(LevelingHandler levelingHandler, long guildID, long userID) { @@ -209,7 +221,6 @@ private List buildLevelingLeaderboard(LevelingHandler levelingHand int currRank = 1; int counter = 0; int page = 1; - String rank = ordinalSuffixOf(levelingHandler.getRank(userID)); embed.setAuthor("Leveling Leaderboard", null, LEVELING_ICON); FindIterable leaderboard = levelingHandler.getLeaderboard(); @@ -218,18 +229,19 @@ private List buildLevelingLeaderboard(LevelingHandler levelingHand long maxPages = 1 + (size / 10); for (Leveling profile : leaderboard) { if (counter == 0 && page == 1) description.append("**"); - description.append("#").append(currRank) - .append(" | <@!") - .append(profile.getUser()) - .append("> XP: `") - .append(FORMATTER.format(profile.getTotalXP())) - .append("`\n"); + description.append(get( + s -> s.levels().top().leveling().entry(), + currRank, + profile.getUser(), + FORMATTER.format(profile.getTotalXP()) + ) + "") + .append("\n"); if (counter == 0 && page == 1) description.append("**"); counter++; currRank++; if (counter % USERS_PER_PAGE == 0) { embed.setDescription(description); - embed.setFooter("Page "+page+"/"+maxPages + " • Your rank: " + rank); + embed.setFooter("Page " + page + "/" + maxPages + " • Your rank: " + currRank); embeds.add(embed.build()); description = new StringBuilder(); counter = 0; @@ -238,7 +250,7 @@ private List buildLevelingLeaderboard(LevelingHandler levelingHand } if (counter != 0) { embed.setDescription(description); - embed.setFooter("Page "+page+"/"+maxPages + " • Your rank: " + rank); + embed.setFooter("Page " + page + "/" + maxPages + " • Your rank: " + currRank); embeds.add(embed.build()); } return embeds; @@ -248,32 +260,12 @@ private List buildLevelingLeaderboard(LevelingHandler levelingHand * Calculates a user's networth, taking into account null values. * * @param balance user's cash balance. - * @param bank user's bank balance. + * @param bank user's bank balance. * @return the user's cash and bank balance combined. */ - private long calculateNetworth(Long balance, Long bank) { + private long calculateNetWorth(Long balance, Long bank) { if (balance == null) balance = 0L; if (bank == null) bank = 0L; return balance + bank; } - - /** - * Get the string ordinal suffix of a number (1st, 2nd, 3rd, 4th, etc). - * - * @param i the number to format. - * @return ordinal suffix of number in string form. - */ - private String ordinalSuffixOf(int i) { - int j = i % 10, k = i % 100; - if (j == 1 && k != 11) { - return i + "st"; - } - if (j == 2 && k != 12) { - return i + "nd"; - } - if (j == 3 && k != 13) { - return i + "rd"; - } - return i + "th"; - } } diff --git a/src/main/java/technobot/commands/staff/RemoveWarnCommand.java b/src/main/java/technobot/commands/staff/RemoveWarnCommand.java index 731cf82..bbf1a95 100644 --- a/src/main/java/technobot/commands/staff/RemoveWarnCommand.java +++ b/src/main/java/technobot/commands/staff/RemoveWarnCommand.java @@ -43,7 +43,7 @@ public void execute(SlashCommandInteractionEvent event) { // Remove warning with this ID int count = data.moderationHandler.removeWarning(idOption.getAsInt()); if (count == 1) { - embed = EmbedUtils.createDefault(GREEN_TICK + " Warning `#"+idOption.getAsInt()+"` has been removed."); + embed = EmbedUtils.createDefault(GREEN_TICK + " Warning `#"+idOption.getAsInt()+"` has been reset."); } else { embed = EmbedUtils.createError("Unable to find a warning with that ID!"); event.replyEmbeds(embed).setEphemeral(true).queue(); @@ -55,9 +55,9 @@ public void execute(SlashCommandInteractionEvent event) { User target = userOption.getAsUser(); int count = data.moderationHandler.clearWarnings(target.getIdLong()); if (count > 1) { - embed = EmbedUtils.createDefault(GREEN_TICK+" "+count+" warnings have been removed for <@!"+target.getId()+">."); + embed = EmbedUtils.createDefault(GREEN_TICK+" "+count+" warnings have been reset for <@!"+target.getId()+">."); } else if (count == 1) { - embed = EmbedUtils.createDefault(GREEN_TICK+" 1 warning has been removed for <@!"+target.getId()+">."); + embed = EmbedUtils.createDefault(GREEN_TICK+" 1 warning has been reset for <@!"+target.getId()+">."); } else { embed = EmbedUtils.createError("That user does not have any warnings!"); event.replyEmbeds(embed).setEphemeral(true).queue(); diff --git a/src/main/java/technobot/handlers/ConfigHandler.java b/src/main/java/technobot/handlers/ConfigHandler.java index 8187791..2e99802 100644 --- a/src/main/java/technobot/handlers/ConfigHandler.java +++ b/src/main/java/technobot/handlers/ConfigHandler.java @@ -64,7 +64,7 @@ public void addAutoRole(long roleID) { /** * Removes an auto role from the local cache and database. * - * @param roleID the ID of the role to be removed from auto-role list. + * @param roleID the ID of the role to be reset from auto-role list. */ public void removeAutoRole(long roleID) { config.removeAutoRole(roleID); diff --git a/src/main/java/technobot/util/localization/Localization.java b/src/main/java/technobot/util/localization/Localization.java index 582dff7..5f61d3c 100644 --- a/src/main/java/technobot/util/localization/Localization.java +++ b/src/main/java/technobot/util/localization/Localization.java @@ -66,6 +66,7 @@ public static String format(String template, Object... args) { .replaceAll("\\{blue_x\\}", EmbedUtils.BLUE_X) .replaceAll("\\{blue_tick\\}", EmbedUtils.BLUE_TICK) .replaceAll("\\{mention\\}", "<@{}>") + .replaceAll("\\{user\\}", "<@!{}>") .replaceAll("\\{role\\}", "<@&{}>") .replaceAll("\\{channel\\}", "<#{}>") .replaceAll("\\{currency\\}", "\uD83E\uDE99"); diff --git a/src/main/java/technobot/util/localization/LocalizationSchema.java b/src/main/java/technobot/util/localization/LocalizationSchema.java index 8aa6c01..29f4848 100644 --- a/src/main/java/technobot/util/localization/LocalizationSchema.java +++ b/src/main/java/technobot/util/localization/LocalizationSchema.java @@ -1,19 +1,20 @@ package technobot.util.localization; +import technobot.util.localization.SchemaUtils.Result; +import technobot.util.localization.SchemaUtils.Value; + public record LocalizationSchema( Automation automation, Economy economy, Fun fun, - Greeting greeting + Greeting greeting, + Levels levels ) { public record Automation(AutoRole autoRole) { - public record AutoRole(Add add, Remove remove, List list) { + public record AutoRole(Add add, Result remove, List list) { public record Add(String higherLevel, String premium, String maxRolesReached, String roleAdded) { } - public record Remove(String roleNotSet, String roleRemoved) { - } - public record List(String noAutoRoles, String premium, String roleCount, String role) { } @@ -59,15 +60,15 @@ public record Work(String timeout, String[] success) { public record Fun( Action action, - Cute cute, + String cute, EightBall eightBall, Emote emote, - Google google, - Joke joke, - Meme meme, - Nsfw nsfw, - Reddit reddit, - Surprise surprise + String google, + String joke, + String meme, + String nsfw, + String reddit, + String surprise ) { public record Action( String failure, @@ -93,9 +94,6 @@ public record Action( ) { } - public record Cute(String failure) { - } - public record EightBall(String tooLong, String[] responses) { } @@ -121,45 +119,85 @@ public record Emote( String yawn ) { } + } - public record Google(String tooLong) { + public record Greeting(Value farewell, Value greet, Greetings greetings, Value joinDm) { + public record Greetings( + String removed, + String set, + String reset, + String welcomeConfig, + String greetingConfig, + String farewellConfig, + String joinDmConfig + ) { } + } - public record Joke(String failure) { - } + public record Levels(Leveling leveling, RankCard rankCard, Rank rank, Rewards rewards, Top top) { + public record Leveling( + Channel channel, + Value message, + Dm dm, + Value mod, + ServerBackground serverBackground, + Mute mute, + Reward reward, + Config config, + String reset, + String resetAll + ) { + public record Channel(String specific, String user) { + } - public record Meme(String failure) { - } + public record Dm(String enable, String disable) { + } - public record Nsfw(String failure) { - } + public record ServerBackground(String set, String reset, String failure) { + } - public record Reddit(String failure) { - } + public record Mute(String enable, String disable) { + } - public record Surprise(String failure) { + public record Reward(String add, String remove, String failure) { + } + + public record Config( + String channel, + String modulus, + String muted, + String dms, + String message, + String background + ) { + } } - } - public record Greeting(Farewell farewell, Greet greet, Greetings greetings, JoinDM joinDm) { - public record Farewell(String set, String removed) { + public record RankCard( + String noRank, + Result background, + Result color, + Result accent, + String opacity, + String reset + ) { } - public record Greet(String set, String removed) { + public record Rank(String noRankSelf, String noRankOther, String accessFailure) { } - public record Greetings( - String removed, - String set, - String reset, - String welcomeConfig, - String greetingConfig, - String farewellConfig, - String joinDmConfig - ) { + public record Rewards(String reward, String title, String noRewards) { } - public record JoinDM(String set, String removed) { + public record Top(Guild guild, Leveling leveling, Economy economy, String footer) { + public record Guild(String name, String more, String title) { + } + + public record Leveling(String name, String empty, String entry) { + } + + public record Economy(String name, String empty, String entry) { + } } } } diff --git a/src/main/java/technobot/util/localization/SchemaUtils.java b/src/main/java/technobot/util/localization/SchemaUtils.java new file mode 100644 index 0000000..6d13364 --- /dev/null +++ b/src/main/java/technobot/util/localization/SchemaUtils.java @@ -0,0 +1,9 @@ +package technobot.util.localization; + +public class SchemaUtils { + public record Result(String success, String failure) { + } + + public record Value(String set, String reset) { + } +} diff --git a/src/main/resources/localization/en_us.json b/src/main/resources/localization/en_us.json index a12bee8..ac4c9e9 100644 --- a/src/main/resources/localization/en_us.json +++ b/src/main/resources/localization/en_us.json @@ -8,8 +8,8 @@ "roleAdded": "{blue_tick} The {role} role will be given to all new members when they join the server." }, "remove": { - "roleNotSet": "The {role} role is not set as an auto-role.", - "roleRemoved": "{blue_x} The {role} role will no longer be given to new members when they join the server." + "failure": "The {role} role is not set as an auto-role.", + "success": "{blue_x} The {role} role will no longer be given to new members when they join the server." }, "list": { "noAutoRoles": "Use `/auto-role add ` to set your first auto role!", @@ -105,29 +105,27 @@ "fun": { "action": { "failure": "I was unable to fetch that emote!", - "bite":"takes a bit out of {}.", - "brofist":"and {} brofist!", + "bite": "takes a bit out of {}.", + "brofist": "and {} brofist!", "cuddle": "cuddles with {}.", - "handhold":"and {} hold hands. How sweet <3", + "handhold": "and {} hold hands. How sweet <3", "hug": "gives {} a big hug!", - "kiss":"kisses {}.", + "kiss": "kisses {}.", "lick": "licks {}... gross!", - "pat":"gives {} a little pat on the head", + "pat": "gives {} a little pat on the head", "pinch": "pinches {}. Ouch!", - "poke":"gives {} a little poke.", + "poke": "gives {} a little poke.", "punch": "punches {} right in the face!", - "slap":"slaps {}. They deserved it!", + "slap": "slaps {}. They deserved it!", "smack": "gives {} a smack they will remember.", - "sorry":"apologizes to {}.", + "sorry": "apologizes to {}.", "stare": "won't stop staring at {}...", - "thumbsup":"gives {} two thumbs up!", + "thumbsup": "gives {} two thumbs up!", "tickle": "tickles {}.", - "wave":"waves at {}. ", + "wave": "waves at {}. ", "wink": "winks at {}." }, - "cute": { - "failure": "I was unable to fetch any cute pictures!" - }, + "cute": "I was unable to fetch any cute pictures!", "eightBall": { "tooLong": "The 8ball doesn't like questions longer than 250 characters!", "responses": [ @@ -168,32 +166,20 @@ "sleep": "falls into a deep sleep.", "yawn": "is getting very sleepy." }, - "google":{ - "tooLong": "google doesn't like questions longer than 250 characters!" - }, - "joke": { - "failure": "I was unable to fetch any jokes!" - }, - "meme": { - "failure": "I was unable to fetch any memes!" - }, - "nsfw": { - "failure": "I was unable to fetch any nsfw pictures!" - }, - "reddit": { - "failure": "I was unable to fetch any posts from that subreddit!" - }, - "surprise": { - "failure": "I was unable to fetch any surprises!" - } + "google": "google doesn't like questions longer than 250 characters!", + "joke": "I was unable to fetch any jokes!", + "meme": "I was unable to fetch any memes!", + "nsfw": "I was unable to fetch any nsfw pictures!", + "reddit": "I was unable to fetch any posts from that subreddit!", + "surprise": "I was unable to fetch any surprises!" }, "greeting": { "farewell": { - "removed": "{blue_x} Farewell message successfully removed!", + "reset": "{blue_x} Farewell message successfully removed!", "set": "{blue_tick} Farewell message successfully updated!" }, "greet": { - "removed": "{blue_x} Greeting message successfully removed!", + "reset": "{blue_x} Greeting message successfully removed!", "set": "{blue_tick} Greeting message successfully updated!" }, "greetings": { @@ -206,8 +192,97 @@ "joinDmConfig": "**Join DM:** {}" }, "joinDm": { - "removed": "{blue_x} Join DM message successfully removed!", + "reset": "{blue_x} Join DM message successfully removed!", "set": "{blue_tick} Join DM message successfully updated!" } + }, + "levels": { + "leveling": { + "channel": { + "specific": "{blue_tick} Leveling messages will now only display in {channel}", + "user": "{blue_tick} Leveling messages will now display in the channel the user levels up in." + }, + "message": { + "set": "{blue_tick} Successfully set a custom level-up message.", + "reset": "{blue_tick} Reset the level-up message to default." + }, + "dm": { + "enable": "{blue_tick} Level-up messages will now be sent through DMs.", + "disable": "{blue_tick} Level-up messages will no longer be sent through DMs." + }, + "mod": { + "set": "{blue_tick} Leveling messages will now only display every **{}** levels.", + "reset": "{blue_tick} Leveling messages have been reset to display every level." + }, + "serverBackground": { + "set": "{blue_tick} Successfully updated the server rank card background!", + "reset": "{blue_tick} Reset the server rank card background to default image!", + "failure": "Unable to set that URL as the server rank card background!" + }, + "mute": { + "enable": "{blue_x} Leveling messages have been muted and will not be displayed!", + "disable": "{blue_tick} Leveling messages will now be displayed!" + }, + "reward": { + "add": "{blue_tick} Users will now receive the {role} role at level **{}**.", + "remove": "{blue_tick Successfully removed the {role} reward role.", + "failure": "I cannot reward that role! Please check my permissions and role position." + }, + "config": { + "channel": "**Level-up Channel:** {}", + "modulus": "**Leveling Modulus:** {}", + "muted": "**Is Muted:** {}", + "dms": "**Level-Up DMs:** {}", + "message": "**Custom Message:** {}", + "background": "**Custom Background:** {}" + }, + "reset": "{blue_tick} All leveling data was reset for **{}**.", + "resetAll": "Would you like to reset the leveling system?\nThis will delete **ALL** data!" + }, + "rankCard": { + "noRank": "You do not have a rank yet! Send some messages first.", + "background": { + "success": "Successfully updated your background!", + "failure": "Unable to set that URL as your background!" + }, + "color": { + "success": "Successfully updated your color to **{}**", + "failure": "That is not a valid hex code, please use a valid color." + }, + "accent": { + "success": "Successfully updated your accent color to **{}**", + "failure": "That is not a valid hex code, please use a valid color." + }, + "opacity": "Successfully updated your opacity to **{}%**", + "reset": "Successfully reset your rank card to default settings!" + }, + "rank": { + "noRankSelf": "You do not have a rank yet! Send some messages first.", + "noRankOther": "That user does not have a rank yet!", + "accessFailure": "An error occurred while trying to access that rank card!" + }, + "rewards": { + "reward": "Level {} ----> {role}", + "title": ":crown: Leveling Rewards", + "noRewards": "{blue_x} No leveling rewards have been set for this server!" + }, + "top": { + "guild": { + "name": "Guild Leaderboards", + "more": ":sparkles: **More?** `/top {}`", + "title": "TOP 5 {} {}" + }, + "leveling": { + "name": "Leveling Leaderboard", + "empty": "Nobody has earned any XP or levels yet!\nSend some messages in chat and use `/rank` to get started!", + "entry": "#{} | {user} XP: `{}`" + }, + "economy": { + "name": "Economy Leaderboard", + "empty": "Nobody has earned any money yet!\nUse `/work` and `/balance` to get started!", + "entry": "#{} | {user} {currency} {}" + }, + "footer": "Page {}/{} • Your rank: #{}" + } } } \ No newline at end of file From 1060a0aaad703543278dc2451e395b7030fefd53 Mon Sep 17 00:00:00 2001 From: theonlytails Date: Mon, 27 Jun 2022 12:48:06 +0300 Subject: [PATCH 04/15] feat(l10n): added a maven plugin to auto-generate the Java schema chore(l10n): switched all the previously migrated commands to the new schema Signed-off-by: theonlytails --- database_init.sh | 0 dependency-reduced-pom.xml | 47 ++++ pom.xml | 27 ++- .../commands/automation/AutoRoleCommand.java | 22 +- .../commands/economy/BalanceCommand.java | 14 +- .../commands/economy/CrimeCommand.java | 6 +- .../commands/economy/DepositCommand.java | 9 +- .../commands/economy/PayCommand.java | 11 +- .../commands/economy/RobCommand.java | 9 +- .../commands/economy/WithdrawCommand.java | 8 +- .../commands/economy/WorkCommand.java | 6 +- .../technobot/commands/fun/ActionCommand.java | 42 ++-- .../technobot/commands/fun/CuteCommand.java | 4 +- .../commands/fun/EightBallCommand.java | 12 +- .../technobot/commands/fun/EmoteCommand.java | 38 ++-- .../technobot/commands/fun/GoogleCommand.java | 4 +- .../technobot/commands/fun/JokeCommand.java | 9 +- .../technobot/commands/fun/MemeCommand.java | 9 +- .../technobot/commands/fun/NsfwCommand.java | 4 +- .../technobot/commands/fun/RedditCommand.java | 4 +- .../commands/fun/SurpriseCommand.java | 4 +- .../commands/greetings/FarewellCommand.java | 6 +- .../commands/greetings/GreetCommand.java | 6 +- .../commands/greetings/GreetingsCommand.java | 16 +- .../commands/greetings/JoinDMCommand.java | 6 +- .../commands/levels/LevelingCommand.java | 55 ++--- .../commands/levels/RankCommand.java | 8 +- .../commands/levels/RankcardCommand.java | 18 +- .../commands/levels/RewardsCommand.java | 8 +- .../technobot/commands/levels/TopCommand.java | 46 ++-- .../handlers/economy/EconomyHandler.java | 6 +- .../handlers/economy/EconomyLocalization.java | 32 +-- .../util/{localization => }/Localization.java | 18 +- .../util/localization/LocalizationSchema.java | 203 ------------------ .../util/localization/SchemaUtils.java | 9 - 35 files changed, 299 insertions(+), 427 deletions(-) mode change 100644 => 100755 database_init.sh create mode 100644 dependency-reduced-pom.xml rename src/main/java/technobot/util/{localization => }/Localization.java (85%) delete mode 100644 src/main/java/technobot/util/localization/LocalizationSchema.java delete mode 100644 src/main/java/technobot/util/localization/SchemaUtils.java diff --git a/database_init.sh b/database_init.sh old mode 100644 new mode 100755 diff --git a/dependency-reduced-pom.xml b/dependency-reduced-pom.xml new file mode 100644 index 0000000..edaf8c9 --- /dev/null +++ b/dependency-reduced-pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + technobot + TechnoBot + 1.0 + + + + maven-shade-plugin + 3.3.0 + + + package + + shade + + + + + ${mainClass} + + + + + + + + + + + dv8tion + m2-dv8tion + https://m2.dv8tion.net/releases + + + jitpack.io + https://jitpack.io + + + + 17 + technobot.TechnoBot + 17 + + diff --git a/pom.xml b/pom.xml index 2619855..fe788eb 100644 --- a/pom.xml +++ b/pom.xml @@ -86,7 +86,8 @@ - + ${mainClass} @@ -94,6 +95,30 @@ + + + + org.jsonschema2pojo + jsonschema2pojo-maven-plugin + 1.1.2 + + src/main/resources/localization/en_us.json + technobot.util.localization + false + true + false + false + gson + json + + + + + generate + + + + \ No newline at end of file diff --git a/src/main/java/technobot/commands/automation/AutoRoleCommand.java b/src/main/java/technobot/commands/automation/AutoRoleCommand.java index c3c7853..38122b3 100644 --- a/src/main/java/technobot/commands/automation/AutoRoleCommand.java +++ b/src/main/java/technobot/commands/automation/AutoRoleCommand.java @@ -17,7 +17,7 @@ import java.util.Set; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that sets roles to be given on user join. @@ -51,34 +51,34 @@ public void execute(SlashCommandInteractionEvent event) { Role role = event.getOption("role").getAsRole(); if (role.isManaged() || role.isPublicRole() || role.getPosition() >= event.getGuild().getBotRole().getPosition()) { event.replyEmbeds(EmbedUtils.createError( - get(s -> s.automation().autoRole().add().higherLevel()) + get(s -> s.automation.autoRole.add.higherLevel) )).setEphemeral(true).queue(); return; } if (configHandler.getConfig().getAutoRoles().size() >= 1 && !configHandler.isPremium()) { event.replyEmbeds(EmbedUtils.createError( - get(s -> s.automation().autoRole().add().premium()) + get(s -> s.automation.autoRole.add.premium) )).setEphemeral(true).queue(); return; } if (configHandler.getConfig().getAutoRoles().size() == MAX_AUTO_ROLES) { event.replyEmbeds(EmbedUtils.createError( - get(s -> s.automation().autoRole().add().maxRolesReached()) + get(s -> s.automation.autoRole.add.maxRolesReached) )).setEphemeral(true).queue(); return; } - embed = EmbedUtils.createDefault(get(s -> s.automation().autoRole().add().roleAdded(), role.getId())); + embed = EmbedUtils.createDefault(get(s -> s.automation.autoRole.add.roleAdded, role.getId())); configHandler.addAutoRole(role.getIdLong()); } case "remove" -> { Role role = event.getOption("role").getAsRole(); if (!configHandler.getConfig().getAutoRoles().contains(role.getIdLong())) { event.replyEmbeds(EmbedUtils.createError( - get(s -> s.automation().autoRole().remove().failure(), role.getId()) + get(s -> s.automation.autoRole.remove.failure, role.getId()) )).setEphemeral(true).queue(); return; } - embed = EmbedUtils.createDefault(get(s -> s.automation().autoRole().remove().success(), role.getId())); + embed = EmbedUtils.createDefault(get(s -> s.automation.autoRole.remove.success, role.getId())); if (!configHandler.isPremium()) { configHandler.clearAutoRoles(); } else { @@ -89,19 +89,19 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embedBuilder = new EmbedBuilder().setTitle("Auto Roles").setColor(EmbedColor.DEFAULT.color); Set roles = configHandler.getConfig().getAutoRoles(); if (roles == null || roles.isEmpty()) { - embedBuilder.setDescription(get(s -> s.automation().autoRole().list().noAutoRoles())); + embedBuilder.setDescription(get(s -> s.automation.autoRole.list.noAutoRoles)); } else { int max = configHandler.isPremium() ? MAX_AUTO_ROLES : 1; if (max == 1) { - embedBuilder.appendDescription(get(s -> s.automation().autoRole().list().premium()) + "\n"); + embedBuilder.appendDescription(get(s -> s.automation.autoRole.list.premium) + "\n"); } else { - embedBuilder.appendDescription(get(s -> s.automation().autoRole().list().roleCount(), roles.size()) + "\n"); + embedBuilder.appendDescription(get(s -> s.automation.autoRole.list.roleCount, roles.size()) + "\n"); } int count = 0; for (long roleID : roles) { if (event.getGuild().getRoleById(roleID) != null) { count++; - embedBuilder.appendDescription("\n" + get(s -> s.automation().autoRole().list().role(), count, roleID)); + embedBuilder.appendDescription("\n" + get(s -> s.automation.autoRole.list.role, count, roleID)); if (count == max) break; } } diff --git a/src/main/java/technobot/commands/economy/BalanceCommand.java b/src/main/java/technobot/commands/economy/BalanceCommand.java index 903fe01..930fc26 100644 --- a/src/main/java/technobot/commands/economy/BalanceCommand.java +++ b/src/main/java/technobot/commands/economy/BalanceCommand.java @@ -13,10 +13,8 @@ import technobot.data.cache.Economy; import technobot.handlers.economy.EconomyHandler; import technobot.util.embeds.EmbedColor; -import technobot.util.localization.Localization; -import technobot.util.localization.LocalizationSchema; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that shows your current cash and bank balance on the server. @@ -58,11 +56,11 @@ public void execute(SlashCommandInteractionEvent event) { // Send embed message String currency = economyHandler.getCurrency(); EmbedBuilder embed = new EmbedBuilder() - .setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()) - .setDescription(get(s -> s.economy().balance().leaderboardRank(), economyHandler.getRank(user.getIdLong()))) - .addField(get(s -> s.economy().balance().cash()), currency + " " + EconomyHandler.FORMATTER.format(balance), true) - .addField(get(s -> s.economy().balance().bank()), currency + " " + EconomyHandler.FORMATTER.format(bank), true) - .addField(get(s -> s.economy().balance().total()), currency + " " + EconomyHandler.FORMATTER.format(total), true) + .setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()) + .setDescription(get(s -> s.economy.balance.leaderboardRank, economyHandler.getRank(user.getIdLong()))) + .addField(get(s -> s.economy.balance.cash), currency + " " + EconomyHandler.FORMATTER.format(balance), true) + .addField(get(s -> s.economy.balance.bank), currency + " " + EconomyHandler.FORMATTER.format(bank), true) + .addField(get(s -> s.economy.balance.total), currency + " " + EconomyHandler.FORMATTER.format(total), true) .setColor(EmbedColor.DEFAULT.color); event.replyEmbeds(embed.build()).queue(); } diff --git a/src/main/java/technobot/commands/economy/CrimeCommand.java b/src/main/java/technobot/commands/economy/CrimeCommand.java index 8a03820..a9c1c2a 100644 --- a/src/main/java/technobot/commands/economy/CrimeCommand.java +++ b/src/main/java/technobot/commands/economy/CrimeCommand.java @@ -10,7 +10,7 @@ import technobot.handlers.economy.EconomyReply; import technobot.util.embeds.EmbedColor; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that risks losing money for a greater potential reward. @@ -36,7 +36,7 @@ public void execute(SlashCommandInteractionEvent event) { if (timeout != null && System.currentTimeMillis() < timeout) { // On timeout String timestamp = economyHandler.formatTimeout(timeout); - embed.setDescription(get(s -> s.economy().crime().timeout(), timestamp)); + embed.setDescription(get(s -> s.economy.crime.timeout, timestamp)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); } else { @@ -45,7 +45,7 @@ public void execute(SlashCommandInteractionEvent event) { int color = reply.isSuccess() ? EmbedColor.SUCCESS.color : EmbedColor.ERROR.color; embed.setDescription(reply.getResponse()); embed.setColor(color); - embed.setFooter(get(s -> s.economy().replyId(), reply.getId())); + embed.setFooter(get(s -> s.economy.replyId, reply.getId())); event.replyEmbeds(embed.build()).queue(); } } diff --git a/src/main/java/technobot/commands/economy/DepositCommand.java b/src/main/java/technobot/commands/economy/DepositCommand.java index 1e8c2d3..0efc0ca 100644 --- a/src/main/java/technobot/commands/economy/DepositCommand.java +++ b/src/main/java/technobot/commands/economy/DepositCommand.java @@ -12,9 +12,8 @@ import technobot.data.GuildData; import technobot.handlers.economy.EconomyHandler; import technobot.util.embeds.EmbedColor; -import technobot.util.embeds.EmbedUtils; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that deposits cash into user's bank. @@ -40,7 +39,7 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()); if (balance <= 0) { // Balance is at 0 - embed.setDescription(get(s -> s.economy().deposit().noMoney())); + embed.setDescription(get(s -> s.economy.deposit.noMoney)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -53,7 +52,7 @@ public void execute(SlashCommandInteractionEvent event) { if (amount > balance) { // Amount is higher than balance embed.setDescription(get( - s -> s.economy().deposit().notEnough(), + s -> s.economy.deposit.notEnough, EconomyHandler.FORMATTER.format(balance) )); embed.setColor(EmbedColor.ERROR.color); @@ -67,7 +66,7 @@ public void execute(SlashCommandInteractionEvent event) { // Send embed message embed.setDescription(get( - s -> s.economy().deposit().success(), + s -> s.economy.deposit.success, EconomyHandler.FORMATTER.format(amount) )); embed.setColor(EmbedColor.SUCCESS.color); diff --git a/src/main/java/technobot/commands/economy/PayCommand.java b/src/main/java/technobot/commands/economy/PayCommand.java index fac4c91..a59daa7 100644 --- a/src/main/java/technobot/commands/economy/PayCommand.java +++ b/src/main/java/technobot/commands/economy/PayCommand.java @@ -11,9 +11,8 @@ import technobot.data.GuildData; import technobot.handlers.economy.EconomyHandler; import technobot.util.embeds.EmbedColor; -import technobot.util.embeds.EmbedUtils; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that transfer cash from one user to another. @@ -38,14 +37,14 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()); if (user.getIdLong() == target.getIdLong()) { // Check for invalid target - embed.setDescription(get(s -> s.economy().pay().paySelf())); + embed.setDescription(get(s -> s.economy.pay.paySelf)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; } if (target.isBot()) { // Check if target is a bot - embed.setDescription(get(s -> s.economy().pay().payBots())); + embed.setDescription(get(s -> s.economy.pay.payBots)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -58,7 +57,7 @@ public void execute(SlashCommandInteractionEvent event) { long balance = economyHandler.getBalance(user.getIdLong()); if (amount > balance) { embed.setDescription(get( - s -> s.economy().pay().notEnough(), + s -> s.economy.pay.notEnough, EconomyHandler.FORMATTER.format(balance) )); embed.setColor(EmbedColor.ERROR.color); @@ -71,7 +70,7 @@ public void execute(SlashCommandInteractionEvent event) { // Send embed message embed.setDescription(get( - s -> s.economy().pay().success(), + s -> s.economy.pay.success, target.getId(), EconomyHandler.FORMATTER.format(amount) )); diff --git a/src/main/java/technobot/commands/economy/RobCommand.java b/src/main/java/technobot/commands/economy/RobCommand.java index cd5e7a5..3ed8fa5 100644 --- a/src/main/java/technobot/commands/economy/RobCommand.java +++ b/src/main/java/technobot/commands/economy/RobCommand.java @@ -12,9 +12,8 @@ import technobot.handlers.economy.EconomyHandler; import technobot.handlers.economy.EconomyReply; import technobot.util.embeds.EmbedColor; -import technobot.util.embeds.EmbedUtils; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that steals money from another user. @@ -37,14 +36,14 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()); if (user.getIdLong() == target.getIdLong()) { // Check for invalid target - embed.setDescription(get(s -> s.economy().rob().robSelf())); + embed.setDescription(get(s -> s.economy.rob.robSelf)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; } if (target.isBot()) { // Check if target is a bot - embed.setDescription(get(s -> s.economy().rob().robBots())); + embed.setDescription(get(s -> s.economy.rob.robBots)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -56,7 +55,7 @@ public void execute(SlashCommandInteractionEvent event) { if (timeout != null && System.currentTimeMillis() < timeout) { // On timeout String timestamp = economyHandler.formatTimeout(timeout); - embed.setDescription(get(s -> s.economy().rob().timeout(), timestamp)); + embed.setDescription(get(s -> s.economy.rob.timeout, timestamp)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); } else { diff --git a/src/main/java/technobot/commands/economy/WithdrawCommand.java b/src/main/java/technobot/commands/economy/WithdrawCommand.java index 0570103..ad6d545 100644 --- a/src/main/java/technobot/commands/economy/WithdrawCommand.java +++ b/src/main/java/technobot/commands/economy/WithdrawCommand.java @@ -13,7 +13,7 @@ import technobot.handlers.economy.EconomyHandler; import technobot.util.embeds.EmbedColor; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that withdraws cash from the user's bank. @@ -38,7 +38,7 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()); if (bank <= 0) { // Bank is at 0 - embed.setDescription(get(s -> s.economy().withdraw().noMoney())); + embed.setDescription(get(s -> s.economy.withdraw.noMoney)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -50,7 +50,7 @@ public void execute(SlashCommandInteractionEvent event) { amount = amountOption.getAsLong(); if (amount > bank) { // Amount is higher than balance - embed.setDescription(get(s -> s.economy().withdraw().tooMuch(), bank)); + embed.setDescription(get(s -> s.economy.withdraw.tooMuch, bank)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); return; @@ -61,7 +61,7 @@ public void execute(SlashCommandInteractionEvent event) { economyHandler.withdraw(user.getIdLong(), amount); // Send embed message - embed.setDescription(get(s -> s.economy().withdraw().success(), amount)); + embed.setDescription(get(s -> s.economy.withdraw.success, amount)); embed.setColor(EmbedColor.SUCCESS.color); event.replyEmbeds(embed.build()).queue(); } diff --git a/src/main/java/technobot/commands/economy/WorkCommand.java b/src/main/java/technobot/commands/economy/WorkCommand.java index d752bc5..adefacf 100644 --- a/src/main/java/technobot/commands/economy/WorkCommand.java +++ b/src/main/java/technobot/commands/economy/WorkCommand.java @@ -10,7 +10,7 @@ import technobot.handlers.economy.EconomyReply; import technobot.util.embeds.EmbedColor; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that adds money to your balance. @@ -36,7 +36,7 @@ public void execute(SlashCommandInteractionEvent event) { if (timeout != null && System.currentTimeMillis() < timeout) { // On timeout String timestamp = economyHandler.formatTimeout(timeout); - embed.setDescription(get(s -> s.economy().work().timeout(), timestamp)); + embed.setDescription(get(s -> s.economy.work.timeout, timestamp)); embed.setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); } else { @@ -44,7 +44,7 @@ public void execute(SlashCommandInteractionEvent event) { EconomyReply reply = economyHandler.work(user); embed.setDescription(reply.getResponse()); embed.setColor(EmbedColor.SUCCESS.color); - embed.setFooter(get(s -> s.economy().replyId(), reply.getId())); + embed.setFooter(get(s -> s.economy.replyId, reply.getId())); event.replyEmbeds(embed.build()).queue(); } } diff --git a/src/main/java/technobot/commands/fun/ActionCommand.java b/src/main/java/technobot/commands/fun/ActionCommand.java index 3c95d2a..3bffc40 100644 --- a/src/main/java/technobot/commands/fun/ActionCommand.java +++ b/src/main/java/technobot/commands/fun/ActionCommand.java @@ -17,7 +17,7 @@ import java.io.IOException; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that generates an image to match an emotion with another user @@ -62,25 +62,25 @@ public void execute(SlashCommandInteractionEvent event) { String target = event.getOption("user").getAsUser().getName(); String text = event.getUser().getName() + " " + switch (emote) { - case "bite" -> get(s -> s.fun().action().bite(), target); - case "brofist" -> get(s -> s.fun().action().brofist(), target); - case "cuddle" -> get(s -> s.fun().action().cuddle(), target); - case "handhold" -> get(s -> s.fun().action().handhold(), target); - case "hug" -> get(s -> s.fun().action().hug(), target); - case "kiss" -> get(s -> s.fun().action().kiss(), target); - case "lick" -> get(s -> s.fun().action().lick(), target); - case "pat" -> get(s -> s.fun().action().pat(), target); - case "pinch" -> get(s -> s.fun().action().pinch(), target); - case "poke" -> get(s -> s.fun().action().poke(), target); - case "punch" -> get(s -> s.fun().action().punch(), target); - case "slap" -> get(s -> s.fun().action().slap(), target); - case "smack" -> get(s -> s.fun().action().smack(), target); - case "sorry" -> get(s -> s.fun().action().sorry(), target); - case "stare" -> get(s -> s.fun().action().stare(), target); - case "thumbsup" -> get(s -> s.fun().action().thumbsup(), target); - case "tickle" -> get(s -> s.fun().action().tickle(), target); - case "wave" -> get(s -> s.fun().action().wave(), target); - case "wink" -> get(s -> s.fun().action().wink(), target); + case "bite" -> get(s -> s.fun.action.bite, target); + case "brofist" -> get(s -> s.fun.action.brofist, target); + case "cuddle" -> get(s -> s.fun.action.cuddle, target); + case "handhold" -> get(s -> s.fun.action.handhold, target); + case "hug" -> get(s -> s.fun.action.hug, target); + case "kiss" -> get(s -> s.fun.action.kiss, target); + case "lick" -> get(s -> s.fun.action.lick, target); + case "pat" -> get(s -> s.fun.action.pat, target); + case "pinch" -> get(s -> s.fun.action.pinch, target); + case "poke" -> get(s -> s.fun.action.poke, target); + case "punch" -> get(s -> s.fun.action.punch, target); + case "slap" -> get(s -> s.fun.action.slap, target); + case "smack" -> get(s -> s.fun.action.smack, target); + case "sorry" -> get(s -> s.fun.action.sorry, target); + case "stare" -> get(s -> s.fun.action.stare, target); + case "thumbsup" -> get(s -> s.fun.action.thumbsup, target); + case "tickle" -> get(s -> s.fun.action.tickle, target); + case "wave" -> get(s -> s.fun.action.wave, target); + case "wink" -> get(s -> s.fun.action.wink, target); default -> ""; }; @@ -90,7 +90,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = get(s -> s.fun().action().failure()); + String text = get(s -> s.fun.action.failure); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); } diff --git a/src/main/java/technobot/commands/fun/CuteCommand.java b/src/main/java/technobot/commands/fun/CuteCommand.java index 4e07024..99402f5 100644 --- a/src/main/java/technobot/commands/fun/CuteCommand.java +++ b/src/main/java/technobot/commands/fun/CuteCommand.java @@ -18,7 +18,7 @@ import java.io.IOException; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that generates a cute picture from reddit. @@ -56,7 +56,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = get(s -> s.fun().cute().failure()); + String text = get(s -> s.fun.cute); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } diff --git a/src/main/java/technobot/commands/fun/EightBallCommand.java b/src/main/java/technobot/commands/fun/EightBallCommand.java index 171c516..9a70883 100644 --- a/src/main/java/technobot/commands/fun/EightBallCommand.java +++ b/src/main/java/technobot/commands/fun/EightBallCommand.java @@ -10,11 +10,9 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; -import java.util.Arrays; -import java.util.List; import java.util.concurrent.ThreadLocalRandom; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that generates a cute picture from reddit. @@ -36,18 +34,18 @@ public void execute(SlashCommandInteractionEvent event) { String question = event.getOption("question").getAsString(); if (question.length() > 250) { event.replyEmbeds(EmbedUtils.createError( - get(s -> s.fun().eightBall().tooLong()) + get(s -> s.fun.eightBall.tooLong) )).queue(); return; } - String[] responses = get(s -> s.fun().eightBall().responses()); + var responses = get(s -> s.fun.eightBall.responses); - int index = ThreadLocalRandom.current().nextInt(responses.length); + int index = ThreadLocalRandom.current().nextInt(responses.size()); EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) .setTitle(question) - .setDescription(":8ball: " + responses[index]); + .setDescription(":8ball: " + responses.get(index)); event.replyEmbeds(embed.build()).queue(); } } diff --git a/src/main/java/technobot/commands/fun/EmoteCommand.java b/src/main/java/technobot/commands/fun/EmoteCommand.java index 11b2dff..ac72dde 100644 --- a/src/main/java/technobot/commands/fun/EmoteCommand.java +++ b/src/main/java/technobot/commands/fun/EmoteCommand.java @@ -17,7 +17,7 @@ import java.io.IOException; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that generates an image to match an emotion. @@ -59,24 +59,24 @@ public void execute(SlashCommandInteractionEvent event) { url += emote; String text = event.getUser().getName() + switch (emote) { - case "mad" -> get(s -> s.fun().emote().mad()); - case "blush" -> get(s -> s.fun().emote().blush()); - case "celebrate" -> get(s -> s.fun().emote().celebrate()); - case "clap" -> get(s -> s.fun().emote().clap()); - case "confused" -> get(s -> s.fun().emote().confused()); - case "cry" -> get(s -> s.fun().emote().cry()); - case "dance" -> get(s -> s.fun().emote().dance()); - case "facepalm" -> get(s -> s.fun().emote().facepalm()); - case "happy" -> get(s -> s.fun().emote().happy()); - case "laugh" -> get(s -> s.fun().emote().laugh()); - case "pout" -> get(s -> s.fun().emote().pout()); - case "shrug" -> get(s -> s.fun().emote().shrug()); - case "shy" -> get(s -> s.fun().emote().shy()); - case "sigh" -> get(s -> s.fun().emote().sigh()); - case "slowclap" -> get(s -> s.fun().emote().slowClap()); - case "scared" -> get(s -> s.fun().emote().scared()); - case "sleep" -> get(s -> s.fun().emote().sleep()); - case "yawn" -> get(s -> s.fun().emote().yawn()); + case "mad" -> get(s -> s.fun.emote.mad); + case "blush" -> get(s -> s.fun.emote.blush); + case "celebrate" -> get(s -> s.fun.emote.celebrate); + case "clap" -> get(s -> s.fun.emote.clap); + case "confused" -> get(s -> s.fun.emote.confused); + case "cry" -> get(s -> s.fun.emote.cry); + case "dance" -> get(s -> s.fun.emote.dance); + case "facepalm" -> get(s -> s.fun.emote.facepalm); + case "happy" -> get(s -> s.fun.emote.happy); + case "laugh" -> get(s -> s.fun.emote.laugh); + case "pout" -> get(s -> s.fun.emote.pout); + case "shrug" -> get(s -> s.fun.emote.shrug); + case "shy" -> get(s -> s.fun.emote.shy); + case "sigh" -> get(s -> s.fun.emote.sigh); + case "slowclap" -> get(s -> s.fun.emote.slowClap); + case "scared" -> get(s -> s.fun.emote.scared); + case "sleep" -> get(s -> s.fun.emote.sleep); + case "yawn" -> get(s -> s.fun.emote.yawn); default -> ""; }; diff --git a/src/main/java/technobot/commands/fun/GoogleCommand.java b/src/main/java/technobot/commands/fun/GoogleCommand.java index e8986d9..86c84af 100644 --- a/src/main/java/technobot/commands/fun/GoogleCommand.java +++ b/src/main/java/technobot/commands/fun/GoogleCommand.java @@ -11,7 +11,7 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that googles something for the user. @@ -33,7 +33,7 @@ public void execute(SlashCommandInteractionEvent event) { String question = event.getOption("question").getAsString(); if (question.length() > 250) { event.replyEmbeds(EmbedUtils.createError( - get(s -> s.fun().google().tooLong()) + get(s -> s.fun.google) )).queue(); return; } diff --git a/src/main/java/technobot/commands/fun/JokeCommand.java b/src/main/java/technobot/commands/fun/JokeCommand.java index 4f0cb03..2cd7cbb 100644 --- a/src/main/java/technobot/commands/fun/JokeCommand.java +++ b/src/main/java/technobot/commands/fun/JokeCommand.java @@ -1,7 +1,10 @@ package technobot.commands.fun; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; -import okhttp3.*; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Request; +import okhttp3.Response; import technobot.TechnoBot; import technobot.commands.Category; import technobot.commands.Command; @@ -9,7 +12,7 @@ import java.io.IOException; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that generates a joke from a joke API. @@ -37,7 +40,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = get(s -> s.fun().joke().failure()); + String text = get(s -> s.fun.joke); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } diff --git a/src/main/java/technobot/commands/fun/MemeCommand.java b/src/main/java/technobot/commands/fun/MemeCommand.java index 2c78a9e..1ad8cb2 100644 --- a/src/main/java/technobot/commands/fun/MemeCommand.java +++ b/src/main/java/technobot/commands/fun/MemeCommand.java @@ -5,7 +5,10 @@ import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; -import okhttp3.*; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Request; +import okhttp3.Response; import technobot.TechnoBot; import technobot.commands.Category; import technobot.commands.Command; @@ -16,7 +19,7 @@ import java.io.IOException; import java.util.concurrent.ThreadLocalRandom; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that generates a meme from the r/dankmemes subreddit. @@ -57,7 +60,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = get(s -> s.fun().meme().failure()); + String text = get(s -> s.fun.meme); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } diff --git a/src/main/java/technobot/commands/fun/NsfwCommand.java b/src/main/java/technobot/commands/fun/NsfwCommand.java index ddb5cab..d16500f 100644 --- a/src/main/java/technobot/commands/fun/NsfwCommand.java +++ b/src/main/java/technobot/commands/fun/NsfwCommand.java @@ -18,7 +18,7 @@ import java.io.IOException; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that generates a nsfw picture from reddit. @@ -60,7 +60,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = get(s -> s.fun().nsfw().failure()); + String text = get(s -> s.fun.nsfw); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } diff --git a/src/main/java/technobot/commands/fun/RedditCommand.java b/src/main/java/technobot/commands/fun/RedditCommand.java index ea37736..64ec506 100644 --- a/src/main/java/technobot/commands/fun/RedditCommand.java +++ b/src/main/java/technobot/commands/fun/RedditCommand.java @@ -17,7 +17,7 @@ import java.io.IOException; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that generates a post from various subreddits. @@ -49,7 +49,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = get(s -> s.fun().reddit().failure()); + String text = get(s -> s.fun.reddit); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } diff --git a/src/main/java/technobot/commands/fun/SurpriseCommand.java b/src/main/java/technobot/commands/fun/SurpriseCommand.java index 8d74299..5c55d74 100644 --- a/src/main/java/technobot/commands/fun/SurpriseCommand.java +++ b/src/main/java/technobot/commands/fun/SurpriseCommand.java @@ -14,7 +14,7 @@ import java.util.List; import java.util.concurrent.ThreadLocalRandom; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that generates a link from uselessweb. @@ -41,7 +41,7 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = get(s -> s.fun().surprise().failure()); + String text = get(s -> s.fun.surprise); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } diff --git a/src/main/java/technobot/commands/greetings/FarewellCommand.java b/src/main/java/technobot/commands/greetings/FarewellCommand.java index ced4de5..585eea6 100644 --- a/src/main/java/technobot/commands/greetings/FarewellCommand.java +++ b/src/main/java/technobot/commands/greetings/FarewellCommand.java @@ -12,7 +12,7 @@ import technobot.handlers.GreetingHandler; import technobot.util.embeds.EmbedUtils; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that configures auto farewells. @@ -39,14 +39,14 @@ public void execute(SlashCommandInteractionEvent event) { // Remove farewell message if (farewellOption == null) { greetingHandler.removeFarewell(); - String text = get(s -> s.greeting().farewell().reset()); + String text = get(s -> s.greeting.farewell.reset); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } // Set greeting message greetingHandler.setFarewell(farewellOption.getAsString()); - String text = get(s -> s.greeting().farewell().set()); + String text = get(s -> s.greeting.farewell.set); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } } diff --git a/src/main/java/technobot/commands/greetings/GreetCommand.java b/src/main/java/technobot/commands/greetings/GreetCommand.java index e97369a..c1d3bf7 100644 --- a/src/main/java/technobot/commands/greetings/GreetCommand.java +++ b/src/main/java/technobot/commands/greetings/GreetCommand.java @@ -12,7 +12,7 @@ import technobot.handlers.GreetingHandler; import technobot.util.embeds.EmbedUtils; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that configures auto greetings. @@ -39,14 +39,14 @@ public void execute(SlashCommandInteractionEvent event) { // Remove greeting message if (greetingOption == null) { greetingHandler.removeGreet(); - String text = get(s -> s.greeting().greet().reset()); + String text = get(s -> s.greeting.greet.reset); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } // Set greeting message greetingHandler.setGreet(greetingOption.getAsString()); - String text = get(s -> s.greeting().greet().reset()); + String text = get(s -> s.greeting.greet.reset); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } } diff --git a/src/main/java/technobot/commands/greetings/GreetingsCommand.java b/src/main/java/technobot/commands/greetings/GreetingsCommand.java index e05c86c..7110e46 100644 --- a/src/main/java/technobot/commands/greetings/GreetingsCommand.java +++ b/src/main/java/technobot/commands/greetings/GreetingsCommand.java @@ -18,7 +18,7 @@ import technobot.listeners.ButtonListener; import technobot.util.embeds.EmbedUtils; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that displays and modifies greetings config. @@ -52,12 +52,12 @@ public void execute(SlashCommandInteractionEvent event) { if (channelOption == null) { // Remove welcome channel if not specified greetingHandler.removeChannel(); - text = get(s -> s.greeting().greetings().removed()); + text = get(s -> s.greeting.greetings.removed); } else { // Set welcome channel Long channelID = channelOption.getAsGuildChannel().getIdLong(); greetingHandler.setChannel(channelID); - text = get(s -> s.greeting().greetings().set(), channelID); + text = get(s -> s.greeting.greetings.set, channelID); } } case "config" -> { @@ -66,7 +66,7 @@ public void execute(SlashCommandInteractionEvent event) { return; } case "reset" -> { - text = get(s -> s.greeting().greetings().reset()); + text = get(s -> s.greeting.greetings.reset); WebhookMessageAction action = event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)); ButtonListener.sendResetMenu(event.getUser().getId(), "Greeting", action); return; @@ -83,16 +83,16 @@ public void execute(SlashCommandInteractionEvent event) { */ private String configToString(Greetings greetings) { String text = ""; - text += get(s -> s.greeting().greetings().welcomeConfig(), + text += get(s -> s.greeting.greetings.welcomeConfig, greetings.getWelcomeChannel() == null ? "none" : "<#" + greetings.getWelcomeChannel() + ">") + "\n"; - text += get(s -> s.greeting().greetings().greetingConfig(), + text += get(s -> s.greeting.greetings.greetingConfig, greetings.getGreeting() == null ? "none" : greetings.getGreeting()) + "\n"; - text += get(s -> s.greeting().greetings().farewellConfig(), + text += get(s -> s.greeting.greetings.farewellConfig, greetings.getFarewell() == null ? "none" : greetings.getFarewell()) + "\n"; - text += get(s -> s.greeting().greetings().joinDmConfig(), + text += get(s -> s.greeting.greetings.joinDmConfig, greetings.getJoinDM() == null ? "none" : greetings.getJoinDM()) + "\n"; return text; diff --git a/src/main/java/technobot/commands/greetings/JoinDMCommand.java b/src/main/java/technobot/commands/greetings/JoinDMCommand.java index ace10f8..23948c8 100644 --- a/src/main/java/technobot/commands/greetings/JoinDMCommand.java +++ b/src/main/java/technobot/commands/greetings/JoinDMCommand.java @@ -12,7 +12,7 @@ import technobot.handlers.GreetingHandler; import technobot.util.embeds.EmbedUtils; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that configures auto join DMs. @@ -39,14 +39,14 @@ public void execute(SlashCommandInteractionEvent event) { // Remove farewell message if (farewellOption == null) { greetingHandler.removeJoinDM(); - String text = get(s -> s.greeting().joinDm().reset()); + String text = get(s -> s.greeting.joinDm.reset); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } // Set greeting message greetingHandler.setJoinDM(farewellOption.getAsString()); - String text = get(s -> s.greeting().joinDm().set()); + String text = get(s -> s.greeting.joinDm.set); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } } diff --git a/src/main/java/technobot/commands/levels/LevelingCommand.java b/src/main/java/technobot/commands/levels/LevelingCommand.java index 4311f73..16e6fd4 100644 --- a/src/main/java/technobot/commands/levels/LevelingCommand.java +++ b/src/main/java/technobot/commands/levels/LevelingCommand.java @@ -3,7 +3,10 @@ import com.mongodb.client.model.Filters; import com.mongodb.client.model.Updates; import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.entities.ChannelType; +import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -24,7 +27,7 @@ import java.io.IOException; import java.net.URL; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that displays and modifies leveling config. @@ -75,11 +78,11 @@ public void execute(SlashCommandInteractionEvent event) { long channel = channelOption.getAsGuildChannel().getIdLong(); config.setLevelingChannel(channel); update = Updates.set("leveling_channel", channel); - text = get(s -> s.levels().leveling().channel().specific(), channel); + text = get(s -> s.levels.leveling.channel.specific, channel); } else { config.setLevelingChannel(null); update = Updates.unset("leveling_channel"); - text = get(s -> s.levels().leveling().channel().specific()); + text = get(s -> s.levels.leveling.channel.user); } } case "message" -> { @@ -88,11 +91,11 @@ public void execute(SlashCommandInteractionEvent event) { String msg = messageOption.getAsString(); config.setLevelingMessage(msg); update = Updates.set("leveling_message", msg); - text = get(s -> s.levels().leveling().message().set()); + text = get(s -> s.levels.leveling.message.set); } else { config.setLevelingMessage(null); update = Updates.unset("leveling_message"); - text = get(s -> s.levels().leveling().message().reset()); + text = get(s -> s.levels.leveling.message.reset); } } case "dm" -> { @@ -100,9 +103,9 @@ public void execute(SlashCommandInteractionEvent event) { config.setLevelingDM(isDM); update = Updates.set("leveling_dm", isDM); if (isDM) { - text = get(s -> s.levels().leveling().dm().enable()); + text = get(s -> s.levels.leveling.dm.enable); } else { - text = get(s -> s.levels().leveling().dm().disable()); + text = get(s -> s.levels.leveling.dm.disable); } } case "mod" -> { @@ -110,9 +113,9 @@ public void execute(SlashCommandInteractionEvent event) { int mod = 1; if (modOption != null) { mod = modOption.getAsInt(); - text = get(s -> s.levels().leveling().mod().set(), mod); + text = get(s -> s.levels.leveling.mod.set, mod); } else { - text = get(s -> s.levels().leveling().mod().reset()); + text = get(s -> s.levels.leveling.mod.reset); } config.setLevelingMod(mod); update = Updates.set("leveling_mod", mod); @@ -127,14 +130,14 @@ public void execute(SlashCommandInteractionEvent event) { test.getWidth(); config.setLevelingBackground(urlOption); update = Updates.set("leveling_background", urlOption); - text = get(s -> s.levels().leveling().serverBackground().set()); + text = get(s -> s.levels.leveling.serverBackground.set); } else { config.setLevelingBackground(null); update = Updates.unset("leveling_background"); - text = get(s -> s.levels().leveling().serverBackground().reset()); + text = get(s -> s.levels.leveling.serverBackground.reset); } } catch (IOException | NullPointerException | OutOfMemoryError e2) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels().leveling().serverBackground().failure()))).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels.leveling.serverBackground.failure))).queue(); return; } } @@ -143,9 +146,9 @@ public void execute(SlashCommandInteractionEvent event) { config.setLevelingMute(isMute); update = Updates.set("leveling_mute", isMute); if (isMute) { - text = get(s -> s.levels().leveling().mute().disable()); + text = get(s -> s.levels.leveling.mute.disable); } else { - text = get(s -> s.levels().leveling().mute().enable()); + text = get(s -> s.levels.leveling.mute.enable); } } case "reward" -> { @@ -156,18 +159,18 @@ public void execute(SlashCommandInteractionEvent event) { Role role = event.getGuild().getRoleById(reward); int botPos = event.getGuild().getBotRole().getPosition(); if (role == null || role.getPosition() >= botPos || role.isManaged()) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels().leveling().reward().failure()))).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels.leveling.reward.failure))).queue(); return; } Integer x = config.getRewards().get(reward); if (x != null && x == level) { config.removeReward(reward); update = Updates.unset("rewards." + reward); - text = get(s -> s.levels().leveling().reward().remove(), role); + text = get(s -> s.levels.leveling.reward.remove, role); } else { config.addReward(level, reward); update = Updates.set("rewards." + reward, level); - text = get(s -> s.levels().leveling().reward().add(), role); + text = get(s -> s.levels.leveling.reward.add, role); } } case "config" -> { @@ -178,12 +181,12 @@ public void execute(SlashCommandInteractionEvent event) { case "reset" -> { User user = event.getOption("user").getAsUser(); data.levelingHandler.resetProfile(user.getIdLong()); - text = get(s -> s.levels().leveling().reset(), user.getName()); + text = get(s -> s.levels.leveling.reset, user.getName()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } case "reset-all" -> { - text = get(s -> s.levels().leveling().resetAll()); + text = get(s -> s.levels.leveling.resetAll); WebhookMessageAction action = event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)); ButtonListener.sendResetMenu(event.getUser().getId(), "Leveling", action); return; @@ -202,33 +205,33 @@ public void execute(SlashCommandInteractionEvent event) { private String configToString(Config config) { String text = ""; text += get( - s -> s.levels().leveling().config().channel(), + s -> s.levels.leveling.config.channel, config.getLevelingChannel() == null ? "none" : config.getLevelingChannel() ) + "\n"; text += get( - s -> s.levels().leveling().config().modulus(), + s -> s.levels.leveling.config.modulus, config.getLevelingMod() ) + "\n"; text += get( - s -> s.levels().leveling().config().muted(), + s -> s.levels.leveling.config.muted, config.isLevelingMute() ) + "\n"; text += get( - s -> s.levels().leveling().config().dms(), + s -> s.levels.leveling.config.dms, config.isLevelingDM() ) + "\n"; text += get( - s -> s.levels().leveling().config().message(), + s -> s.levels.leveling.config.message, config.getLevelingMessage() == null ? "none" : config.getLevelingMessage() ) + "\n"; text += get( - s -> s.levels().leveling().config().background(), + s -> s.levels.leveling.config.background, config.getLevelingBackground() == null ? "none" : config.getLevelingBackground() ) + "\n"; diff --git a/src/main/java/technobot/commands/levels/RankCommand.java b/src/main/java/technobot/commands/levels/RankCommand.java index 6554727..84be340 100644 --- a/src/main/java/technobot/commands/levels/RankCommand.java +++ b/src/main/java/technobot/commands/levels/RankCommand.java @@ -29,7 +29,7 @@ import java.util.NavigableMap; import java.util.TreeMap; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that renders and displays a user's rank card. @@ -69,9 +69,9 @@ public void execute(SlashCommandInteractionEvent event) { if (profile == null) { String text; if (user.getIdLong() == event.getUser().getIdLong()) { - text = get(s -> s.levels().rank().noRankSelf()); + text = get(s -> s.levels.rank.noRankSelf); } else { - text = get(s -> s.levels().rank().noRankOther()); + text = get(s -> s.levels.rank.noRankOther); } event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); return; @@ -187,7 +187,7 @@ public void execute(SlashCommandInteractionEvent event) { event.getHook().sendFile(bytes, "card.png").queue(); } catch (IOException e) { - String text = get(s -> s.levels().rank().accessFailure()); + String text = get(s -> s.levels.rank.accessFailure); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); e.printStackTrace(); } diff --git a/src/main/java/technobot/commands/levels/RankcardCommand.java b/src/main/java/technobot/commands/levels/RankcardCommand.java index a6fb4f2..1d2b28e 100644 --- a/src/main/java/technobot/commands/levels/RankcardCommand.java +++ b/src/main/java/technobot/commands/levels/RankcardCommand.java @@ -25,7 +25,7 @@ import java.util.ArrayList; import java.util.List; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that allows you to customize your rank card. @@ -76,9 +76,9 @@ public void execute(SlashCommandInteractionEvent event) { BufferedImage test = ImageIO.read(url); test.getWidth(); update = Updates.set("background", urlOption); - text = get(s -> s.levels().rankCard().background().success()); + text = get(s -> s.levels.rankCard.background.success); } catch (IOException | NullPointerException | OutOfMemoryError e2) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels().rankCard().background().failure()))).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels.rankCard.background.failure))).queue(); return; } } @@ -90,9 +90,9 @@ public void execute(SlashCommandInteractionEvent event) { } Color.decode(color); update = Updates.set("color", color); - text = get(s -> s.levels().rankCard().color().success(), color); + text = get(s -> s.levels.rankCard.color.success, color); } catch (NumberFormatException e) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels().rankCard().color().failure()) + event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels.rankCard.color.failure) )).queue(); return; } @@ -105,16 +105,16 @@ public void execute(SlashCommandInteractionEvent event) { } Color.decode(accent); update = Updates.set("accent", accent); - text = get(s -> s.levels().rankCard().accent().success(), accent); + text = get(s -> s.levels.rankCard.accent.success, accent); } catch (NumberFormatException e) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels().rankCard().accent().failure()))).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createError(get(s -> s.levels.rankCard.accent.failure))).queue(); return; } } case "opacity" -> { int opacity = event.getOption("percent").getAsInt(); update = Updates.set("opacity", opacity); - text = get(s -> s.levels().rankCard().opacity(), opacity); + text = get(s -> s.levels.rankCard.opacity, opacity); } case "reset" -> { List updates = new ArrayList<>(); @@ -123,7 +123,7 @@ public void execute(SlashCommandInteractionEvent event) { updates.add(Updates.set("accent", "#FFFFFF")); updates.add(Updates.set("background", "")); bot.database.leveling.updateOne(filter, updates); - event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(get(s -> s.levels().rankCard().reset()))).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(get(s -> s.levels.rankCard.reset))).queue(); return; } } diff --git a/src/main/java/technobot/commands/levels/RewardsCommand.java b/src/main/java/technobot/commands/levels/RewardsCommand.java index a7e864b..e1a2138 100644 --- a/src/main/java/technobot/commands/levels/RewardsCommand.java +++ b/src/main/java/technobot/commands/levels/RewardsCommand.java @@ -15,7 +15,7 @@ import java.util.LinkedHashMap; import java.util.Map; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that displays leveling rewards. @@ -45,7 +45,7 @@ public void execute(SlashCommandInteractionEvent event) { if (event.getGuild().getRoleById(reward.getKey()) != null) { //noinspection StringConcatenationInsideStringBufferAppend content.append(get( - s -> s.levels().rewards().reward(), + s -> s.levels.rewards.reward, reward.getValue(), reward.getKey() ) + "").append("\n"); } else { @@ -58,11 +58,11 @@ public void execute(SlashCommandInteractionEvent event) { if (!content.isEmpty()) { EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setTitle(get(s -> s.levels().rewards().title())) + .setTitle(get(s -> s.levels.rewards.title)) .setDescription(content); event.getHook().sendMessageEmbeds(embed.build()).queue(); return; } - event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(get(s -> s.levels().rewards().noRewards()))).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(get(s -> s.levels.rewards.noRewards))).queue(); } } diff --git a/src/main/java/technobot/commands/levels/TopCommand.java b/src/main/java/technobot/commands/levels/TopCommand.java index 0552a7f..d317248 100644 --- a/src/main/java/technobot/commands/levels/TopCommand.java +++ b/src/main/java/technobot/commands/levels/TopCommand.java @@ -23,9 +23,11 @@ import technobot.util.embeds.EmbedColor; import java.text.DecimalFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Command that displays various leaderboards. @@ -69,8 +71,8 @@ public void execute(SlashCommandInteractionEvent event) { if (embeds.isEmpty()) { event.getHook().sendMessageEmbeds(new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setAuthor(get(s -> s.levels().top().leveling().name()), null, LEVELING_ICON) - .setDescription(get(s -> s.levels().top().leveling().empty())) + .setAuthor(get(s -> s.levels.top.leveling.name), null, LEVELING_ICON) + .setDescription(get(s -> s.levels.top.leveling.empty)) .build() ).queue(); return; @@ -82,8 +84,8 @@ else if (type.equalsIgnoreCase("Economy")) { if (embeds.isEmpty()) { event.getHook().sendMessageEmbeds(new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setAuthor(get(s -> s.levels().top().economy().name()), null, ECONOMY_ICON) - .setDescription(get(s -> s.levels().top().economy().empty())) + .setAuthor(get(s -> s.levels.top.economy.name), null, ECONOMY_ICON) + .setDescription(get(s -> s.levels.top.economy.empty)) .build() ).queue(); return; @@ -103,7 +105,7 @@ else if (type.equalsIgnoreCase("Economy")) { EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setAuthor(get(s -> s.levels().top().guild().name()), null, LEADERBOARD_ICON) + .setAuthor(get(s -> s.levels.top.guild.name), null, LEADERBOARD_ICON) .setTimestamp(new Date().toInstant()); int counter = 1; @@ -112,7 +114,7 @@ else if (type.equalsIgnoreCase("Economy")) { if (counter == 6) break; if (counter == 1) levelDesc.append("**"); levelDesc.append(get( - s -> s.levels().top().leveling().entry(), + s -> s.levels.top.leveling.entry, counter, profile.getUser(), FORMATTER.format(profile.getTotalXP()) @@ -121,9 +123,9 @@ else if (type.equalsIgnoreCase("Economy")) { if (counter == 1) levelDesc.append("**"); counter++; } - levelDesc.append(get(s -> s.levels().top().guild().more(), "leveling") + ""); + levelDesc.append(get(s -> s.levels.top.guild.more, "leveling") + ""); embed.addField( - get(s -> s.levels().top().guild().title(), "LEVELING", ":chart_with_upwards_trend:"), + get(s -> s.levels.top.guild.title, "LEVELING", ":chart_with_upwards_trend:"), levelDesc.toString(), true ); @@ -135,7 +137,7 @@ else if (type.equalsIgnoreCase("Economy")) { if (counter == 1) econDesc.append("**"); long netWorth = calculateNetWorth(profile.getBalance(), profile.getBank()); econDesc.append(get( - s -> s.levels().top().economy().entry(), + s -> s.levels.top.economy.entry, counter, profile.getUser(), FORMATTER.format(netWorth) @@ -144,9 +146,9 @@ else if (type.equalsIgnoreCase("Economy")) { if (counter == 1) econDesc.append("**"); counter++; } - econDesc.append(get(s -> s.levels().top().guild().more(), "economy") + ""); + econDesc.append(get(s -> s.levels.top.guild.more, "economy") + ""); embed.addField( - get(s -> s.levels().top().guild().title(), + get(s -> s.levels.top.guild.title, "ECONOMY", "moneybag"), econDesc.toString(), true ); @@ -180,7 +182,7 @@ private List buildEconomyLeaderboard(EconomyHandler economyHandler long netWorth = calculateNetWorth(profile.getBalance(), profile.getBank()); if (counter == 0 && page == 1) description.append("**"); description.append(get( - s -> s.levels().top().economy().entry(), + s -> s.levels.top.economy.entry, currRank, profile.getUser(), FORMATTER.format(netWorth) @@ -230,7 +232,7 @@ private List buildLevelingLeaderboard(LevelingHandler levelingHand for (Leveling profile : leaderboard) { if (counter == 0 && page == 1) description.append("**"); description.append(get( - s -> s.levels().top().leveling().entry(), + s -> s.levels.top.leveling.entry, currRank, profile.getUser(), FORMATTER.format(profile.getTotalXP()) @@ -241,7 +243,12 @@ private List buildLevelingLeaderboard(LevelingHandler levelingHand currRank++; if (counter % USERS_PER_PAGE == 0) { embed.setDescription(description); - embed.setFooter("Page " + page + "/" + maxPages + " • Your rank: " + currRank); + embed.setFooter(get( + s -> s.levels.top.footer, + page, + maxPages, + currRank + )); embeds.add(embed.build()); description = new StringBuilder(); counter = 0; @@ -250,7 +257,12 @@ private List buildLevelingLeaderboard(LevelingHandler levelingHand } if (counter != 0) { embed.setDescription(description); - embed.setFooter("Page " + page + "/" + maxPages + " • Your rank: " + currRank); + embed.setFooter(get( + s -> s.levels.top.footer, + page, + maxPages, + currRank + )); embeds.add(embed.build()); } return embeds; diff --git a/src/main/java/technobot/handlers/economy/EconomyHandler.java b/src/main/java/technobot/handlers/economy/EconomyHandler.java index 45f57f7..1a84af0 100644 --- a/src/main/java/technobot/handlers/economy/EconomyHandler.java +++ b/src/main/java/technobot/handlers/economy/EconomyHandler.java @@ -15,7 +15,7 @@ import java.util.Map; import java.util.concurrent.ThreadLocalRandom; -import static technobot.util.localization.Localization.get; +import static technobot.util.Localization.get; /** * Handles the server economy backend. @@ -110,7 +110,7 @@ public EconomyReply rob(long userID, long targetID) { // Rob successful pay(targetID, userID, amountStolen); String response = get( - s -> s.economy().rob().success(), + s -> s.economy.rob.success, EconomyHandler.FORMATTER.format(amountStolen), targetID ); @@ -120,7 +120,7 @@ public EconomyReply rob(long userID, long targetID) { long fine = calculateFine(userID); removeMoney(userID, fine); String response = get( - s -> s.economy().rob().failure(), + s -> s.economy.rob.failure, EconomyHandler.FORMATTER.format(fine), targetID ); diff --git a/src/main/java/technobot/handlers/economy/EconomyLocalization.java b/src/main/java/technobot/handlers/economy/EconomyLocalization.java index e882d23..179daea 100644 --- a/src/main/java/technobot/handlers/economy/EconomyLocalization.java +++ b/src/main/java/technobot/handlers/economy/EconomyLocalization.java @@ -1,11 +1,11 @@ package technobot.handlers.economy; -import technobot.util.localization.Localization; -import technobot.util.localization.LocalizationSchema; +import technobot.util.Localization; +import java.util.List; import java.util.concurrent.ThreadLocalRandom; -import static technobot.util.localization.Localization.format; +import static technobot.util.Localization.format; /** * Handles localized responses to economy commands. @@ -14,18 +14,18 @@ */ public class EconomyLocalization { - private final String[] work; - private final String[] crimeSuccess; - private final String[] crimeFailure; + private final List work; + private final List crimeSuccess; + private final List crimeFailure; /** * Reads economy responses into local memory */ public EconomyLocalization() { - LocalizationSchema.Economy responses = Localization.get(LocalizationSchema::economy); - work = responses.work().success(); - crimeSuccess = responses.crime().success(); - crimeFailure = responses.crime().failure(); + var responses = Localization.get(s -> s.economy); + work = responses.work.success; + crimeSuccess = responses.crime.success; + crimeFailure = responses.crime.failure; } /** @@ -35,9 +35,9 @@ public EconomyLocalization() { * @return an EconomyReply object with response and ID number. */ public EconomyReply getWorkResponse(long amount) { - int index = ThreadLocalRandom.current().nextInt(work.length); + int index = ThreadLocalRandom.current().nextInt(work.size()); - return new EconomyReply(format(work[index], amount), index + 1); + return new EconomyReply(format(work.get(index), amount), index + 1); } /** @@ -47,10 +47,10 @@ public EconomyReply getWorkResponse(long amount) { * @return an EconomyReply object with response and ID number. */ public EconomyReply getCrimeSuccessResponse(long amount) { - int index = ThreadLocalRandom.current().nextInt(crimeSuccess.length); + int index = ThreadLocalRandom.current().nextInt(crimeSuccess.size()); return new EconomyReply( - format(crimeSuccess[index], amount), + format(crimeSuccess.get(index), amount), index + 1, true ); @@ -63,10 +63,10 @@ public EconomyReply getCrimeSuccessResponse(long amount) { * @return an EconomyReply object with response and ID number. */ public EconomyReply getCrimeFailResponse(long amount) { - int index = ThreadLocalRandom.current().nextInt(crimeFailure.length); + int index = ThreadLocalRandom.current().nextInt(crimeFailure.size()); return new EconomyReply( - format(crimeFailure[index], amount), + format(crimeFailure.get(index), amount), index + 1, false ); diff --git a/src/main/java/technobot/util/localization/Localization.java b/src/main/java/technobot/util/Localization.java similarity index 85% rename from src/main/java/technobot/util/localization/Localization.java rename to src/main/java/technobot/util/Localization.java index 5f61d3c..05d451f 100644 --- a/src/main/java/technobot/util/localization/Localization.java +++ b/src/main/java/technobot/util/Localization.java @@ -1,15 +1,13 @@ -package technobot.util.localization; +package technobot.util; import com.google.gson.Gson; -import kotlin.text.Regex; -import technobot.handlers.economy.EconomyReply; import technobot.util.embeds.EmbedUtils; +import technobot.util.localization.EnUs; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; -import java.util.Locale; import java.util.function.Function; import java.util.regex.Pattern; @@ -29,12 +27,12 @@ public class Localization { * @return The localization value. * @throws NullPointerException If no localization file is found for the locale. */ - public static T get(Function query, Locale locale, Object... args) throws NullPointerException { + public static T get(Function query, Locale locale, Object... args) throws NullPointerException { try (var inputStream = Localization.class.getClassLoader().getResourceAsStream("localization/" + locale.locale + ".json")) { if (inputStream == null) throw new IOException(); var reader = new BufferedReader(new InputStreamReader(inputStream)); - var schema = new Gson().fromJson(reader, LocalizationSchema.class); + var schema = new Gson().fromJson(reader, EnUs.class); final var value = query.apply(schema); if (args.length > 0 && value instanceof String template) { @@ -55,7 +53,7 @@ public static T get(Function query, Locale locale, Ob * @return The localization value. * @throws NullPointerException If no localization file is found for the locale. */ - public static T get(Function query, Object... args) throws NullPointerException { + public static T get(Function query, Object... args) throws NullPointerException { return get(query, currentLocale, args); } @@ -77,9 +75,9 @@ public static String format(String template, Object... args) { switch (Integer.compare(argsList.size(), templateArgsCount)) { case -1 -> { System.err.printf(""" - Too few arguments (%d) provided for template: %s - All unused template slots will not be filled. - """, argsList.size(), template); + Too few arguments (%d) provided for template: %s + All unused template slots will not be filled. + """, argsList.size(), template); for (final var arg : argsList) { template = template.replace("{}", arg); } diff --git a/src/main/java/technobot/util/localization/LocalizationSchema.java b/src/main/java/technobot/util/localization/LocalizationSchema.java deleted file mode 100644 index 29f4848..0000000 --- a/src/main/java/technobot/util/localization/LocalizationSchema.java +++ /dev/null @@ -1,203 +0,0 @@ -package technobot.util.localization; - -import technobot.util.localization.SchemaUtils.Result; -import technobot.util.localization.SchemaUtils.Value; - -public record LocalizationSchema( - Automation automation, - Economy economy, - Fun fun, - Greeting greeting, - Levels levels -) { - public record Automation(AutoRole autoRole) { - public record AutoRole(Add add, Result remove, List list) { - public record Add(String higherLevel, String premium, String maxRolesReached, String roleAdded) { - } - - public record List(String noAutoRoles, String premium, String roleCount, String role) { - } - - } - } - - /** - * Represents list of responses to economy commands. - * - * @author TechnoVision - */ - public record Economy( - String replyId, - Balance balance, - Crime crime, - Deposit deposit, - Pay pay, - Rob rob, - Withdraw withdraw, - Work work - ) { - public record Balance(String leaderboardRank, String cash, String bank, String total) { - } - - public record Crime(String timeout, String[] success, String[] failure) { - } - - public record Deposit(String noMoney, String notEnough, String success) { - } - - public record Pay(String paySelf, String payBots, String notEnough, String success) { - } - - public record Rob(String robSelf, String robBots, String timeout, String failure, String success) { - } - - public record Withdraw(String noMoney, String tooMuch, String success) { - } - - public record Work(String timeout, String[] success) { - } - } - - public record Fun( - Action action, - String cute, - EightBall eightBall, - Emote emote, - String google, - String joke, - String meme, - String nsfw, - String reddit, - String surprise - ) { - public record Action( - String failure, - String bite, - String brofist, - String cuddle, - String handhold, - String hug, - String kiss, - String lick, - String pat, - String pinch, - String poke, - String punch, - String slap, - String smack, - String sorry, - String stare, - String thumbsup, - String tickle, - String wave, - String wink - ) { - } - - public record EightBall(String tooLong, String[] responses) { - } - - public record Emote( - String failure, - String mad, - String blush, - String celebrate, - String clap, - String confused, - String cry, - String dance, - String facepalm, - String happy, - String laugh, - String pout, - String shrug, - String shy, - String sigh, - String slowClap, - String scared, - String sleep, - String yawn - ) { - } - } - - public record Greeting(Value farewell, Value greet, Greetings greetings, Value joinDm) { - public record Greetings( - String removed, - String set, - String reset, - String welcomeConfig, - String greetingConfig, - String farewellConfig, - String joinDmConfig - ) { - } - } - - public record Levels(Leveling leveling, RankCard rankCard, Rank rank, Rewards rewards, Top top) { - public record Leveling( - Channel channel, - Value message, - Dm dm, - Value mod, - ServerBackground serverBackground, - Mute mute, - Reward reward, - Config config, - String reset, - String resetAll - ) { - public record Channel(String specific, String user) { - } - - public record Dm(String enable, String disable) { - } - - public record ServerBackground(String set, String reset, String failure) { - } - - public record Mute(String enable, String disable) { - } - - public record Reward(String add, String remove, String failure) { - } - - public record Config( - String channel, - String modulus, - String muted, - String dms, - String message, - String background - ) { - } - } - - public record RankCard( - String noRank, - Result background, - Result color, - Result accent, - String opacity, - String reset - ) { - } - - public record Rank(String noRankSelf, String noRankOther, String accessFailure) { - } - - public record Rewards(String reward, String title, String noRewards) { - } - - public record Top(Guild guild, Leveling leveling, Economy economy, String footer) { - public record Guild(String name, String more, String title) { - } - - public record Leveling(String name, String empty, String entry) { - } - - public record Economy(String name, String empty, String entry) { - } - } - } -} diff --git a/src/main/java/technobot/util/localization/SchemaUtils.java b/src/main/java/technobot/util/localization/SchemaUtils.java deleted file mode 100644 index 6d13364..0000000 --- a/src/main/java/technobot/util/localization/SchemaUtils.java +++ /dev/null @@ -1,9 +0,0 @@ -package technobot.util.localization; - -public class SchemaUtils { - public record Result(String success, String failure) { - } - - public record Value(String set, String reset) { - } -} From 795d9daa7bf104235f7e8cf37e1c9638720153f6 Mon Sep 17 00:00:00 2001 From: theonlytails Date: Mon, 27 Jun 2022 14:40:30 +0300 Subject: [PATCH 05/15] refactor(economy): converted EconomyReply to record Signed-off-by: theonlytails --- .../handlers/economy/EconomyLocalization.java | 3 +- .../handlers/economy/EconomyReply.java | 29 ++----------------- 2 files changed, 3 insertions(+), 29 deletions(-) diff --git a/src/main/java/technobot/handlers/economy/EconomyLocalization.java b/src/main/java/technobot/handlers/economy/EconomyLocalization.java index 179daea..be6545e 100644 --- a/src/main/java/technobot/handlers/economy/EconomyLocalization.java +++ b/src/main/java/technobot/handlers/economy/EconomyLocalization.java @@ -51,8 +51,7 @@ public EconomyReply getCrimeSuccessResponse(long amount) { return new EconomyReply( format(crimeSuccess.get(index), amount), - index + 1, - true + index + 1 ); } diff --git a/src/main/java/technobot/handlers/economy/EconomyReply.java b/src/main/java/technobot/handlers/economy/EconomyReply.java index fdb3b72..c33f75e 100644 --- a/src/main/java/technobot/handlers/economy/EconomyReply.java +++ b/src/main/java/technobot/handlers/economy/EconomyReply.java @@ -6,33 +6,8 @@ * * @author TechnoVision */ -public class EconomyReply { - - private final String response; - private final int id; - private final boolean isSuccess; - +public record EconomyReply(String response, int id, boolean isSuccess) { public EconomyReply(String response, int id) { - this.response = response; - this.id = id; - this.isSuccess = true; - } - - public EconomyReply(String response, int id, boolean isSuccess) { - this.response = response; - this.id = id; - this.isSuccess = isSuccess; - } - - public String getResponse() { - return response; - } - - public int getId() { - return id; - } - - public boolean isSuccess() { - return isSuccess; + this(response, id, true); } } From 9f35674459bdde667fdd974db8e04c274855ec07 Mon Sep 17 00:00:00 2001 From: theonlytails Date: Mon, 27 Jun 2022 15:07:58 +0300 Subject: [PATCH 06/15] feature(l10n,music): migrated music commands to the new l10n system config(l10n): added an intellij run config file to generate the schema Signed-off-by: theonlytails --- .run/Generate Schema.run.xml | 60 +++++++++++++++++++ .../commands/music/NowPlayingCommand.java | 16 +++-- .../commands/music/PauseCommand.java | 6 +- .../technobot/commands/music/PlayCommand.java | 12 ++-- .../commands/music/QueueCommand.java | 21 ++++--- .../commands/music/RepeatCommand.java | 6 +- .../commands/music/ResumeCommand.java | 6 +- .../technobot/commands/music/SeekCommand.java | 11 +++- .../technobot/commands/music/SkipCommand.java | 10 +++- .../technobot/commands/music/StopCommand.java | 6 +- .../commands/music/VolumeCommand.java | 6 +- src/main/resources/localization/en_us.json | 52 ++++++++++++++++ 12 files changed, 180 insertions(+), 32 deletions(-) create mode 100644 .run/Generate Schema.run.xml diff --git a/.run/Generate Schema.run.xml b/.run/Generate Schema.run.xml new file mode 100644 index 0000000..d0fef1e --- /dev/null +++ b/.run/Generate Schema.run.xml @@ -0,0 +1,60 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/technobot/commands/music/NowPlayingCommand.java b/src/main/java/technobot/commands/music/NowPlayingCommand.java index ca7079f..7744465 100644 --- a/src/main/java/technobot/commands/music/NowPlayingCommand.java +++ b/src/main/java/technobot/commands/music/NowPlayingCommand.java @@ -12,6 +12,8 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that displays the currently playing song. * @@ -32,7 +34,7 @@ public void execute(SlashCommandInteractionEvent event) { // Verify the Music Manager isn't null. if (music == null) { - String text = ":sound: Not currently playing any music!"; + String text = get(s -> s.music.nowPlaying.notPlaying); event.replyEmbeds(EmbedUtils.createDefault(text)).queue(); return; } @@ -40,7 +42,7 @@ public void execute(SlashCommandInteractionEvent event) { // Get currently playing track AudioTrack nowPlaying = music.getQueue().size() > 0 ? music.getQueue().getFirst() : null; if (nowPlaying == null) { - String text = ":sound: Not currently playing any music!"; + String text = get(s -> s.music.nowPlaying.notPlaying); event.replyEmbeds(EmbedUtils.createDefault(text)).queue(); return; } @@ -62,10 +64,14 @@ public void execute(SlashCommandInteractionEvent event) { event.replyEmbeds( new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setTitle("Now Playing :musical_note: ") + .setTitle(get(s -> s.music.nowPlaying.title)) .setDescription("[" + nowPlaying.getInfo().title + "](" + nowPlaying.getInfo().uri + ")") - .addField("Position", progressBar, false) - .addField("Progress", "%s / %s".formatted(trackStart, trackEnd), false) + .addField(get(s -> s.music.nowPlaying.positionTitle), progressBar, false) + .addField( + get(s -> s.music.nowPlaying.progressTitle), + get(s -> s.music.nowPlaying.progress, trackStart, trackEnd), + false + ) .build() ).queue(); } diff --git a/src/main/java/technobot/commands/music/PauseCommand.java b/src/main/java/technobot/commands/music/PauseCommand.java index 539c213..e2afa04 100644 --- a/src/main/java/technobot/commands/music/PauseCommand.java +++ b/src/main/java/technobot/commands/music/PauseCommand.java @@ -7,6 +7,8 @@ import technobot.handlers.MusicHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that pauses music player. * @@ -28,10 +30,10 @@ public void execute(SlashCommandInteractionEvent event) { if (music == null) return; if (music.isPaused()) { - String text = "The player is already paused!"; + String text = get(s -> s.music.pause.failure); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } else { - String text = ":pause_button: Paused the music player!"; + String text = get(s -> s.music.pause.success); music.pause(); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } diff --git a/src/main/java/technobot/commands/music/PlayCommand.java b/src/main/java/technobot/commands/music/PlayCommand.java index f66aafe..27eb1d1 100644 --- a/src/main/java/technobot/commands/music/PlayCommand.java +++ b/src/main/java/technobot/commands/music/PlayCommand.java @@ -13,6 +13,8 @@ import java.net.MalformedURLException; import java.net.URL; +import static technobot.util.Localization.get; + /** * Command that searches and plays music. * @@ -38,14 +40,14 @@ public void execute(SlashCommandInteractionEvent event) { // Check if member is in the right voice channel AudioChannel channel = event.getMember().getVoiceState().getChannel(); if (music.getPlayChannel() != channel) { - String text = "You are not in the same voice channel as TechnoBot!"; + String text = get(s -> s.music.play.differentChannel); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); return; } // Cannot have more than 100 songs in the queue if (music.getQueue().size() >= 100) { - String text = "You cannot queue more than 100 songs!"; + String text = get(s -> s.music.play.tooManySongs); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); return; } @@ -57,13 +59,13 @@ public void execute(SlashCommandInteractionEvent event) { // Check for real URL url = new URL(song).toString(); } catch (MalformedURLException e) { - // Else search youtube using args + // Else search YouTube using args url = "ytsearch:" + song; music.setLogChannel(event.getTextChannel()); bot.musicListener.addTrack(event, url); return; } - // Search youtube if using a soundcloud link + // Search YouTube if using a soundcloud link if (url.contains("https://soundcloud.com/")) { String[] contents = url.split("/"); url = "ytsearch:" + contents[3] + "/" + contents[4]; @@ -72,7 +74,7 @@ public void execute(SlashCommandInteractionEvent event) { music.setLogChannel(event.getTextChannel()); bot.musicListener.addTrack(event, url); } catch (IndexOutOfBoundsException e) { - String text = "Please specify a song a to play."; + String text = get(s -> s.music.play.specifySong); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } } diff --git a/src/main/java/technobot/commands/music/QueueCommand.java b/src/main/java/technobot/commands/music/QueueCommand.java index ddf7942..7bdb57a 100644 --- a/src/main/java/technobot/commands/music/QueueCommand.java +++ b/src/main/java/technobot/commands/music/QueueCommand.java @@ -21,6 +21,8 @@ import java.util.LinkedList; import java.util.List; +import static technobot.util.Localization.get; + /** * Command that displays an embed to showcases the music queue. * @@ -43,7 +45,7 @@ public void execute(SlashCommandInteractionEvent event) { // Check if queue is null or empty if (music == null || music.getQueue().isEmpty()) { - String text = ":sound: There are no songs in the queue!"; + String text = get(s -> s.music.queue.empty); event.replyEmbeds(EmbedUtils.createDefault(text)).queue(); return; } @@ -70,7 +72,7 @@ public void execute(SlashCommandInteractionEvent event) { List embeds = new ArrayList<>(); EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setTitle("Music Queue :musical_note:"); + .setTitle(get(s -> s.music.queue.title)); // Calculate total playlist length long queueTime = 0; @@ -78,20 +80,25 @@ public void execute(SlashCommandInteractionEvent event) { queueTime += track.getInfo().length; } String total = MusicListener.formatTrackLength(queueTime); - String song = "Song"; - if (queueSize >= 3) { song += "s";} - String footer = queueSize > 1 ? String.format("**%s %s in Queue | %s Total Length**", queueSize - 1, song, total) : ""; + String song = queueSize < 3 + ? get(s -> s.music.queue.song) + : get(s -> s.music.queue.songPlural); + + String footer = queueSize > 1 ? get( + s -> s.music.queue.footer, + queueSize - 1, song, total + ) : ""; for (AudioTrack track : queue) { AudioTrackInfo trackInfo = track.getInfo(); if (count == 0) { //Current playing track - description.append("__Now Playing:__\n"); + description.append(get(s -> s.music.queue.nowPlaying) + "\n"); description.append(String.format("[%s](%s) | ", trackInfo.title, trackInfo.uri)); description.append(String.format("`%s`\n\n", MusicListener.formatTrackLength(trackInfo.length))); count++; continue; } else if (count == 1) { //Header for queue - description.append("__Up Next:__\n"); + description.append(get(s -> s.music.queue.upNext) + "\n"); } //Rest of the queue description.append(String.format("`%s.` [%s](%s) | ", count, trackInfo.title, trackInfo.uri)); diff --git a/src/main/java/technobot/commands/music/RepeatCommand.java b/src/main/java/technobot/commands/music/RepeatCommand.java index a68c209..de6afaf 100644 --- a/src/main/java/technobot/commands/music/RepeatCommand.java +++ b/src/main/java/technobot/commands/music/RepeatCommand.java @@ -7,6 +7,8 @@ import technobot.handlers.MusicHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that toggles repeat mode for music queue. * @@ -30,9 +32,9 @@ public void execute(SlashCommandInteractionEvent event) { music.loop(); String text; if (music.isLoop()) { - text = ":repeat_one: Loop Enabled!"; + text = get(s -> s.music.repeat.enabled); } else { - text = ":repeat_one: Loop Disabled!"; + text = get(s -> s.music.repeat.disabled); } event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } diff --git a/src/main/java/technobot/commands/music/ResumeCommand.java b/src/main/java/technobot/commands/music/ResumeCommand.java index bac877f..e8d80d8 100644 --- a/src/main/java/technobot/commands/music/ResumeCommand.java +++ b/src/main/java/technobot/commands/music/ResumeCommand.java @@ -7,6 +7,8 @@ import technobot.handlers.MusicHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that un-pauses music player. * @@ -29,10 +31,10 @@ public void execute(SlashCommandInteractionEvent event) { if (music.isPaused()) { music.unpause(); - String text = ":play_pause: Resuming the music player!"; + String text = get(s -> s.music.resume.success); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } else { - String text = "The player is not paused!"; + String text = get(s -> s.music.resume.failure); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } } diff --git a/src/main/java/technobot/commands/music/SeekCommand.java b/src/main/java/technobot/commands/music/SeekCommand.java index d317913..1ffb951 100644 --- a/src/main/java/technobot/commands/music/SeekCommand.java +++ b/src/main/java/technobot/commands/music/SeekCommand.java @@ -10,6 +10,8 @@ import technobot.listeners.MusicListener; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that jumps to a specified position in the current track. * @@ -51,19 +53,22 @@ public void execute(SlashCommandInteractionEvent event) { // Make sure pos is not longer than track if (pos >= music.getQueue().getFirst().getDuration()) { - String text = "Time cannot be longer than the song!"; + String text = get(s -> s.music.seek.tooLong); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); return; } // Set position and send message music.seek(pos); - String text = ":fast_forward: Set position to `" + MusicListener.formatTrackLength(pos) + "`"; + String text = get( + s -> s.music.seek.success, + MusicListener.formatTrackLength(pos) + ); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } catch ( NumberFormatException | ArrayIndexOutOfBoundsException e) { // Invalid timestamps - String text = "That is not a valid timestamp!"; + String text = get(s -> s.music.seek.invalidTimestamp); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } } diff --git a/src/main/java/technobot/commands/music/SkipCommand.java b/src/main/java/technobot/commands/music/SkipCommand.java index d73fbba..da5e95b 100644 --- a/src/main/java/technobot/commands/music/SkipCommand.java +++ b/src/main/java/technobot/commands/music/SkipCommand.java @@ -9,6 +9,8 @@ import technobot.handlers.MusicHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that skips the current song. * @@ -29,9 +31,13 @@ public void execute(SlashCommandInteractionEvent event) { if (music == null) return; music.skipTrack(); - WebhookMessageAction action = event.getHook().sendMessage(":fast_forward: Skipping..."); + WebhookMessageAction action = event.getHook().sendMessage( + get(s -> s.music.skip.skipping) + "" + ); if (music.getQueue().size() == 1) { - action = action.addEmbeds(EmbedUtils.createDefault(":sound: The music queue is now empty!")); + action = action.addEmbeds(EmbedUtils.createDefault( + get(s -> s.music.skip.queueEmpty) + )); } action.queue(); } diff --git a/src/main/java/technobot/commands/music/StopCommand.java b/src/main/java/technobot/commands/music/StopCommand.java index 63922b0..7f24db7 100644 --- a/src/main/java/technobot/commands/music/StopCommand.java +++ b/src/main/java/technobot/commands/music/StopCommand.java @@ -8,6 +8,8 @@ import technobot.handlers.MusicHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that clears the music queue and stops music * @@ -26,11 +28,11 @@ public StopCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { MusicHandler musicHandler = GuildData.get(event.getGuild()).musicHandler; if (musicHandler == null || musicHandler.getQueue().isEmpty()) { - String text = "The music player is already stopped!"; + String text = get(s -> s.music.stop.failure); event.replyEmbeds(EmbedUtils.createError(text)).queue(); } else { musicHandler.stop(); - String text = EmbedUtils.BLUE_TICK + " Stopped the music player!"; + String text = get(s -> s.music.stop.success); event.replyEmbeds(EmbedUtils.createDefault(text)).queue(); } } diff --git a/src/main/java/technobot/commands/music/VolumeCommand.java b/src/main/java/technobot/commands/music/VolumeCommand.java index 0539029..52ac661 100644 --- a/src/main/java/technobot/commands/music/VolumeCommand.java +++ b/src/main/java/technobot/commands/music/VolumeCommand.java @@ -10,6 +10,8 @@ import technobot.handlers.MusicHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that changes volume of the music player. * @@ -39,12 +41,12 @@ public void execute(SlashCommandInteractionEvent event) { throw new NumberFormatException(); } music.setVolume(volume); - String text = String.format(":loud_sound: Set volume to %s%%", volume); + String text = get(s -> s.music.volume.success, volume); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return; } catch (@NotNull NumberFormatException | ArrayIndexOutOfBoundsException ignored) {} - String text = "You must specify a volume between 0-100"; + String text = get(s -> s.music.volume.failure); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } } diff --git a/src/main/resources/localization/en_us.json b/src/main/resources/localization/en_us.json index ac4c9e9..e687b8a 100644 --- a/src/main/resources/localization/en_us.json +++ b/src/main/resources/localization/en_us.json @@ -284,5 +284,57 @@ }, "footer": "Page {}/{} • Your rank: #{}" } + }, + "music": { + "nowPlaying": { + "notPlaying": ":sound: Not currently playing any music!", + "title": "Now Playing :musical_note:", + "positionTitle": "Position", + "progressTitle": "Progress", + "progress": "{} / {}" + }, + "pause": { + "success": ":pause_button: Paused the music player!", + "failure": "The player is already paused!" + }, + "play": { + "differentChannel": "You are not in the same voice channel as TechnoBot!", + "tooManySongs": "You cannot queue more than 100 songs!", + "specifySong": "Please specify a song to play." + }, + "queue": { + "empty": ":sound: There are no songs in the queue!", + "title": "Music Queue :musical_note:", + "song": "Song", + "songPlural": "Songs", + "footer": "**{} {} in Queue | {} Total Length**", + "nowPlaying": "__Now Playing:__", + "upNext": "__Up Next:__" + }, + "repeat": { + "enabled": ":repeat_one: Loop Enabled!", + "disabled": ":repeat_one: Loop Disabled!" + }, + "resume": { + "success": ":play_pause: Resuming the music player!", + "failure": "The player is not paused!" + }, + "seek": { + "success": ":fast_forward: Set position to `{}`", + "tooLong": "Time cannot be longer than the song!", + "invalidTimestamp": "That is not a valid timestamp!" + }, + "skip": { + "skipping": ":fast_forward: Skipping...", + "queueEmpty": ":sound: The music queue is now empty!" + }, + "stop": { + "success": "{blue_tick} Stopped the music player!", + "failure": "The music player is already stopped!" + }, + "volume": { + "success": ":loud_sound: Set volume to {}%", + "failure": "You must specify a volume between 0 and 100!" + } } } \ No newline at end of file From a47dd939dad5c010a63a8bdca2869f953f0828a7 Mon Sep 17 00:00:00 2001 From: theonlytails Date: Mon, 27 Jun 2022 15:16:37 +0300 Subject: [PATCH 07/15] feature(l10n,music): migrated the music listener to the new l10n system Signed-off-by: theonlytails --- .../technobot/listeners/MusicListener.java | 47 +++++++++++++------ src/main/resources/localization/en_us.json | 12 +++++ 2 files changed, 44 insertions(+), 15 deletions(-) diff --git a/src/main/java/technobot/listeners/MusicListener.java b/src/main/java/technobot/listeners/MusicListener.java index 4ed639b..a51ef52 100644 --- a/src/main/java/technobot/listeners/MusicListener.java +++ b/src/main/java/technobot/listeners/MusicListener.java @@ -8,8 +8,10 @@ import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.events.guild.voice.GuildVoiceJoinEvent; +import net.dv8tion.jda.api.entities.AudioChannel; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent; import net.dv8tion.jda.api.events.guild.voice.GuildVoiceMoveEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; @@ -27,6 +29,8 @@ import java.util.Objects; import java.util.concurrent.TimeUnit; +import static technobot.util.Localization.get; + /** * Module for music player backend and voice channel events. * @@ -75,7 +79,7 @@ public MusicHandler getMusic(@NotNull SlashCommandInteractionEvent event, boolea GuildData settings = GuildData.get(event.getGuild()); // Check if user is in voice channel if (!inChannel(Objects.requireNonNull(event.getMember()))) { - String text = "Please connect to a voice channel first!"; + String text = get(s -> s.music.listener.connect); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); return null; } @@ -88,13 +92,13 @@ public MusicHandler getMusic(@NotNull SlashCommandInteractionEvent event, boolea // Check if music is playing in this guild if (!skipQueueCheck) { if (settings.musicHandler == null || settings.musicHandler.getQueue().isEmpty()) { - String text = ":sound: There are no songs in the queue!"; + String text = get(s -> s.music.listener.queueEmpty); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); return null; } // Check if member is in the right voice channel if (settings.musicHandler.getPlayChannel() != channel) { - String text = "You are not in the same voice channel as TechnoBot!"; + String text = get(s -> s.music.listener.differentChannel); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); return null; } @@ -133,8 +137,8 @@ public boolean inChannel(@NotNull Member member) { /** * Add a track to the specified guild. * - * @param event A slash command event. - * @param url The track URL. + * @param event A slash command event. + * @param url The track URL. */ public void addTrack(SlashCommandInteractionEvent event, String url) { MusicHandler music = GuildData.get(event.getGuild()).musicHandler; @@ -143,10 +147,11 @@ public void addTrack(SlashCommandInteractionEvent event, String url) { // Check for SSRF vulnerability with whitelist try { boolean isWhitelisted = SecurityUtils.isUrlWhitelisted(url); - if(!isWhitelisted) { + if (!isWhitelisted) { url = ""; } - } catch(MalformedURLException ignored) {} + } catch (MalformedURLException ignored) { + } playerManager.loadItem(url, new AudioLoadResultHandler() { @Override @@ -159,14 +164,23 @@ public void trackLoaded(@NotNull AudioTrack audioTrack) { MessageEmbed embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) .setTitle(audioTrack.getInfo().title, audioTrack.getInfo().uri) - .addField("Song Duration", duration, true) - .addField("Position in Queue", String.valueOf(music.getQueue().size()), true) - .setFooter("Added by " + event.getUser().getAsTag(), event.getUser().getEffectiveAvatarUrl()) + .addField(get(s -> s.music.listener.songDuration), duration, true) + .addField(get(s -> s.music.listener.position), String.valueOf(music.getQueue().size()), true) + .setFooter( + get(s -> s.music.listener.addedBy, event.getUser().getAsTag()), + event.getUser().getEffectiveAvatarUrl() + ) .setThumbnail(thumb) .build(); - event.getHook().sendMessage(EmbedUtils.BLUE_TICK + " **" + audioTrack.getInfo().title + "** successfully added!").addEmbeds(embed).queue(); + event.getHook().sendMessage(get( + s -> s.music.listener.addSong, + audioTrack.getInfo().title + ) + "").addEmbeds(embed).queue(); } else { - event.getHook().sendMessage(EmbedUtils.BLUE_TICK + " **" + audioTrack.getInfo().title + "** successfully added!").queue(); + event.getHook().sendMessage(get( + s -> s.music.listener.addSong, + audioTrack.getInfo().title + ) + "").queue(); } music.enqueue(audioTrack); } @@ -182,7 +196,10 @@ public void playlistLoaded(@NotNull AudioPlaylist audioPlaylist) { // Otherwise load first 100 tracks from playlist int total = audioPlaylist.getTracks().size(); if (total > 100) total = 100; - String msg = ":ballot_box_with_check: Added " + total + " tracks from playlist `" + audioPlaylist.getName() + "`"; + String msg = get( + s -> s.music.listener.addPlaylist, + total, audioPlaylist.getName() + ); event.getHook().sendMessage(msg).queue(); total = music.getQueue().size(); diff --git a/src/main/resources/localization/en_us.json b/src/main/resources/localization/en_us.json index e687b8a..8206790 100644 --- a/src/main/resources/localization/en_us.json +++ b/src/main/resources/localization/en_us.json @@ -286,6 +286,18 @@ } }, "music": { + "listener": { + "connect": "Please connect to a voice channel first!", + "queueEmpty": ":sound: There are no songs in the queue!", + "differentChannel": "You are not in the same voice channel as TechnoBot!", + "songDuration": "Song Duration", + "position": "Position in Queue", + "addedBy": "Added By {}", + "addSong": "{blue_tick} **{}** successfully added!", + "addPlaylist": ":ballot_box_with_check: Added {} tracks from playlist `{}`", + "invalidSong": "That is not a valid song!", + "invalidLink": "That is not a valid link!" + }, "nowPlaying": { "notPlaying": ":sound: Not currently playing any music!", "title": "Now Playing :musical_note:", From 806b48b2c9b7db43e3c0e7a39e4ff91887a301b4 Mon Sep 17 00:00:00 2001 From: theonlytails Date: Tue, 28 Jun 2022 11:25:17 +0300 Subject: [PATCH 08/15] feature(l10n,staff): migrated the staff commands to the new l10n system Signed-off-by: theonlytails --- .../technobot/commands/staff/BanCommand.java | 48 ++++---- .../commands/staff/ClearCommand.java | 6 +- .../technobot/commands/staff/KickCommand.java | 27 +++-- .../technobot/commands/staff/LockCommand.java | 22 ++-- .../technobot/commands/staff/MuteCommand.java | 34 ++++-- .../commands/staff/MuteRoleCommand.java | 18 ++- .../commands/staff/RemoveWarnCommand.java | 24 ++-- .../technobot/commands/staff/RoleCommand.java | 16 ++- .../commands/staff/SetNickCommand.java | 14 ++- .../commands/staff/SlowmodeCommand.java | 32 +++-- .../commands/staff/UnMuteCommand.java | 24 ++-- .../commands/staff/UnbanCommand.java | 11 +- .../commands/staff/UnlockCommand.java | 15 ++- .../technobot/commands/staff/WarnCommand.java | 27 +++-- .../commands/staff/WarningsCommand.java | 40 ++++--- .../technobot/handlers/ModerationHandler.java | 14 ++- src/main/resources/localization/en_us.json | 113 ++++++++++++++++++ 17 files changed, 356 insertions(+), 129 deletions(-) diff --git a/src/main/java/technobot/commands/staff/BanCommand.java b/src/main/java/technobot/commands/staff/BanCommand.java index eeb98f7..be59673 100644 --- a/src/main/java/technobot/commands/staff/BanCommand.java +++ b/src/main/java/technobot/commands/staff/BanCommand.java @@ -17,6 +17,8 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that bans a user from the guild. * @@ -42,7 +44,9 @@ public void execute(SlashCommandInteractionEvent event) { User user = event.getOption("user").getAsUser(); Member member = event.getOption("user").getAsMember(); if (user.getIdLong() == event.getJDA().getSelfUser().getIdLong()) { - event.replyEmbeds(EmbedUtils.createError("Did you seriously expect me to ban myself?")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.ban.banBot) + )).setEphemeral(true).queue(); return; } @@ -50,44 +54,44 @@ public void execute(SlashCommandInteractionEvent event) { Guild guild = event.getGuild(); GuildData data = GuildData.get(guild); if (!data.moderationHandler.canTargetMember(member)) { - event.replyEmbeds(EmbedUtils.createError("This member cannot be banned. I need my role moved higher than theirs.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.ban.tooHighRole) + )).setEphemeral(true).queue(); return; } // Get command line options - OptionMapping reasonOption = event.getOption("reason"); - String reason = reasonOption != null ? reasonOption.getAsString() : "Unspecified"; + String reason = event.getOption( + "reason", + get(s -> s.staff.reasonUnspecified) + "", + OptionMapping::getAsString + ); OptionMapping daysOption = event.getOption("days"); - final boolean isTempBan; - String duration = null; - if (daysOption != null) { - duration = daysOption.getAsInt()+" Days"; - isTempBan = true; - } else { - isTempBan = false; - } + String duration = daysOption != null + ? get(s -> s.staff.ban.duration, daysOption.getAsInt()) + : null; // Start unban timer if temp ban specified - String content = user.getAsTag() + " has been banned"; + String content = get( + s -> s.staff.ban.message, + user.getAsTag(), + daysOption != null ? " for " + duration : "" + ); if (daysOption != null) { - int days = daysOption.getAsInt(); - content += " for " + days + " day"; - if (days > 1) content += "s"; - data.moderationHandler.scheduleUnban(guild, user, days); + data.moderationHandler.scheduleUnban(guild, user, daysOption.getAsInt()); } else if (data.moderationHandler.hasTimedBan(user.getId())) { // Remove timed ban in favor of permanent ban data.moderationHandler.removeBan(user); } // Ban user from guild - String finalDuration = duration; user.openPrivateChannel().queue(privateChannel -> { // Private message user with reason for Ban MessageEmbed msg; - if (isTempBan) { - msg = data.moderationHandler.createCaseMessage(event.getUser().getIdLong(), "Ban", reason, finalDuration, EmbedColor.ERROR.color); + if (daysOption != null) { + msg = data.moderationHandler.createCaseMessage(event.getUser().getIdLong(), get(s -> s.staff.cases.actions.ban), reason, duration, EmbedColor.ERROR.color); } else { - msg = data.moderationHandler.createCaseMessage(event.getUser().getIdLong(), "Ban", reason, EmbedColor.ERROR.color); + msg = data.moderationHandler.createCaseMessage(event.getUser().getIdLong(), get(s -> s.staff.cases.actions.ban), reason, EmbedColor.ERROR.color); } privateChannel.sendMessageEmbeds(msg).queue( message -> guild.ban(user, 7, reason).queue(), @@ -98,7 +102,7 @@ public void execute(SlashCommandInteractionEvent event) { // Send confirmation message event.replyEmbeds(new EmbedBuilder() .setAuthor(content, null, user.getEffectiveAvatarUrl()) - .setDescription("**Reason:** " + reason) + .setDescription(get(s -> s.staff.cases.reason, reason)) .setColor(EmbedColor.DEFAULT.color) .build() ).queue(); diff --git a/src/main/java/technobot/commands/staff/ClearCommand.java b/src/main/java/technobot/commands/staff/ClearCommand.java index b7bda6e..fcaa6b3 100644 --- a/src/main/java/technobot/commands/staff/ClearCommand.java +++ b/src/main/java/technobot/commands/staff/ClearCommand.java @@ -10,6 +10,8 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Purges a channel of a specified number of messages. * @@ -36,12 +38,12 @@ public void execute(SlashCommandInteractionEvent event) { try { // Delete messages and notify user ((TextChannel) event.getChannel()).deleteMessages(messages).queue(result -> { - String text = ":ballot_box_with_check: I have deleted `%d messages!`".formatted(amount); + String text = get(s -> s.staff.clear.success, amount); event.getHook().sendMessage(text).queue(); }); } catch (IllegalArgumentException e) { // Messages were older than 2 weeks - String text = "You cannot clear messages older than 2 weeks!"; + String text = get(s -> s.staff.clear.failure); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } }); diff --git a/src/main/java/technobot/commands/staff/KickCommand.java b/src/main/java/technobot/commands/staff/KickCommand.java index 8fa3659..d4be6b4 100644 --- a/src/main/java/technobot/commands/staff/KickCommand.java +++ b/src/main/java/technobot/commands/staff/KickCommand.java @@ -17,6 +17,8 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that kicks a user from the guild. * @@ -41,26 +43,35 @@ public void execute(SlashCommandInteractionEvent event) { User user = event.getOption("user").getAsUser(); Member target = event.getOption("user").getAsMember(); if (target == null) { - event.replyEmbeds(EmbedUtils.createError("That user is not in this server!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.kick.kickForeign) + )).setEphemeral(true).queue(); return; } else if (target.getIdLong() == event.getJDA().getSelfUser().getIdLong()) { - event.replyEmbeds(EmbedUtils.createError("Do you seriously expect me to kick myself?")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.kick.kickBot) + )).setEphemeral(true).queue(); return; } // Check target role position ModerationHandler moderationHandler = GuildData.get(event.getGuild()).moderationHandler; if (!moderationHandler.canTargetMember(target)) { - event.replyEmbeds(EmbedUtils.createError("This member cannot be kicked. I need my role moved higher than theirs.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.kick.tooHighRole) + )).setEphemeral(true).queue(); return; } // Kick user from guild - OptionMapping reasonOption = event.getOption("reason"); - String reason = reasonOption != null ? reasonOption.getAsString() : "Unspecified"; + String reason = event.getOption( + "reason", + get(s -> s.staff.reasonUnspecified) + "", + OptionMapping::getAsString + ); user.openPrivateChannel().queue(privateChannel -> { // Private message user with reason for kick - MessageEmbed msg = moderationHandler.createCaseMessage(event.getUser().getIdLong(), "Kick", reason, EmbedColor.WARNING.color); + MessageEmbed msg = moderationHandler.createCaseMessage(event.getUser().getIdLong(), get(s -> s.staff.cases.actions.kick), reason, EmbedColor.WARNING.color); privateChannel.sendMessageEmbeds(msg).queue( message -> target.kick(reason).queue(), failure -> target.kick(reason).queue() @@ -69,8 +80,8 @@ public void execute(SlashCommandInteractionEvent event) { // Send confirmation message event.replyEmbeds(new EmbedBuilder() - .setAuthor(user.getAsTag() + " has been kicked", null, user.getEffectiveAvatarUrl()) - .setDescription("**Reason:** " + reason) + .setAuthor(get(s -> s.staff.kick.message, user.getAsTag()), null, user.getEffectiveAvatarUrl()) + .setDescription(get(s -> s.staff.cases.reason, reason)) .setColor(EmbedColor.DEFAULT.color) .build() ).queue(); diff --git a/src/main/java/technobot/commands/staff/LockCommand.java b/src/main/java/technobot/commands/staff/LockCommand.java index 0b2a851..680dd2d 100644 --- a/src/main/java/technobot/commands/staff/LockCommand.java +++ b/src/main/java/technobot/commands/staff/LockCommand.java @@ -2,7 +2,6 @@ import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.ChannelType; -import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -12,6 +11,8 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that prevents users from sending messages in a channel. * @@ -32,19 +33,22 @@ public LockCommand(TechnoBot bot) { @Override public void execute(SlashCommandInteractionEvent event) { - OptionMapping channelOption = event.getOption("channel"); - TextChannel channel; - - if (channelOption != null) { channel = channelOption.getAsTextChannel(); } - else { channel = event.getTextChannel(); } + var channel = event.getOption( + "channel", + event.getTextChannel(), + OptionMapping::getAsTextChannel + ); if (channel == null) { - event.replyEmbeds(EmbedUtils.createError("That is not a valid channel!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.lock.failure) + )).setEphemeral(true).queue(); return; } channel.upsertPermissionOverride(event.getGuild().getPublicRole()).deny(Permission.MESSAGE_SEND).queue(); - String channelString = "<#"+channel.getId()+">"; - event.replyEmbeds(EmbedUtils.createDefault(":lock: "+channelString+" has been locked.")).queue(); + event.replyEmbeds(EmbedUtils.createDefault( + get(s -> s.staff.lock.success, channel.getId()) + )).queue(); } } diff --git a/src/main/java/technobot/commands/staff/MuteCommand.java b/src/main/java/technobot/commands/staff/MuteCommand.java index 6b60ed2..3d7110b 100644 --- a/src/main/java/technobot/commands/staff/MuteCommand.java +++ b/src/main/java/technobot/commands/staff/MuteCommand.java @@ -18,6 +18,8 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that adds a muted role to a user in the guild. * @@ -42,39 +44,48 @@ public void execute(SlashCommandInteractionEvent event) { User user = event.getOption("user").getAsUser(); Member target = event.getOption("user").getAsMember(); if (target == null) { - event.replyEmbeds(EmbedUtils.createError("That user is not in this server!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.mute.muteForeign) + )).setEphemeral(true).queue(); return; } else if (target.getIdLong() == event.getJDA().getSelfUser().getIdLong()) { - event.replyEmbeds(EmbedUtils.createError("Do you seriously expect me to mute myself?")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.mute.muteBot) + )).setEphemeral(true).queue(); return; } // Check target role position ModerationHandler moderationHandler = GuildData.get(event.getGuild()).moderationHandler; if (!moderationHandler.canTargetMember(target)) { - event.replyEmbeds(EmbedUtils.createError("This member cannot be muted. I need my role moved higher than theirs.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.mute.tooHighRole) + )).setEphemeral(true).queue(); return; } // Get command line options - OptionMapping reasonOption = event.getOption("reason"); - String reason = reasonOption != null ? reasonOption.getAsString() : "Unspecified"; + var reason = event.getOption( + "reason", + get(s -> s.staff.reasonUnspecified) + "", + OptionMapping::getAsString + ); // Check that muted role is valid and not already added to user Role muteRole = moderationHandler.getMuteRole(); if (muteRole == null) { - String text = "This server does not have a mute role, use `/mute-role ` to set one or `/mute-role create [name]` to create one."; + String text = get(s -> s.staff.mute.noRole); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); return; } if (target.getRoles().contains(muteRole)) { - String text = "That user is already muted!"; + String text = get(s -> s.staff.mute.alreadyMuted); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); return; } int botPos = event.getGuild().getBotRole().getPosition(); if (muteRole.getPosition() >= botPos) { - event.replyEmbeds(EmbedUtils.createError("This member cannot be muted. I need my role moved higher than the mute role.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError(get(s -> s.staff.mute.tooHighRole))).setEphemeral(true).queue(); return; } @@ -85,12 +96,13 @@ public void execute(SlashCommandInteractionEvent event) { // Private message user with reason for kick MessageEmbed msg = moderationHandler.createCaseMessage(event.getUser().getIdLong(), "Mute", reason, EmbedColor.WARNING.color); privateChannel.sendMessageEmbeds(msg).queue(); - }, fail -> {}); + }, fail -> { + }); // Send confirmation message event.replyEmbeds(new EmbedBuilder() - .setAuthor(user.getAsTag() + " has been muted", null, user.getEffectiveAvatarUrl()) - .setDescription("**Reason:** " + reason) + .setAuthor(get(s -> s.staff.mute.message, user.getAsTag()), null, user.getEffectiveAvatarUrl()) + .setDescription(get(s -> s.staff.cases.reason, reason)) .setColor(EmbedColor.DEFAULT.color) .build() ).queue(); diff --git a/src/main/java/technobot/commands/staff/MuteRoleCommand.java b/src/main/java/technobot/commands/staff/MuteRoleCommand.java index 46023cb..fcc2550 100644 --- a/src/main/java/technobot/commands/staff/MuteRoleCommand.java +++ b/src/main/java/technobot/commands/staff/MuteRoleCommand.java @@ -1,6 +1,6 @@ package technobot.commands.staff; -import net.dv8tion.jda.api.Permission;; +import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.GuildChannel; import net.dv8tion.jda.api.entities.Role; @@ -20,6 +20,10 @@ import java.util.Arrays; import java.util.List; +import static technobot.util.Localization.get; + +; + /** * Command that sets/creates the mute role to give on /mute. * @@ -48,7 +52,9 @@ public void execute(SlashCommandInteractionEvent event) { // Check for admin permissions Role botRole = event.getGuild().getBotRole(); if (!botRole.hasPermission(Permission.ADMINISTRATOR)) { - event.replyEmbeds(EmbedUtils.createError("I am unable to create roles. Please check my permissions and role position.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.muteRole.noPerm) + )).setEphemeral(true).queue(); return; } @@ -58,11 +64,13 @@ public void execute(SlashCommandInteractionEvent event) { // Set existing role as the mute role Role role = event.getOption("role").getAsRole(); if (role.isManaged() || role.isPublicRole()) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError("I cannot set bot/managed roles as the mute role!")).setEphemeral(true).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createError( + get(s -> s.staff.muteRole.botManagedRole) + )).setEphemeral(true).queue(); return; } data.moderationHandler.setMuteRole(role.getIdLong()); - String text = EmbedUtils.BLUE_TICK + " The "+role.getAsMention()+" role will be used for the `mute` command."; + String text = get(s -> s.staff.muteRole.success, role.getAsMention()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } case "create" -> { @@ -87,7 +95,7 @@ public void execute(SlashCommandInteractionEvent event) { channel.getPermissionContainer().getManager().putRolePermissionOverride(roleID, null, denyPerms).queue(); } data.moderationHandler.setMuteRole(roleID); - String text = EmbedUtils.BLUE_TICK + " The "+role.getAsMention()+" role will be used for the `mute` command."; + String text = get(s -> s.staff.muteRole.success, role.getAsMention()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); }); } diff --git a/src/main/java/technobot/commands/staff/RemoveWarnCommand.java b/src/main/java/technobot/commands/staff/RemoveWarnCommand.java index bbf1a95..39bfaf1 100644 --- a/src/main/java/technobot/commands/staff/RemoveWarnCommand.java +++ b/src/main/java/technobot/commands/staff/RemoveWarnCommand.java @@ -13,7 +13,7 @@ import technobot.data.GuildData; import technobot.util.embeds.EmbedUtils; -import static technobot.util.embeds.EmbedUtils.GREEN_TICK; +import static technobot.util.Localization.get; /** * Command that removes a warning by user or id. @@ -43,9 +43,14 @@ public void execute(SlashCommandInteractionEvent event) { // Remove warning with this ID int count = data.moderationHandler.removeWarning(idOption.getAsInt()); if (count == 1) { - embed = EmbedUtils.createDefault(GREEN_TICK + " Warning `#"+idOption.getAsInt()+"` has been reset."); + embed = EmbedUtils.createDefault(get( + s -> s.staff.removeWarn.successId, + idOption.getAsInt() + )); } else { - embed = EmbedUtils.createError("Unable to find a warning with that ID!"); + embed = EmbedUtils.createError( + get(s -> s.staff.removeWarn.failureId) + ); event.replyEmbeds(embed).setEphemeral(true).queue(); return; } @@ -55,18 +60,21 @@ public void execute(SlashCommandInteractionEvent event) { User target = userOption.getAsUser(); int count = data.moderationHandler.clearWarnings(target.getIdLong()); if (count > 1) { - embed = EmbedUtils.createDefault(GREEN_TICK+" "+count+" warnings have been reset for <@!"+target.getId()+">."); - } else if (count == 1) { - embed = EmbedUtils.createDefault(GREEN_TICK+" 1 warning has been reset for <@!"+target.getId()+">."); + embed = EmbedUtils.createDefault(get( + s -> s.staff.removeWarn.successUser, + target.getId() + )); } else { - embed = EmbedUtils.createError("That user does not have any warnings!"); + embed = EmbedUtils.createError(get(s -> s.staff.removeWarn.failureUser)); event.replyEmbeds(embed).setEphemeral(true).queue(); return; } event.replyEmbeds(embed).queue(); } else { // No user or ID specified - event.replyEmbeds(EmbedUtils.createError("You must specify a user or a warning ID!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.removeWarn.failure) + )).setEphemeral(true).queue(); } } } diff --git a/src/main/java/technobot/commands/staff/RoleCommand.java b/src/main/java/technobot/commands/staff/RoleCommand.java index def1f7b..7bafbee 100644 --- a/src/main/java/technobot/commands/staff/RoleCommand.java +++ b/src/main/java/technobot/commands/staff/RoleCommand.java @@ -13,6 +13,8 @@ import technobot.handlers.ModerationHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that gives or removes a role from user. * @@ -40,22 +42,28 @@ public void execute(SlashCommandInteractionEvent event) { Member member = event.getOption("user").getAsMember(); Role role = event.getOption("role").getAsRole(); if (member == null) { - event.replyEmbeds(EmbedUtils.createError("That user is not in your server!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.role.roleForeign) + )).setEphemeral(true).queue(); return; } if (role.isManaged() || role.isPublicRole()) { - event.replyEmbeds(EmbedUtils.createError("I cannot give/remove bot or managed roles!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.role.botManagedRole) + )).setEphemeral(true).queue(); return; } // Check target role position ModerationHandler moderationHandler = GuildData.get(event.getGuild()).moderationHandler; if (!moderationHandler.canTargetMember(member)) { - event.replyEmbeds(EmbedUtils.createError("This member cannot be updated. I need my role moved higher than theirs.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.role.tooHighRole) + )).setEphemeral(true).queue(); return; } - String text = EmbedUtils.GREEN_TICK + " Changed roles for " + member.getEffectiveName() + ", "; + String text = get(s -> s.staff.role.message, member.getEffectiveName()); switch (event.getSubcommandName()) { case "give" -> { text += "**+" + role.getName() + "**"; diff --git a/src/main/java/technobot/commands/staff/SetNickCommand.java b/src/main/java/technobot/commands/staff/SetNickCommand.java index af41d53..9e4a79d 100644 --- a/src/main/java/technobot/commands/staff/SetNickCommand.java +++ b/src/main/java/technobot/commands/staff/SetNickCommand.java @@ -12,6 +12,8 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that changes or resets a user's nickname. * @@ -34,7 +36,9 @@ public SetNickCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { Member target = event.getOption("user").getAsMember(); if (target == null) { - event.replyEmbeds(EmbedUtils.createError("That user is not in your server!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.setNick.nickForeign) + )).setEphemeral(true).queue(); return; } @@ -45,15 +49,17 @@ public void execute(SlashCommandInteractionEvent event) { String originalName = target.getUser().getName(); String name = nickOption.getAsString(); target.modifyNickname(name).queue(); - content = EmbedUtils.GREEN_TICK + " **" + originalName + "**'s nick has been changed to **" + name + "**."; + content = get(s -> s.staff.setNick.set, originalName, name); } else { String name = target.getUser().getName(); target.modifyNickname(name).queue(); - content = EmbedUtils.GREEN_TICK + " **" + name + "**'s nick has been reset."; + content = get(s -> s.staff.setNick.reset, name); } event.replyEmbeds(EmbedUtils.createDefault(content)).queue(); } catch (HierarchyException e) { - event.replyEmbeds(EmbedUtils.createError(" This member cannot be updated. I need my role moved higher than theirs.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.setNick.tooHighRole) + )).setEphemeral(true).queue(); } } } diff --git a/src/main/java/technobot/commands/staff/SlowmodeCommand.java b/src/main/java/technobot/commands/staff/SlowmodeCommand.java index 0646ede..a2d64b3 100644 --- a/src/main/java/technobot/commands/staff/SlowmodeCommand.java +++ b/src/main/java/technobot/commands/staff/SlowmodeCommand.java @@ -15,6 +15,8 @@ import java.time.Duration; import java.time.format.DateTimeParseException; +import static technobot.util.Localization.get; + /** * Command that puts a channel in slowmode with specified time. * @@ -37,7 +39,9 @@ public void execute(SlashCommandInteractionEvent event) { // Prevent slowmode in threads ChannelType type = event.getChannelType(); if (type == ChannelType.GUILD_PUBLIC_THREAD || type == ChannelType.GUILD_NEWS_THREAD || type == ChannelType.GUILD_PRIVATE_THREAD) { - event.replyEmbeds(EmbedUtils.createError("You cannot set slowmode on threads!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.slowMode.failureThread) + )).setEphemeral(true).queue(); return; } @@ -58,21 +62,28 @@ public void execute(SlashCommandInteractionEvent event) { } catch (NumberFormatException e2) { // Disable slowmode event.getTextChannel().getManager().setSlowmode(0).queue(); - event.replyEmbeds(EmbedUtils.createDefault(":stopwatch: Slowmode has been disabled from this channel.")).queue(); + event.replyEmbeds(EmbedUtils.createDefault(get(s -> s.staff.slowMode.disable) + )).queue(); return; } // Set slowmode timer if (time > TextChannel.MAX_SLOWMODE) { - event.replyEmbeds(EmbedUtils.createError("Time should be less than or equal to **6 hours**.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.slowMode.tooHigh) + )).setEphemeral(true).queue(); return; } event.getTextChannel().getManager().setSlowmode(time).queue(); - event.replyEmbeds(EmbedUtils.createDefault(":stopwatch: This channel's slowmode has been set to **"+formatTime(time)+"**.")).queue(); + event.replyEmbeds(EmbedUtils.createDefault( + get(s -> s.staff.slowMode.set, formatTime(time)) + )).queue(); } else { // Display current slowmode timer int totalSecs = event.getTextChannel().getSlowmode(); String timeString = formatTime(totalSecs); - event.replyEmbeds(EmbedUtils.createDefault(":stopwatch: This channel's slowmode is **"+timeString+"**.")).queue(); + event.replyEmbeds(EmbedUtils.createDefault( + get(s -> s.staff.slowMode.display, timeString) + )).queue(); } } @@ -88,18 +99,17 @@ private String formatTime(int totalSeconds) { int seconds = totalSeconds % 60; String time = ""; if (hours > 0) { - time += hours + " hour"; - if (hours > 1) time += "s"; + time += get(s -> s.staff.slowMode.format.hours, hours); + if (minutes > 0) time += ", "; } if (minutes > 0) { - time += minutes + " minute"; - if (minutes > 1) time += "s"; + time += get(s -> s.staff.slowMode.format.minutes, minutes); + if (seconds > 0) time += ", "; } if (seconds > 0) { - time += seconds + " second"; - if (seconds > 1) time += "s"; + time += get(s -> s.staff.slowMode.format.seconds, seconds); } return time; } diff --git a/src/main/java/technobot/commands/staff/UnMuteCommand.java b/src/main/java/technobot/commands/staff/UnMuteCommand.java index dee589b..c882be7 100644 --- a/src/main/java/technobot/commands/staff/UnMuteCommand.java +++ b/src/main/java/technobot/commands/staff/UnMuteCommand.java @@ -17,6 +17,8 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that removes a muted role from a user in the guild. * @@ -40,35 +42,43 @@ public void execute(SlashCommandInteractionEvent event) { User user = event.getOption("user").getAsUser(); Member target = event.getOption("user").getAsMember(); if (target == null) { - event.replyEmbeds(EmbedUtils.createError("That user is not in this server!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.unmute.unmuteForeign) + )).setEphemeral(true).queue(); return; } else if (target.getIdLong() == event.getJDA().getSelfUser().getIdLong()) { - event.replyEmbeds(EmbedUtils.createError("Do you seriously expect me to unmute myself?")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.unmute.unmuteBot) + )).setEphemeral(true).queue(); return; } // Check target role position ModerationHandler moderationHandler = GuildData.get(event.getGuild()).moderationHandler; if (!moderationHandler.canTargetMember(target)) { - event.replyEmbeds(EmbedUtils.createError("This member cannot be unmuted. I need my role moved higher than theirs.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.unmute.tooHighRole) + )).setEphemeral(true).queue(); return; } // Check that muted role is valid and user has it Role muteRole = GuildData.get(event.getGuild()).moderationHandler.getMuteRole(); if (muteRole == null) { - String text = "This server does not have a mute role, use `/mute-role ` to set one or `/mute-role create [name]` to create one."; + String text = get(s -> s.staff.unmute.noRole); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); return; } if (!target.getRoles().contains(muteRole)) { - String text = "That user is not muted!"; + String text = get(s -> s.staff.unmute.notMuted); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); return; } int botPos = event.getGuild().getBotRole().getPosition(); if (muteRole.getPosition() >= botPos) { - event.replyEmbeds(EmbedUtils.createError("This member cannot be unmuted. I need my role moved higher than the mute role.")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.unmute.tooHighRole) + )).setEphemeral(true).queue(); return; } @@ -83,7 +93,7 @@ public void execute(SlashCommandInteractionEvent event) { // Send confirmation message event.replyEmbeds(new EmbedBuilder() - .setAuthor(user.getAsTag() + " has been unmuted", null, user.getEffectiveAvatarUrl()) + .setAuthor(get(s -> s.staff.unmute.message, user.getAsTag()), null, user.getEffectiveAvatarUrl()) .setColor(EmbedColor.DEFAULT.color) .build() ).queue(); diff --git a/src/main/java/technobot/commands/staff/UnbanCommand.java b/src/main/java/technobot/commands/staff/UnbanCommand.java index 0f38618..1b52757 100644 --- a/src/main/java/technobot/commands/staff/UnbanCommand.java +++ b/src/main/java/technobot/commands/staff/UnbanCommand.java @@ -12,6 +12,8 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that unbans a user from the guild. * @@ -33,7 +35,8 @@ public UnbanCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { String input = event.getOption("user_id").getAsString(); if (input.equals(event.getJDA().getSelfUser().getId())) { - event.replyEmbeds(EmbedUtils.createError("Ah yes let me just unban myself...")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError(get(s -> s.staff.unban.unbanSelf) + )).setEphemeral(true).queue(); return; } try { @@ -43,13 +46,13 @@ public void execute(SlashCommandInteractionEvent event) { // Send confirmation message event.replyEmbeds(new EmbedBuilder() - .setAuthor(user.getAsTag() + " has been unbanned", null, user.getEffectiveAvatarUrl()) + .setAuthor(get(s -> s.staff.unban.success, user.getAsTag()), null, user.getEffectiveAvatarUrl()) .setColor(EmbedColor.DEFAULT.color) .build() ).queue(); - }, fail -> event.replyEmbeds(EmbedUtils.createError("That user does not exist!")).setEphemeral(true).queue()); + }, fail -> event.replyEmbeds(EmbedUtils.createError(get(s -> s.staff.unban.noUser))).setEphemeral(true).queue()); } catch (NumberFormatException e) { - event.replyEmbeds(EmbedUtils.createError("That is not a valid user ID!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError(get(s -> s.staff.unban.invalidUser))).setEphemeral(true).queue(); } } } diff --git a/src/main/java/technobot/commands/staff/UnlockCommand.java b/src/main/java/technobot/commands/staff/UnlockCommand.java index 44cda90..f8a791f 100644 --- a/src/main/java/technobot/commands/staff/UnlockCommand.java +++ b/src/main/java/technobot/commands/staff/UnlockCommand.java @@ -13,6 +13,8 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that removes lock from a specified channel. * @@ -40,16 +42,21 @@ public void execute(SlashCommandInteractionEvent event) { else { channel = event.getTextChannel(); } if (channel == null) { - event.replyEmbeds(EmbedUtils.createError("That is not a valid channel!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.unlock.invalidChannel) + )).setEphemeral(true).queue(); return; } try { channel.upsertPermissionOverride(event.getGuild().getPublicRole()).clear(Permission.MESSAGE_SEND).queue(); - String channelString = "<#" + channel.getId() + ">"; - event.replyEmbeds(EmbedUtils.createDefault(":unlock: " + channelString + " has been unlocked.")).queue(); + event.replyEmbeds(EmbedUtils.createDefault( + get(s -> s.staff.unlock.success, channel.getId()) + )).queue(); } catch (InsufficientPermissionException e) { - event.replyEmbeds(EmbedUtils.createError("I am lacking some permissions required to unlock channels.")).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.unlock.noPerms) + )).queue(); } } } diff --git a/src/main/java/technobot/commands/staff/WarnCommand.java b/src/main/java/technobot/commands/staff/WarnCommand.java index e05de9b..e20e49e 100644 --- a/src/main/java/technobot/commands/staff/WarnCommand.java +++ b/src/main/java/technobot/commands/staff/WarnCommand.java @@ -17,7 +17,8 @@ import technobot.util.embeds.EmbedUtils; import java.awt.*; -import java.util.Date; + +import static technobot.util.Localization.get; /** * Command that adds a warning to user's account. @@ -42,18 +43,26 @@ public void execute(SlashCommandInteractionEvent event) { User user = event.getOption("user").getAsUser(); Member target = event.getGuild().getMemberById(user.getIdLong()); if (target == null) { - event.replyEmbeds(EmbedUtils.createError("That user is not in this server!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.warn.warnForeign) + )).setEphemeral(true).queue(); return; } else if (target.getIdLong() == event.getJDA().getSelfUser().getIdLong()) { - event.replyEmbeds(EmbedUtils.createError("Why would I warn myself... silly human!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.staff.warn.warnBot) + )).setEphemeral(true).queue(); return; } - OptionMapping reasonOption = event.getOption("reason"); - String reason = reasonOption != null ? reasonOption.getAsString() : "Unspecified"; + String reason = event.getOption( + "reason", + get(s -> s.staff.reasonUnspecified) + "", + OptionMapping::getAsString + ); // Check that target is not the same as author if (target.getIdLong() == event.getUser().getIdLong()) { - event.replyEmbeds(EmbedUtils.createError("You cannot warn yourself!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError(get(s -> s.staff.warn.warnSelf) + )).setEphemeral(true).queue(); return; } @@ -63,14 +72,14 @@ public void execute(SlashCommandInteractionEvent event) { // Private message user with reason for warn user.openPrivateChannel().queue(privateChannel -> { - MessageEmbed msg = data.moderationHandler.createCaseMessage(event.getUser().getIdLong(), "Warn", reason, Color.yellow.getRGB()); + MessageEmbed msg = data.moderationHandler.createCaseMessage(event.getUser().getIdLong(), get(s -> s.staff.cases.actions.warn), reason, Color.yellow.getRGB()); privateChannel.sendMessageEmbeds(msg).queue(); }, fail -> { }); // Send confirmation message event.replyEmbeds(new EmbedBuilder() - .setAuthor(user.getAsTag() + " has been warned", null, user.getEffectiveAvatarUrl()) - .setDescription("**Reason:** " + reason) + .setAuthor(get(s -> s.staff.warn.message, user.getAsTag()), null, user.getEffectiveAvatarUrl()) + .setDescription(get(s -> s.staff.cases.reason, reason)) .setColor(EmbedColor.DEFAULT.color) .build() ).queue(); diff --git a/src/main/java/technobot/commands/staff/WarningsCommand.java b/src/main/java/technobot/commands/staff/WarningsCommand.java index 1c75556..37242a9 100644 --- a/src/main/java/technobot/commands/staff/WarningsCommand.java +++ b/src/main/java/technobot/commands/staff/WarningsCommand.java @@ -17,6 +17,8 @@ import java.util.List; import java.util.concurrent.TimeUnit; +import static technobot.util.Localization.get; + /** * Command that shows the warnings for a specified user. * @@ -35,13 +37,7 @@ public WarningsCommand(TechnoBot bot) { @Override public void execute(SlashCommandInteractionEvent event) { GuildData data = GuildData.get(event.getGuild()); - OptionMapping option = event.getOption("user"); - User target; - if (option != null) { - target = option.getAsUser(); - } else { - target = event.getUser(); - } + User target = event.getOption("user", event.getUser(), OptionMapping::getAsUser); // Create embed template EmbedBuilder embed = new EmbedBuilder(); @@ -50,17 +46,17 @@ public void execute(SlashCommandInteractionEvent event) { // Check if user has no warnings List warnings = data.moderationHandler.getWarnings(target.getId()); if (warnings == null || warnings.isEmpty()) { - embed.setAuthor(target.getAsTag()+" has no infractions", null, target.getEffectiveAvatarUrl()); + embed.setAuthor(get(s -> s.staff.warnings.noWarnings, target.getAsTag()), null, target.getEffectiveAvatarUrl()); event.replyEmbeds(embed.build()).queue(); return; } // Display warnings in an embed - int lastSevenDays = 0; + int lastWeek = 0; int lastDay = 0; StringBuilder content = new StringBuilder(); int counter = 0; - for (int i = warnings.size()-1; i >= 0; i--) { + for (int i = warnings.size() - 1; i >= 0; i--) { Warning w = warnings.get(i); String time = TimeFormat.RELATIVE.format(w.getTimestamp()); if (counter < 10) { @@ -70,15 +66,27 @@ public void execute(SlashCommandInteractionEvent event) { lastDay++; } if (w.getTimestamp() >= System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7)) { - lastSevenDays++; + lastWeek++; } counter++; } - embed.setAuthor(target.getAsTag()+"'s Infractions", null, target.getEffectiveAvatarUrl()); - embed.addField("Last 24 Hours", lastDay+" warnings", true); - embed.addField("Last 7 Days", lastSevenDays+" warnings", true); - embed.addField("Total", warnings.size()+" warnings", true); - embed.addField("[ID] Last 10 Warnings", content.toString(), false); + embed.setAuthor(get(s -> s.staff.warnings.title, target.getAsTag()), null, target.getEffectiveAvatarUrl()); + embed.addField( + get(s -> s.staff.warnings.lastDay), + get(s -> s.staff.warnings.message, lastDay), true + ); + embed.addField( + get(s -> s.staff.warnings.lastWeek), + get(s -> s.staff.warnings.message, lastWeek), true + ); + embed.addField( + get(s -> s.staff.warnings.total), + get(s -> s.staff.warnings.message, warnings.size()), true + ); + embed.addField( + get(s -> s.staff.warnings.last10), + content.toString(), false + ); event.replyEmbeds(embed.build()).queue(); } } diff --git a/src/main/java/technobot/handlers/ModerationHandler.java b/src/main/java/technobot/handlers/ModerationHandler.java index 0cf8b7a..6fc3236 100644 --- a/src/main/java/technobot/handlers/ModerationHandler.java +++ b/src/main/java/technobot/handlers/ModerationHandler.java @@ -18,6 +18,8 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import static technobot.util.Localization.get; + /** * Handles moderation and warnings. Interfaces with POJO objects. * @@ -106,11 +108,13 @@ public MessageEmbed createCaseMessage(long moderatorID, String action, int color * Creates the actual embed for createCaseMessage(), ignoring null values. */ private MessageEmbed caseMessageHelper(long moderatorID, String action, String reason, String duration, int color) { - String text = "**Server:** " + guild.getName(); - text += "\n**Actioned by:** <@!" + moderatorID + ">"; - text += "\n**Action:** " + action; - if (duration != null) text += "\n**Duration:** " + duration; - if (reason != null) text += "\n**Reason:** " + reason; + String text = get(s -> s.staff.cases.server, guild.getName()); + text += "\n" + get(s -> s.staff.cases.actionedBy, moderatorID); + text += "\n" + get(s -> s.staff.cases.action, action); + if (duration != null) + text += "\n" + get(s -> s.staff.cases.duration, duration); + if (reason != null) + text += "\n" + get(s -> s.staff.cases.reason, reason); return new EmbedBuilder().setColor(color).setDescription(text).setTimestamp(new Date().toInstant()).build(); } diff --git a/src/main/resources/localization/en_us.json b/src/main/resources/localization/en_us.json index 8206790..0333a50 100644 --- a/src/main/resources/localization/en_us.json +++ b/src/main/resources/localization/en_us.json @@ -348,5 +348,118 @@ "success": ":loud_sound: Set volume to {}%", "failure": "You must specify a volume between 0 and 100!" } + }, + "staff": { + "cases": { + "actions": { + "ban": "Ban", + "kick": "Kick", + "warn": "Warn" + }, + "server": "**Server:** {}", + "actionedBy": "**Actioned By:** {mention}", + "action": "**Action:** {}", + "duration": "**Duration:** {}", + "reason": "**Reason:** {}" + }, + "ban": { + "banBot": "Did you seriously expect me to ban myself?", + "tooHighRole": "This member cannot be banned. I need my role moved higher than theirs.", + "duration": "{} Days", + "message": "{} has been banned{}" + }, + "clear": { + "success": ":ballot_box_with_check: I have deleted `{} messages!`", + "failure": "You cannot clear messages older than 2 weeks!" + }, + "kick": { + "kickForeign": "That user is not in this server!", + "kickBot": "Did you seriously expect me to kick myself?", + "tooHighRole": "This member cannot be kicked. I need my role moved higher than theirs.", + "message": "{} has been kicked" + }, + "lock": { + "success": ":lock: {channel} has been locked.", + "failure": "That is not a valid channel!" + }, + "mute": { + "muteForeign": "That user is not in this server!", + "muteBot": "Did you seriously expect me to mute myself?", + "tooHighRole": "This member cannot be muted. I need my role moved higher than theirs.", + "noRole": "This server does not have a mute role, use `/mute-role ` to set one or `/mute-role create [name]` to create one.", + "alreadyMuted": "This user is already muted!", + "message": "{} has been muted" + }, + "muteRole": { + "noPerm": "I am unable to create roles. Please check my permissions and role position.", + "botManagedRole": "I cannot set bot/managed roles as the mute role!", + "success": "{blue_tick} The {mention} role will be user for the `/mute` command." + }, + "removeWarn": { + "successId": "{green_tick} Warning #{} has been removed.", + "failureId": "Unable to find a warning with that ID!", + "successUser": "{green_tick} {} warnings have been removed for {mention}.", + "failureUser": "That user has no warnings!", + "failure": "You must specify a user or a warning ID!" + }, + "role": { + "roleForeign": "That user is not in this server!", + "botManagedRole": "I cannot give/remove bot/managed roles!", + "tooHighRole": "This member cannot be updated. I need my role moved higher than theirs.", + "message": "{green_tick} Changed roles for {}, " + }, + "setNick": { + "nickForeign": "That user is not in this server!", + "set": "{green_tick} **{}**'s nickname has been changed to **{}**.", + "reset": "{green_tick} **{}**'s nickname has been reset.", + "tooHighRole": "This member cannot be updated. I need my role moved higher than theirs." + }, + "slowMode": { + "failureThread": "You cannot set slow mode on threads!", + "disable": ":stopwatch: Slow mode has been disabled in this channel.", + "tooHigh": "Time should be less than or equal to **6 hours**.", + "set": ":stopwatch: This channel slow mode delay has been set to **{}**.", + "display": ":stopwatch: This channel slow mode delay is **{}**.", + "format": { + "hours": "{} hours", + "minutes": "{} minutes", + "seconds": "{} seconds" + } + }, + "unban": { + "unbanSelf": "Ah yes, let me just unban myself...", + "success": "{} has been unbanned", + "noUser": "That user does not exist!", + "invalidUser": "That is not a valid user ID!" + }, + "unlock": { + "invalidChannel": "That is not a valid channel!", + "noPerms": "I am lacking some permissions require to unlock channels.", + "success": ":unlock: {channel} has been unlocked." + }, + "unmute": { + "unmuteForeign": "That user is not in this server!", + "unmuteBot": "Do you seriously expect me to unmute myself?", + "tooHighRole": "This member cannot be unmuted. I need my role moved higher than theirs.", + "noRole": "This server does not have a mute role, use `/mute-role ` to set one or `/mute-role create [name]` to create one.", + "notMuted": "This user is not muted!", + "message": "{} has been unmuted" + }, + "warn": { + "warnForeign": "That user is not in this server!", + "warnBot": "Why would I warn myself... silly human!", + "warnSelf": "You cannot warn yourself!", + "message": "{} has been warned" + }, + "warnings": { + "noWarnings": "{} has no infractions!", + "title": "{}'s Infractions", + "lastDay": "Last 24 hours", + "lastWeek": "Last 7 days", + "total": "Total", + "last10": "[ID] Last 10 Warnings", + "message": "{} warnings" + }, + "reasonUnspecified": "Unspecified" } } \ No newline at end of file From f05b744e8015361131415c2dd83c874cf2978c20 Mon Sep 17 00:00:00 2001 From: theonlytails Date: Tue, 28 Jun 2022 11:46:11 +0300 Subject: [PATCH 09/15] feature(l10n,starboard): migrated the starboard commands to the new l10n system Signed-off-by: theonlytails --- .../commands/starboard/StarboardCommand.java | 69 +++++++++++-------- src/main/resources/localization/en_us.json | 40 +++++++++++ 2 files changed, 79 insertions(+), 30 deletions(-) diff --git a/src/main/java/technobot/commands/starboard/StarboardCommand.java b/src/main/java/technobot/commands/starboard/StarboardCommand.java index c0b9ad1..af25164 100644 --- a/src/main/java/technobot/commands/starboard/StarboardCommand.java +++ b/src/main/java/technobot/commands/starboard/StarboardCommand.java @@ -14,6 +14,10 @@ import technobot.handlers.StarboardHandler; import technobot.util.embeds.EmbedUtils; +import java.util.stream.Collectors; + +import static technobot.util.Localization.get; + /** * Admin command that sets up and modifies the starboard. * @@ -52,80 +56,85 @@ public void execute(SlashCommandInteractionEvent event) { StarboardHandler starboardHandler = GuildData.get(event.getGuild()).starboardHandler; String text = null; - switch(event.getSubcommandName()) { + switch (event.getSubcommandName()) { case "create" -> { // Set starboard channel long channel = channelOption.getAsGuildChannel().getIdLong(); starboardHandler.setChannel(channel); - text = EmbedUtils.BLUE_TICK + " Set the starboard channel to <#" + channel + ">"; + text = get(s -> s.starboard.create, channel); } case "limit" -> { OptionMapping limitOption = event.getOption("stars"); if (limitOption != null) { int limit = limitOption.getAsInt(); starboardHandler.setStarLimit(limit); - text = EmbedUtils.BLUE_TICK + " Messages now require " + limit + " stars to show up on the starboard!"; + text = get(s -> s.starboard.limit.set, limit); } else { starboardHandler.setStarLimit(3); - text = EmbedUtils.BLUE_TICK + " Reset the star limit to default!"; + text = get(s -> s.starboard.limit.reset); } } case "blacklist" -> { if (channelOption != null) { long channel = channelOption.getAsGuildChannel().getIdLong(); starboardHandler.blacklistChannel(channel); - text = EmbedUtils.BLUE_TICK + " Starboard will now ignore reactions from <#" + channel + ">"; + text = get(s -> s.starboard.blacklist.add, channel); } else { starboardHandler.clearBlacklist(); - text = EmbedUtils.BLUE_TICK + " Reset the starboard blacklist!"; + text = get(s -> s.starboard.blacklist.reset); } } case "unblacklist" -> { if (channelOption != null) { long channel = channelOption.getAsGuildChannel().getIdLong(); starboardHandler.unBlacklistChannel(channel); - text = EmbedUtils.BLUE_X + " Removed <#" + channel + "> from the Starboard blacklist!"; + text = get(s -> s.starboard.unblacklist.remove, channel); } else { starboardHandler.clearBlacklist(); - text = EmbedUtils.BLUE_TICK + " Reset the starboard blacklist!"; + text = get(s -> s.starboard.unblacklist.reset); } } case "lock" -> { boolean isLocked = starboardHandler.toggleLock(); - if (isLocked) text = EmbedUtils.BLUE_TICK + " Locked the starboard!"; - else text = EmbedUtils.BLUE_X + " Unlocked the starboard!"; + if (isLocked) text = get(s -> s.starboard.lock.lock); + else text = get(s -> s.starboard.lock.unlock); } case "jump" -> { boolean hasJumpLink = starboardHandler.toggleJump(); - if (hasJumpLink) text = EmbedUtils.BLUE_TICK + " Enabled jump links on Starboard posts!"; - else text = EmbedUtils.BLUE_X + " Disabled jump links on Starboard posts!"; + if (hasJumpLink) text = get(s -> s.starboard.jump.enable); + else text = get(s -> s.starboard.jump.disable); } case "nsfw" -> { boolean isNSFW = starboardHandler.toggleNSFW(); - if (isNSFW) text = EmbedUtils.BLUE_TICK + " Users can now star messages in NSFW channels!"; - else text = EmbedUtils.BLUE_X + " Users can no longer star messages in NSFW channels!"; + if (isNSFW) text = get(s -> s.starboard.nsfw.enable); + else text = get(s -> s.starboard.nsfw.disable); } case "self" -> { boolean canSelfStar = starboardHandler.toggleSelfStar(); - if (canSelfStar) text = EmbedUtils.BLUE_TICK + " Users can now star their own messages!"; - else text = EmbedUtils.BLUE_X + " Users can no longer star their own messages!"; + if (canSelfStar) text = get(s -> s.starboard.self.enable); + else text = get(s -> s.starboard.self.disable); } case "config" -> { text = ""; - text += "**Threshold:** " + starboardHandler.getStarLimit(); - if (starboardHandler.getChannel() != null) { - text += "\n**Channel:** <#" + starboardHandler.getChannel() + ">"; - } else { - text += "\n**Channel:** none"; - } - text += "\n**Allow NSFW:** " + starboardHandler.isNSFW(); - text += "\n**Count Self Stars:** " + starboardHandler.canSelfStar(); - text += "\n**Show Jump URL:** " + starboardHandler.hasJumpLink(); - text += "\n**Locked:** " + starboardHandler.isLocked(); - text += "\n**Blacklisted Channels:** "; - for (Long channel : starboardHandler.getBlacklist()) { - text += "<#" + channel + "> "; - } + text += get(s -> s.starboard.config.threshold, starboardHandler.getStarLimit()); + text += "\n" + get( + s -> s.starboard.config.channel, + starboardHandler.getChannel() != null + ? "<#" + starboardHandler.getChannel() + ">" + : "none" + ); + text += "\n" + get(s -> s.starboard.config.allowNsfw, starboardHandler.isNSFW()); + text += "\n" + get(s -> s.starboard.config.allowSelf, starboardHandler.canSelfStar()); + text += "\n" + get(s -> s.starboard.config.showJumpLinks, starboardHandler.hasJumpLink()); + text += "\n" + get(s -> s.starboard.config.locked, starboardHandler.isLocked()); + + text += "\n" + get( + s -> s.starboard.config.blacklistedChannels, + starboardHandler.getBlacklist().stream() + .map(channel -> "<#" + channel + "> ") + .collect(Collectors.joining(" ")) + ); + event.getHook().sendMessage(text).queue(); return; } diff --git a/src/main/resources/localization/en_us.json b/src/main/resources/localization/en_us.json index 0333a50..5808e66 100644 --- a/src/main/resources/localization/en_us.json +++ b/src/main/resources/localization/en_us.json @@ -461,5 +461,45 @@ "message": "{} warnings" }, "reasonUnspecified": "Unspecified" + }, + "starboard": { + "create": "{blue_tick} Set the starboard channel to {channel}", + "limit": { + "set": "{blue_tick} Messages now require {} stars to show up on the starboard.", + "reset": "{blue_tick} Reset the star limit to default." + }, + "blacklist": { + "add": "{blue_tick} Starboard will now ignore reactions from {channel}", + "reset": "{blue_tick} Reset the starboard blacklist!" + }, + "unblacklist": { + "remove": "{blue_x} Removed {channel} from the starboard blacklist!", + "reset": "{blue_tick} Reset the starboard blacklist!" + }, + "lock": { + "lock": "{blue_tick} Locked the starboard!", + "unlock": "{blue_x} Unlocked the starboard!" + }, + "jump": { + "enable": "{blue_tick} Enabled jump links on starboard posts!", + "disable": "{blue_x} Disabled jump links on starboard posts!" + }, + "nsfw": { + "enable": "{blue_tick} Users can now star messages in NSFW channels!", + "disable": "{blue_x} Users can no longer star messages in NSFW channels!" + }, + "self": { + "enable": "{blue_tick} Users can now star their own messages!", + "disable": "{blue_x} Users can no longer star their own messages!" + }, + "config": { + "threshold": "**Threshold:** {}", + "channel": "**Channel:** {}", + "allowNsfw": "**Allow NSFW:** {}", + "allowSelf": "**Allow Self Stars:** {}", + "showJumpLinks": "**Show Jump Links:** {}", + "locked": "**Locked:** {}", + "blacklistedChannels": "**Blacklisted Channels:** {}" + } } } \ No newline at end of file From 6f535a8f35c4326173594866e2c1941ca4db35e7 Mon Sep 17 00:00:00 2001 From: theonlytails Date: Tue, 28 Jun 2022 12:35:11 +0300 Subject: [PATCH 10/15] feature(l10n,suggestions): migrated the suggestions commands to the new l10n system Signed-off-by: theonlytails --- .../commands/suggestions/RespondCommand.java | 23 ++++++- .../commands/suggestions/SuggestCommand.java | 17 +++-- .../suggestions/SuggestionsCommand.java | 39 ++++++----- .../technobot/handlers/SuggestionHandler.java | 67 +++++++++++-------- .../java/technobot/util/Localization.java | 10 +-- src/main/resources/localization/en_us.json | 45 +++++++++++++ 6 files changed, 140 insertions(+), 61 deletions(-) diff --git a/src/main/java/technobot/commands/suggestions/RespondCommand.java b/src/main/java/technobot/commands/suggestions/RespondCommand.java index 56d3853..f7a8718 100644 --- a/src/main/java/technobot/commands/suggestions/RespondCommand.java +++ b/src/main/java/technobot/commands/suggestions/RespondCommand.java @@ -11,6 +11,8 @@ import technobot.data.GuildData; import technobot.handlers.SuggestionHandler; +import static technobot.util.Localization.get; + /** * Command that responds to suggestions on the suggestion board. * @@ -41,9 +43,26 @@ public void execute(SlashCommandInteractionEvent event) { String responseString = event.getOption("response").getAsString(); SuggestionHandler.SuggestionResponse response = SuggestionHandler.SuggestionResponse.valueOf(responseString); + String responseMessage = switch (response) { + case APPROVE -> get(s -> s.suggestions.respond.responses.approved); + case DENY -> get(s -> s.suggestions.respond.responses.denied); + case CONSIDER -> get(s -> s.suggestions.respond.responses.considered); + case IMPLEMENT -> get(s -> s.suggestions.respond.responses.implemented); + }; + int id = event.getOption("number").getAsInt() - 1; - OptionMapping reason = event.getOption("reason"); + String reason = event.getOption( + "reason", + get(s -> s.suggestions.respond.noReason) + "", + OptionMapping::getAsString + ); - GuildData.get(event.getGuild()).suggestionHandler.respond(event, id, reason, response); + GuildData.get(event.getGuild()).suggestionHandler.respond( + event, + id, + reason, + responseMessage, + response.color + ); } } diff --git a/src/main/java/technobot/commands/suggestions/SuggestCommand.java b/src/main/java/technobot/commands/suggestions/SuggestCommand.java index 4f73132..9288722 100644 --- a/src/main/java/technobot/commands/suggestions/SuggestCommand.java +++ b/src/main/java/technobot/commands/suggestions/SuggestCommand.java @@ -14,6 +14,8 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that allows a user to make a suggestion on the suggestion board. * @@ -33,10 +35,10 @@ public SuggestCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { event.deferReply().queue(); - // Check if suggestion board has been setup + // Check if suggestion board has been set up SuggestionHandler suggestionHandler = GuildData.get(event.getGuild()).suggestionHandler; if (!suggestionHandler.isSetup()) { - String text = "The suggestion channel has not been set!"; + String text = get(s -> s.suggestions.suggest.noChannel); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); return; } @@ -45,12 +47,12 @@ public void execute(SlashCommandInteractionEvent event) { String content = event.getOption("suggestion").getAsString(); EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setTitle("Suggestion #" + suggestionHandler.getNumber()) + .setTitle(get(s -> s.suggestions.suggest.title, suggestionHandler.getNumber())) .setDescription(content); // Add author to embed if anonymous mode is turned off if (suggestionHandler.isAnonymous()) { - embed.setAuthor("Anonymous", null, "https://cdn.discordapp.com/embed/avatars/0.png"); + embed.setAuthor(get(s -> s.suggestions.suggest.anonymousAuthor), null, "https://cdn.discordapp.com/embed/avatars/0.png"); } else { embed.setAuthor(event.getUser().getAsTag(), null, event.getUser().getEffectiveAvatarUrl()); } @@ -58,7 +60,7 @@ public void execute(SlashCommandInteractionEvent event) { // Make sure channel is valid TextChannel channel = event.getGuild().getTextChannelById(suggestionHandler.getChannel()); if (channel == null) { - String text = "The suggestion channel has been deleted, please set a new one!"; + String text = get(s -> s.suggestions.suggest.channelDeleted); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); return; } @@ -69,11 +71,12 @@ public void execute(SlashCommandInteractionEvent event) { try { suggestion.addReaction("⬆").queue(); suggestion.addReaction("⬇").queue(); - } catch (InsufficientPermissionException ignored) { } + } catch (InsufficientPermissionException ignored) { + } }); // Send a response message - String text = EmbedUtils.BLUE_TICK + "Your suggestion has been added to <#" + suggestionHandler.getChannel() + ">!"; + String text = get(s -> s.suggestions.suggest.message, suggestionHandler.getChannel()); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); } } diff --git a/src/main/java/technobot/commands/suggestions/SuggestionsCommand.java b/src/main/java/technobot/commands/suggestions/SuggestionsCommand.java index 78b9e3e..7d1c9c1 100644 --- a/src/main/java/technobot/commands/suggestions/SuggestionsCommand.java +++ b/src/main/java/technobot/commands/suggestions/SuggestionsCommand.java @@ -20,8 +20,10 @@ import java.util.ArrayList; +import static technobot.util.Localization.get; + /** - * Admin command to setup and modify the suggestion board. + * Admin command to set up and modify the suggestion board. * * @author TechnoVision */ @@ -49,7 +51,7 @@ public void execute(SlashCommandInteractionEvent event) { SuggestionHandler suggestionHandler = GuildData.get(guild).suggestionHandler; String text = null; - switch(event.getSubcommandName()) { + switch (event.getSubcommandName()) { case "create" -> { // Setup suggestion board OptionMapping channelOption = event.getOption("channel"); @@ -67,16 +69,15 @@ public void execute(SlashCommandInteractionEvent event) { channel.upsertPermissionOverride(guild.getPublicRole()).deny(denyPerms).setAllowed(allowPerms).queue(); suggestionHandler.setChannel(channel.getIdLong()); }); - text = EmbedUtils.BLUE_TICK + " Created a new suggestion channel!"; + text = get(s -> s.suggestions.suggestions.create.create); } else { // Set suggestion board to mentioned channel try { long channel = channelOption.getAsGuildChannel().getIdLong(); - String channelMention = "<#" + channel + ">"; suggestionHandler.setChannel(channel); - text = EmbedUtils.BLUE_TICK + " Set the suggestion channel to " + channelMention; + text = get(s -> s.suggestions.suggestions.create.set, channel); } catch (NullPointerException e) { - text = "You can only set a text channel as the suggestion board!"; + text = get(s -> s.suggestions.suggestions.create.failure); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); return; } @@ -85,33 +86,35 @@ public void execute(SlashCommandInteractionEvent event) { case "dm" -> { boolean isEnabled = suggestionHandler.toggleResponseDM(); if (isEnabled) { - text = EmbedUtils.BLUE_TICK + " Response DMs have been **enabled** for suggestions!"; + text = get(s -> s.suggestions.suggestions.dm.enable); } else { - text = EmbedUtils.BLUE_X + " Response DMs have been **disabled** for suggestions!"; + text = get(s -> s.suggestions.suggestions.dm.disable); } } case "anonymous" -> { boolean isEnabled = suggestionHandler.toggleAnonymous(); if (isEnabled) { - text = EmbedUtils.BLUE_TICK + " Anonymous mode has been **enabled** for suggestions!"; + text = get(s -> s.suggestions.suggestions.anonymous.enable); } else { - text = EmbedUtils.BLUE_X + " Anonymous mode has been **disabled** for suggestions!"; + text = get(s -> s.suggestions.suggestions.dm.disable); } } case "config" -> { text = ""; - if (suggestionHandler.getChannel() != null) { - text += "\n**Channel:** <#" + suggestionHandler.getChannel() + ">"; - } else { - text += "\n**Channel:** none"; - } - text += "\n**DM on Response:** " + suggestionHandler.hasResponseDM(); - text += "\n**Anonymous Mode:** " + suggestionHandler.isAnonymous(); + text += "\n" + get( + s -> s.suggestions.suggestions.config.channel, + suggestionHandler.getChannel() != null + ? "<#" + suggestionHandler.getChannel() + ">" + : "none" + ); + text += "\n" + get(s -> s.suggestions.suggestions.config.dm, suggestionHandler.hasResponseDM()); + text += "\n" + get(s -> s.suggestions.suggestions.config.anonymous, suggestionHandler.isAnonymous()); + event.getHook().sendMessage(text).queue(); return; } case "reset" -> { - text = "Would you like to reset the suggestions system?\nThis will delete **ALL** data!"; + text = get(s -> s.suggestions.suggestions.reset); WebhookMessageAction action = event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)); ButtonListener.sendResetMenu(event.getUser().getId(), "Suggestion", action); return; diff --git a/src/main/java/technobot/handlers/SuggestionHandler.java b/src/main/java/technobot/handlers/SuggestionHandler.java index 0b3bd95..d3403a8 100644 --- a/src/main/java/technobot/handlers/SuggestionHandler.java +++ b/src/main/java/technobot/handlers/SuggestionHandler.java @@ -6,7 +6,6 @@ import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.exceptions.ErrorResponseException; -import net.dv8tion.jda.api.interactions.commands.OptionMapping; import org.bson.conversions.Bson; import technobot.TechnoBot; import technobot.data.GuildData; @@ -15,6 +14,8 @@ import java.util.List; +import static technobot.util.Localization.get; + /** * Handles the suggestion board for a guild. * @@ -31,7 +32,7 @@ public class SuggestionHandler { /** * Sets up the local cache for this guild's suggestions from MongoDB. * - * @param bot Instance of TechnoBot shard. + * @param bot Instance of TechnoBot shard. * @param guild Instance of the guild this handler is for. */ public SuggestionHandler(TechnoBot bot, Guild guild) { @@ -66,7 +67,7 @@ public void add(long messageID, long author) { // Update local cache suggestions.getMessages().add(messageID); suggestions.getAuthors().add(author); - suggestions.setNumber(suggestions.getNumber()+1); + suggestions.setNumber(suggestions.getNumber() + 1); // Update MongoDB data file bot.database.suggestions.updateOne(filter, Updates.push("messages", messageID)); @@ -96,14 +97,18 @@ public boolean isSetup() { * * @return anonymous mode boolean. */ - public boolean isAnonymous() { return suggestions.isAnonymous(); } + public boolean isAnonymous() { + return suggestions.isAnonymous(); + } /** * Checks if response DMs are enabled/disabled. * * @return response DMs boolean. */ - public boolean hasResponseDM() { return suggestions.isResponseDM(); } + public boolean hasResponseDM() { + return suggestions.isResponseDM(); + } /** * Gets the number of the next suggestion. @@ -128,7 +133,9 @@ public Long getChannel() { * * @return list of suggestion message IDs. */ - public List getMessages() { return suggestions.getMessages(); } + public List getMessages() { + return suggestions.getMessages(); + } /** * Switches on/off anonymous mode and returns the result. @@ -157,32 +164,36 @@ public boolean toggleResponseDM() { /** * Responds to a suggestion by editing the embed and responding to the author. * - * @param event The slash command event that triggered this method. - * @param id the id number of the suggestion to respond to. - * @param reasonOption the reason option passed in by user. - * @param responseType the type of response (approve, deny, etc). + * @param event The slash command event that triggered this method. + * @param id the id number of the suggestion to respond to. + * @param reason the reason passed in by user. + * @param response the response message (approve, deny, etc). + * @param responseColor the color of the response message. */ - public void respond(SlashCommandInteractionEvent event, int id, OptionMapping reasonOption, SuggestionResponse responseType) { - String reason = (reasonOption != null) ? reasonOption.getAsString() : "No reason given"; + public void respond(SlashCommandInteractionEvent event, int id, String reason, String response, int responseColor) { try { SuggestionHandler suggestionHandler = GuildData.get(event.getGuild()).suggestionHandler; TextChannel channel = event.getGuild().getTextChannelById(suggestionHandler.getChannel()); - if (channel == null) { throw new NullPointerException(); } + if (channel == null) { + throw new NullPointerException(); + } // Edit suggestion embed Message suggestionMessage = channel.retrieveMessageById(suggestionHandler.getMessages().get(id)).complete(); MessageEmbed embed = suggestionMessage.getEmbeds().get(0); MessageEmbed editedEmbed = new EmbedBuilder() .setAuthor(embed.getAuthor().getName(), embed.getUrl(), embed.getAuthor().getIconUrl()) - .setTitle("Suggestion #" + (id+1) + " " + responseType.response) + .setTitle( + get(s -> s.suggestions.respond.title, id + 1, response) + "" + ) .setDescription(embed.getDescription()) - .addField("Reason from " + event.getUser().getAsTag(), reason.toString(), false) - .setColor(responseType.color) + .addField(get(s -> s.suggestions.respond.reason, event.getUser().getAsTag()), reason, false) + .setColor(responseColor) .build(); suggestionMessage.editMessageEmbeds(editedEmbed).queue(); - String lowercaseResponse = responseType.response.toLowerCase(); - String text = "Suggestion #" + (id+1) + " has been " + lowercaseResponse + "!"; + String lowercaseResponse = response.toLowerCase(); + String text = get(s -> s.suggestions.respond.message, id + 1, lowercaseResponse); event.getHook().sendMessageEmbeds(EmbedUtils.createDefault(text)).queue(); // DM Author if response DMs are turned on @@ -190,7 +201,7 @@ public void respond(SlashCommandInteractionEvent event, int id, OptionMapping re User author = event.getJDA().getUserById(suggestions.getAuthors().get(id)); if (author != null) { author.openPrivateChannel().queue(dm -> { - String dmText = "Your suggestion has been " + lowercaseResponse + " by " + event.getUser().getAsTag(); + String dmText = get(s -> s.suggestions.respond.dmText, lowercaseResponse, event.getUser().getAsTag()); dm.sendMessage(dmText).setEmbeds(editedEmbed).queue(); }); } @@ -198,11 +209,11 @@ public void respond(SlashCommandInteractionEvent event, int id, OptionMapping re } catch (IllegalArgumentException | IndexOutOfBoundsException e) { // Invalid ID format - String text = "Could not find a suggestion with that id number."; + String text = get(s -> s.suggestions.respond.noSuggestion); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } catch (ErrorResponseException | NullPointerException e) { // Invalid channel - String text = "Could not find that message, was the channel deleted or changed?"; + String text = get(s -> s.suggestions.respond.noMessage); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } } @@ -212,16 +223,14 @@ public void respond(SlashCommandInteractionEvent event, int id, OptionMapping re * Includes the correct color scheme and wording. */ public enum SuggestionResponse { - APPROVE("Approved", 0xd2ffd0), - DENY("Denied", 0xffd0ce), - CONSIDER("Considered", 0xfdff91), - IMPLEMENT("Implemented", 0x91fbff); + APPROVE(0xd2ffd0), + DENY(0xffd0ce), + CONSIDER(0xfdff91), + IMPLEMENT(0x91fbff); - private final String response; - private final int color; + public final int color; - SuggestionResponse(String response, int color) { - this.response = response; + SuggestionResponse(int color) { this.color = color; } } diff --git a/src/main/java/technobot/util/Localization.java b/src/main/java/technobot/util/Localization.java index 05d451f..0091ba2 100644 --- a/src/main/java/technobot/util/Localization.java +++ b/src/main/java/technobot/util/Localization.java @@ -63,14 +63,14 @@ public static String format(String template, Object... args) { .replaceAll("\\{green_tick\\}", EmbedUtils.GREEN_TICK) .replaceAll("\\{blue_x\\}", EmbedUtils.BLUE_X) .replaceAll("\\{blue_tick\\}", EmbedUtils.BLUE_TICK) - .replaceAll("\\{mention\\}", "<@{}>") - .replaceAll("\\{user\\}", "<@!{}>") - .replaceAll("\\{role\\}", "<@&{}>") - .replaceAll("\\{channel\\}", "<#{}>") + .replaceAll("\\{mention\\}", "<@{mention}>") + .replaceAll("\\{user\\}", "<@!{user}>") + .replaceAll("\\{role\\}", "<@&{role}>") + .replaceAll("\\{channel\\}", "<#{channel}>") .replaceAll("\\{currency\\}", "\uD83E\uDE99"); var argsList = Arrays.stream(args).map(Object::toString).toList(); - var templateArgsCount = Pattern.compile("\\{\\}").matcher(template).groupCount(); + var templateArgsCount = Pattern.compile("\\{\\w+\\}").matcher(template).groupCount(); switch (Integer.compare(argsList.size(), templateArgsCount)) { case -1 -> { diff --git a/src/main/resources/localization/en_us.json b/src/main/resources/localization/en_us.json index 5808e66..03a13a1 100644 --- a/src/main/resources/localization/en_us.json +++ b/src/main/resources/localization/en_us.json @@ -501,5 +501,50 @@ "locked": "**Locked:** {}", "blacklistedChannels": "**Blacklisted Channels:** {}" } + }, + "suggestions": { + "respond": { + "responses": { + "approved": "Approved", + "denied": "Denied", + "considered": "Considered", + "implemented": "Implemented" + }, + "noReason": "No reason given", + "title": "Suggestion #{id} • {response}", + "reason": "Reason from {userTag}", + "message": "Suggestion #{id} has been {response}!", + "dmText": "Your suggestion has been {response} by {userTag}", + "noSuggestion": "Could not find a suggestion with that ID.", + "noMessage": "Could not find that message, was the channel deleted or changed?" + }, + "suggest": { + "noChannel": "The suggestion channel has not been set!", + "title": "Suggestion #{id}", + "anonymousAuthor": "Anonymous", + "channelDeleted": "The suggestion channel has been deleted, please set a new one!", + "message": "{blue_tick} Your suggestion has been added to {channel}!" + }, + "suggestions": { + "create": { + "create": "{blue_tick} Created a new suggestion channel!", + "set": "{blue_tick} Set the suggestion channel to {channel}!", + "failure": "You can only set a text channel as the suggestion board!" + }, + "dm": { + "enable": "{blue_tick} Suggestion response DMs have been **enabled**!", + "disable": "{blue_x} Suggestion response DMs have been **disabled**!" + }, + "anonymous": { + "enable": "{blue_tick} Anonymous suggestions have been **enabled**!", + "disable": "{blue_x} Anonymous suggestions have been **disabled**!" + }, + "config": { + "channel": "**Channel:** {}", + "dm": "**Reponse DMs:** {}", + "anonymous": "**Anonymous Suggestions:** {}" + }, + "reset": "Would you like to reset the suggestions system?\nThis will delete **ALL** data!" + } } } \ No newline at end of file From 0f930daafeb94661999a4ddc1e405bad2c62653e Mon Sep 17 00:00:00 2001 From: theonlytails Date: Tue, 28 Jun 2022 13:20:55 +0300 Subject: [PATCH 11/15] feature(l10n,utility): migrated the utility commands to the new l10n system Signed-off-by: theonlytails --- .../java/technobot/commands/Category.java | 26 ++++--- .../commands/utility/AvatarCommand.java | 12 +-- .../commands/utility/HelpCommand.java | 58 ++++++++------- .../commands/utility/InviteCommand.java | 14 ++-- .../commands/utility/MathCommand.java | 11 ++- .../commands/utility/PingCommand.java | 18 ++++- .../commands/utility/PollCommand.java | 26 +++---- .../commands/utility/PremiumCommand.java | 12 +-- .../commands/utility/RolesCommand.java | 4 +- .../commands/utility/RollCommand.java | 9 ++- .../commands/utility/ServerCommand.java | 36 ++++++--- .../commands/utility/UserCommand.java | 11 +-- src/main/resources/localization/en_us.json | 73 +++++++++++++++++++ 13 files changed, 211 insertions(+), 99 deletions(-) diff --git a/src/main/java/technobot/commands/Category.java b/src/main/java/technobot/commands/Category.java index b681c00..03234c5 100644 --- a/src/main/java/technobot/commands/Category.java +++ b/src/main/java/technobot/commands/Category.java @@ -1,5 +1,7 @@ package technobot.commands; +import static technobot.util.Localization.get; + /** * Category that represents a group of similar commands. * Each category has a name and an emoji. @@ -7,18 +9,18 @@ * @author TechnoVision */ public enum Category { - STAFF(":computer:", "Staff"), - LEVELS(":chart_with_upwards_trend:", "Levels"), - MUSIC(":musical_note:", "Music"), - ECONOMY(":moneybag:", "Economy"), - STARBOARD(":star:", "Starboard"), - FUN(":smile:", "Fun"), - AUTOMATION(":gear:", "Automation"), - UTILITY(":tools:", "Utility"), - GREETINGS(":wave:", "Greetings"), - SUGGESTIONS(":thought_balloon:", "Suggestions"), - CASINO(":game_die:", "Casino"), - PETS(":dog:", "Pets"); + STAFF(":computer:", get(s -> s.utility.help.categories.staff)), + LEVELS(":chart_with_upwards_trend:", get(s -> s.utility.help.categories.levels)), + MUSIC(":musical_note:", get(s -> s.utility.help.categories.music)), + ECONOMY(":moneybag:", get(s -> s.utility.help.categories.economy)), + STARBOARD(":star:", get(s -> s.utility.help.categories.starboard)), + FUN(":smile:", get(s -> s.utility.help.categories.fun)), + AUTOMATION(":gear:", get(s -> s.utility.help.categories.automation)), + UTILITY(":tools:", get(s -> s.utility.help.categories.utility)), + GREETINGS(":wave:", get(s -> s.utility.help.categories.greetings)), + SUGGESTIONS(":thought_balloon:", get(s -> s.utility.help.categories.suggestions)), + CASINO(":game_die:", get(s -> s.utility.help.categories.casino)), + PETS(":dog:", get(s -> s.utility.help.categories.pets)); public final String emoji; public final String name; diff --git a/src/main/java/technobot/commands/utility/AvatarCommand.java b/src/main/java/technobot/commands/utility/AvatarCommand.java index d506a64..21c6725 100644 --- a/src/main/java/technobot/commands/utility/AvatarCommand.java +++ b/src/main/java/technobot/commands/utility/AvatarCommand.java @@ -11,6 +11,8 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedColor; +import static technobot.util.Localization.get; + /** * Command that displays a user's avatar and link. * @@ -28,20 +30,14 @@ public AvatarCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { // Get user - OptionMapping option = event.getOption("user"); - User user; - if (option != null) { - user = option.getAsUser(); - } else { - user = event.getUser(); - } + User user = event.getOption("user", event.getUser(), OptionMapping::getAsUser); // Create and send embed String avatarUrl = user.getEffectiveAvatarUrl() + "?size=1024"; EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) .setAuthor(user.getAsTag(), null, avatarUrl) - .setTitle("Avatar Link", avatarUrl) + .setTitle(get(s -> s.utility.avatar), avatarUrl) .setImage(avatarUrl); event.replyEmbeds(embed.build()).queue(); } diff --git a/src/main/java/technobot/commands/utility/HelpCommand.java b/src/main/java/technobot/commands/utility/HelpCommand.java index 086c73d..6099a8a 100644 --- a/src/main/java/technobot/commands/utility/HelpCommand.java +++ b/src/main/java/technobot/commands/utility/HelpCommand.java @@ -16,7 +16,12 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; + +import static technobot.util.Localization.get; public class HelpCommand extends Command { @@ -48,8 +53,8 @@ public void execute(SlashCommandInteractionEvent event) { } OptionMapping option = event.getOption("category"); - OptionMapping option2 = event.getOption("command"); - if (option != null && option2 != null) { + OptionMapping commandOption = event.getOption("command"); + if (option != null && commandOption != null) { event.replyEmbeds(EmbedUtils.createError("Please only give one optional argument and try again.")).queue(); } else if (option != null) { // Display category commands menu @@ -58,8 +63,11 @@ public void execute(SlashCommandInteractionEvent event) { if (embeds.isEmpty()) { // No commands for this category EmbedBuilder embed = new EmbedBuilder() - .setTitle(category.emoji + " **%s Commands**".formatted(category.name)) - .setDescription("Coming soon...") + .setTitle(get( + s -> s.utility.help.categoryTitle, + category.emoji, category.name + )) + .setDescription(get(s -> s.utility.help.comingSoon)) .setColor(EmbedColor.DEFAULT.color); event.replyEmbeds(embed.build()).queue(); return; @@ -71,11 +79,11 @@ public void execute(SlashCommandInteractionEvent event) { return; } action.queue(); - } else if (option2 != null) { + } else if (commandOption != null) { // Display command details menu - Command cmd = CommandRegistry.commandsMap.get(option2.getAsString()); + Command cmd = CommandRegistry.commandsMap.get(commandOption.getAsString()); if (cmd != null) { - builder.setTitle("Command: " + cmd.name); + builder.setTitle(get(s -> s.utility.help.commandTitle, cmd.name)); builder.setDescription(cmd.description); StringBuilder usages = new StringBuilder(); if (cmd.subCommands.isEmpty()) { @@ -85,16 +93,16 @@ public void execute(SlashCommandInteractionEvent event) { usages.append("`").append(getUsage(sub, cmd.name)).append("`\n"); } } - builder.addField("Usage:", usages.toString(), false); - builder.addField("Permission:", getPermissions(cmd), false); + builder.addField(get(s -> s.utility.help.commandUsage), usages.toString(), false); + builder.addField(get(s -> s.utility.help.commandPerms), getPermissions(cmd), false); event.replyEmbeds(builder.build()).queue(); } else { // Command specified doesn't exist. - event.replyEmbeds(EmbedUtils.createError("No command called \"" + option2.getAsString() + "\" found.")).queue(); + event.replyEmbeds(EmbedUtils.createError(get(s -> s.utility.help.noCommand, commandOption.getAsString()))).queue(); } } else { // Display default menu - builder.setTitle("TechnoBot Commands"); + builder.setTitle(get(s -> s.utility.help.defaultTitle)); categories.forEach((category, commands) -> { String categoryName = category.name().toLowerCase(); String value = "`/help " + categoryName + "`"; @@ -114,7 +122,11 @@ public void execute(SlashCommandInteractionEvent event) { public List buildCategoryMenu(Category category, List commands) { List embeds = new ArrayList<>(); EmbedBuilder embed = new EmbedBuilder(); - embed.setTitle(category.emoji + " **%s Commands**".formatted(category.name)); + + embed.setTitle(get( + s -> s.utility.help.categoryTitle, + category.emoji, category.name + )); embed.setColor(EmbedColor.DEFAULT.color); int counter = 0; @@ -154,11 +166,9 @@ public String getUsage(Command cmd) { if (cmd.args.isEmpty()) return usage.toString(); for (int i = 0; i < cmd.args.size(); i++) { boolean isRequired = cmd.args.get(i).isRequired(); - if (isRequired) { usage.append(" <"); } - else { usage.append(" ["); } + usage.append(isRequired ? " <" : " ["); usage.append(cmd.args.get(i).getName()); - if (isRequired) { usage.append(">"); } - else { usage.append("]"); } + usage.append(isRequired ? ">" : "]"); } return usage.toString(); } @@ -174,17 +184,9 @@ public String getUsage(SubcommandData cmd, String commandName) { if (cmd.getOptions().isEmpty()) return usage.toString(); for (OptionData arg : cmd.getOptions()) { boolean isRequired = arg.isRequired(); - if (isRequired) { - usage.append(" <"); - } else { - usage.append(" ["); - } + usage.append(isRequired ? " <" : " ["); usage.append(arg.getName()); - if (isRequired) { - usage.append(">"); - } else { - usage.append("]"); - } + usage.append(isRequired ? ">" : "]"); } return usage.toString(); } @@ -197,7 +199,7 @@ public String getUsage(SubcommandData cmd, String commandName) { */ private String getPermissions(Command cmd) { if (cmd.permission == null) { - return "None"; + return get(s -> s.utility.help.noPermissions); } return cmd.permission.getName(); } diff --git a/src/main/java/technobot/commands/utility/InviteCommand.java b/src/main/java/technobot/commands/utility/InviteCommand.java index f9bc8d5..f2dee9f 100644 --- a/src/main/java/technobot/commands/utility/InviteCommand.java +++ b/src/main/java/technobot/commands/utility/InviteCommand.java @@ -7,6 +7,8 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Creates button links to invite bot and join the support server. * @@ -23,10 +25,12 @@ public InviteCommand(TechnoBot bot) { @Override public void execute(SlashCommandInteractionEvent event) { - Button b1 = Button.link("https://discord.com/oauth2/authorize?client_id=979590525428580363&permissions=2088234238&scope=applications.commands%20bot", "Invite TechnoBot"); - Button b2 = Button.link("https://discord.gg/2TKJqfUQas", "Support Server"); - Button b3 = Button.link("https://technobot.app", "Dashboard"); - event.replyEmbeds(EmbedUtils.createDefault(":robot: Click the button below to invite TechnoBot to your servers!")) - .addActionRow(b1, b2, b3).queue(); + Button botInvite = Button.link("https://discord.com/oauth2/authorize?client_id=979590525428580363&permissions=2088234238&scope=applications.commands%20bot", "Invite TechnoBot"); + Button supportServerInvite = Button.link("https://discord.gg/2TKJqfUQas", "Support Server"); + Button dashboardLink = Button.link("https://technobot.app", "Dashboard"); + event.replyEmbeds(EmbedUtils.createDefault( + get(s -> s.utility.invite) + )) + .addActionRow(botInvite, supportServerInvite, dashboardLink).queue(); } } diff --git a/src/main/java/technobot/commands/utility/MathCommand.java b/src/main/java/technobot/commands/utility/MathCommand.java index cbabd9b..d11ebb0 100644 --- a/src/main/java/technobot/commands/utility/MathCommand.java +++ b/src/main/java/technobot/commands/utility/MathCommand.java @@ -13,6 +13,8 @@ import java.text.DecimalFormat; +import static technobot.util.Localization.get; + /** * Solves expressions like a calculator. * @@ -37,11 +39,14 @@ public void execute(SlashCommandInteractionEvent event) { Double result = new DoubleEvaluator().evaluate(expression); EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .addField("Expression", "`"+expression+"`", false) - .addField("Result", FORMATTER.format(result), false); + .addField(get(s -> s.utility.math.expression), "`" + expression + "`", false) + .addField(get(s -> s.utility.math.result), FORMATTER.format(result), false); event.replyEmbeds(embed.build()).queue(); } catch (IllegalArgumentException e) { - event.replyEmbeds(EmbedUtils.createError("That is not a valid math expression! Example: `(2^3-1)*sin(pi/4)/ln(pi^2)`")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError(get( + s -> s.utility.math.failure, + "(2 ^ 3 - 1) * sin(pi / 4) / ln(pi ^ 2)" + ))).setEphemeral(true).queue(); } } } diff --git a/src/main/java/technobot/commands/utility/PingCommand.java b/src/main/java/technobot/commands/utility/PingCommand.java index fa44c7f..1c338f8 100644 --- a/src/main/java/technobot/commands/utility/PingCommand.java +++ b/src/main/java/technobot/commands/utility/PingCommand.java @@ -7,6 +7,8 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedColor; +import static technobot.util.Localization.get; + /** * Ping command to check latency with Discord API. * @@ -24,12 +26,20 @@ public PingCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { event.deferReply().queue(); long time = System.currentTimeMillis(); - event.getHook().sendMessage(":signal_strength: Ping").queue(m -> { + event.getHook().sendMessage(get(s -> s.utility.ping.ping) + "").queue(m -> { long latency = System.currentTimeMillis() - time; EmbedBuilder embed = new EmbedBuilder(); - embed.setTitle(":ping_pong: Pong!"); - embed.addField("Latency", latency + "ms", false); - embed.addField("Discord API", event.getJDA().getGatewayPing() + "ms", false); + embed.setTitle(get(s -> s.utility.ping.pong)); + embed.addField( + get(s -> s.utility.ping.latency), + get(s -> s.utility.ping.value, latency), + false + ); + embed.addField( + get(s -> s.utility.ping.discordApi), + get(s -> s.utility.ping.value, event.getJDA().getGatewayPing()), + false + ); embed.setColor(EmbedColor.DEFAULT.color); m.editMessageEmbeds(embed.build()).override(true).queue(); }); diff --git a/src/main/java/technobot/commands/utility/PollCommand.java b/src/main/java/technobot/commands/utility/PollCommand.java index 7445760..09acf5a 100644 --- a/src/main/java/technobot/commands/utility/PollCommand.java +++ b/src/main/java/technobot/commands/utility/PollCommand.java @@ -13,6 +13,8 @@ import java.util.Arrays; import java.util.List; +import static technobot.util.Localization.get; + /** * Command that creates a quick poll with options and reactions. * @@ -21,16 +23,8 @@ public class PollCommand extends Command { private static final List NUMBER_EMOJIS = Arrays.asList( - "\u0031\u20E3", - "\u0032\u20E3", - "\u0033\u20E3", - "\u0034\u20E3", - "\u0035\u20E3", - "\u0036\u20E3", - "\u0037\u20E3", - "\u0038\u20E3", - "\u0039\u20E3", - "\uD83D\uDD1F"); + "1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣", "🔟" + ); public PollCommand(TechnoBot bot) { super(bot); @@ -52,7 +46,9 @@ public void execute(SlashCommandInteractionEvent event) { // Create multi-choice poll String[] choices = choicesOption.getAsString().strip().split("\\s+"); if (choices.length > 10) { - event.getHook().sendMessageEmbeds(EmbedUtils.createError("You cannot have more than 10 choices!")).queue(); + event.getHook().sendMessageEmbeds(EmbedUtils.createError( + get(s -> s.utility.poll.tooManyChoices) + )).queue(); return; } poll.append("\n"); @@ -68,10 +64,12 @@ public void execute(SlashCommandInteractionEvent event) { // Create simply upvote/downvote poll event.getHook().sendMessage(poll.toString()).queue(msg -> { try { - msg.addReaction("\uD83D\uDC4D").queue(); - msg.addReaction("\uD83D\uDC4E").queue(); + msg.addReaction("👍").queue(); + msg.addReaction("👎").queue(); } catch (InsufficientPermissionException e) { - msg.editMessage(" ").setEmbeds(EmbedUtils.createError("I don't have permissions to add reaction in this channel!")).queue(); + msg.editMessage(" ").setEmbeds(EmbedUtils.createError( + get(s -> s.utility.poll.noPerms) + )).queue(); } }); } diff --git a/src/main/java/technobot/commands/utility/PremiumCommand.java b/src/main/java/technobot/commands/utility/PremiumCommand.java index 13bf428..076b9a5 100644 --- a/src/main/java/technobot/commands/utility/PremiumCommand.java +++ b/src/main/java/technobot/commands/utility/PremiumCommand.java @@ -8,6 +8,8 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedColor; +import static technobot.util.Localization.get; + /** * Creates button links to the Patreon to buy premium. * @@ -26,10 +28,10 @@ public PremiumCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setTitle("TechnoBot Premium") - .setDescription("Premium features are coming soon! But in the meantime, feel free to donate [HERE](https://www.patreon.com/TechnoVision)! ") - .appendDescription("TechnoBot is developed by one guy who pays for server costs out of pocket! I appreciate any support :heart:") - .addField("Premium Features", "⦁ Add up to 10 auto-roles\n⦁ More coming soon...", true); - event.replyEmbeds(embed.build()).addActionRow(Button.link("https://www.patreon.com/TechnoVision", "Buy Premium")).queue(); + .setTitle(get(s -> s.utility.premium.title)) + .setDescription(get(s -> s.utility.premium.description1)) + .appendDescription(get(s -> s.utility.premium.description2)) + .addField(get(s -> s.utility.premium.features), get(s -> s.utility.premium.list), true); + event.replyEmbeds(embed.build()).addActionRow(Button.link("https://www.patreon.com/TechnoVision", get(s -> s.utility.premium.button) + "")).queue(); } } diff --git a/src/main/java/technobot/commands/utility/RolesCommand.java b/src/main/java/technobot/commands/utility/RolesCommand.java index 25106b4..a315117 100644 --- a/src/main/java/technobot/commands/utility/RolesCommand.java +++ b/src/main/java/technobot/commands/utility/RolesCommand.java @@ -8,6 +8,8 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedColor; +import static technobot.util.Localization.get; + /** * Command that displays all server roles. * @@ -34,7 +36,7 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setTitle("All Roles") + .setTitle(get(s -> s.utility.roles)) .setDescription(content); event.replyEmbeds(embed.build()).queue(); } diff --git a/src/main/java/technobot/commands/utility/RollCommand.java b/src/main/java/technobot/commands/utility/RollCommand.java index 0faf9e1..2405b04 100644 --- a/src/main/java/technobot/commands/utility/RollCommand.java +++ b/src/main/java/technobot/commands/utility/RollCommand.java @@ -11,6 +11,8 @@ import java.util.Random; +import static technobot.util.Localization.get; + /** * Command to roll a die for random number generation. * @@ -30,10 +32,11 @@ public RollCommand(TechnoBot bot) { } public void execute(SlashCommandInteractionEvent event) { - OptionMapping option = event.getOption("dice"); - int bound = option != null ? option.getAsInt() : 6; + int bound = event.getOption("dice", 6, OptionMapping::getAsInt); if (bound == 0) bound = 1; int result = random.nextInt(bound) + 1; - event.replyEmbeds(EmbedUtils.createDefault(":game_die: You rolled a "+bound+"-sided dice and got: **"+result+"**")).queue(); + event.replyEmbeds(EmbedUtils.createDefault( + get(s -> s.utility.roll, bound, result) + )).queue(); } } diff --git a/src/main/java/technobot/commands/utility/ServerCommand.java b/src/main/java/technobot/commands/utility/ServerCommand.java index 1c2013c..b06f684 100644 --- a/src/main/java/technobot/commands/utility/ServerCommand.java +++ b/src/main/java/technobot/commands/utility/ServerCommand.java @@ -9,6 +9,8 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedColor; +import static technobot.util.Localization.get; + /** * Command that displays relevant server information. * @@ -30,23 +32,35 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) .setTitle(guild.getName()) - .addField(":id: Server ID:", guild.getId(), true) - .addField(":calendar: Created On", guildTime, true) - .addField(":crown: Owned By", "<@" + guild.getOwnerId() + ">", true); + .addField(get(s -> s.utility.server.id), guild.getId(), true) + .addField(get(s -> s.utility.server.createdOn), guildTime, true) + .addField(get(s -> s.utility.server.owner), "<@" + guild.getOwnerId() + ">", true); - String members = String.format("**%s** Boosts :sparkles:", guild.getBoostCount()); - embed.addField(":busts_in_silhouette: Members (" + guild.getMemberCount() + ")", members, true); + embed.addField( + get(s -> s.utility.server.members, guild.getMemberCount()), + get(s -> s.utility.server.boosts, guild.getBoostCount()), + true + ); int textChannels = guild.getTextChannels().size(); int voiceChannels = guild.getVoiceChannels().size(); - String channels = String.format("**%s** Text\n**%s** Voice", textChannels, voiceChannels); - embed.addField(":speech_balloon: Channels (" + (textChannels + voiceChannels) + ")", channels, true); + embed.addField( + get(s -> s.utility.server.channels, textChannels + voiceChannels), + get(s -> s.utility.server.channelTypes, textChannels, voiceChannels), + true + ); - String other = "**Verification Level:** " + guild.getVerificationLevel().getKey(); - embed.addField(":earth_africa: Other:", other, true); + embed.addField( + get(s -> s.utility.server.other), + get(s -> s.utility.server.verification, guild.getVerificationLevel().getKey()), + true + ); - String roles = "To see a list with all roles use **/roles**"; - embed.addField(":closed_lock_with_key: Roles (" + guild.getRoles().size() + ")", roles, true); + embed.addField( + get(s -> s.utility.server.roles, guild.getRoles().size()), + get(s -> s.utility.server.rolesList), + true + ); event.replyEmbeds(embed.build()).queue(); } diff --git a/src/main/java/technobot/commands/utility/UserCommand.java b/src/main/java/technobot/commands/utility/UserCommand.java index 404badd..ae2eee3 100644 --- a/src/main/java/technobot/commands/utility/UserCommand.java +++ b/src/main/java/technobot/commands/utility/UserCommand.java @@ -13,6 +13,8 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedColor; +import static technobot.util.Localization.get; + /** * Command that displays information about a user. * @@ -31,8 +33,7 @@ public UserCommand(TechnoBot bot) { @Override public void execute(SlashCommandInteractionEvent event) { // Get user - OptionMapping userOption = event.getOption("user"); - User user = userOption != null ? userOption.getAsUser() : event.getUser(); + User user = event.getOption("user", event.getUser(), OptionMapping::getAsUser); Member member = event.getGuild().getMember(user); // Create and send embed @@ -40,9 +41,9 @@ public void execute(SlashCommandInteractionEvent event) { String joinedServer = TimeFormat.RELATIVE.format(member.getTimeJoined().toInstant().toEpochMilli()); EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .addField("Joined Discord", joinedDiscord, true) - .addField("Joined Server", joinedServer, true) - .addField("Discord ID", user.getId(), false) + .addField(get(s -> s.utility.user.joinedDiscord), joinedDiscord, true) + .addField(get(s -> s.utility.user.joinedServer), joinedServer, true) + .addField(get(s -> s.utility.user.discordId), user.getId(), false) .setThumbnail(user.getEffectiveAvatarUrl()) .setFooter(user.getAsTag(), user.getEffectiveAvatarUrl()); event.replyEmbeds(embed.build()).queue(); diff --git a/src/main/resources/localization/en_us.json b/src/main/resources/localization/en_us.json index 03a13a1..5ef8de7 100644 --- a/src/main/resources/localization/en_us.json +++ b/src/main/resources/localization/en_us.json @@ -546,5 +546,78 @@ }, "reset": "Would you like to reset the suggestions system?\nThis will delete **ALL** data!" } + }, + "utility": { + "avatar": "Avatar Link", + "help": { + "categories": { + "automation": "Automation", + "economy": "Economy", + "fun": "Fun", + "greetings": "Greetings", + "levels": "Levels", + "music": "Music", + "staff": "Staff", + "starboard": "Starboard", + "suggestions": "Suggestions", + "utility": "Utility", + "casino": "Casino", + "pets": "Pets" + }, + "categoryTitle": "{emoji} **{category} Commands**", + "noPermissions": "None", + "oneArgument": "Please only give one optional argument and try again", + "comingSoon": "Coming soon...", + "commandTitle": "Command: {cmdName}", + "commandUsage": "Usage:", + "commandPerms": "Permission:", + "noCommand": "No command called {cmdName} found.", + "defaultTitle": "TechnoBot Commands" + }, + "invite": ":robot: Click the button below to invite TechnoBot to your servers!", + "math": { + "expression": "Expression", + "result": "Result", + "failure": "That is not a valid math expression! Example: `{example}`" + }, + "ping": { + "ping": ":signal_strength: Ping!", + "pong": ":ping_pong: Pong!", + "latency": "Latency", + "discordApi": "DiscordAPI", + "value": "{latency}ms" + }, + "poll": { + "tooManyChoices": "You cannot have more than 10 choices!", + "noPerms": "I don't have permissions to add reactions in this channel!" + }, + "premium": { + "title": "TechnoBot Premium", + "description1": "Premium features are coming soon! But in the meantime, feel free to donate [HERE](https://www.patreon.com/TechnoVision)!", + "description2": "TechnoBot is developed by one guy who pays for server costs out of pocket! I appreciate any support :heart:", + "features": "Premium Features", + "list": "⦁ Add up to 10 auto-roles\n⦁ More coming soon...", + "button": "Buy Premium" + }, + "roles": "All Roles", + "roll": ":game_die: You rolled a {sides}-sided die and got: **{result}**", + "server": { + "id": ":id: Server ID:", + "createdOn": ":calendar: Created on:", + "owner": ":crown: Owner:", + "boosts": "**{boosts}** Boosts :sparkles:", + "members": ":busts_in_silhouette: Members ({count})", + "channels": ":speech_balloon: Channels ({count})", + "channelTypes": "**{text}** Text\n**{voice}** Voice", + "verification": "**Verification Level:** {level}", + "other": ":earth_africa: Other:", + "roles": ":closed_lock_with_key: Roles ({count})", + "rolesList": "To see a list with all roles use **`/roles`**." + }, + "user": { + "joinedDiscord": ":calendar: Joined Discord:", + "joinedServer": ":calendar: Joined Server:", + "discordId": ":id: Discord ID:" + } } } \ No newline at end of file From c8bab51bcbbccc0ebb6cba2bd7c398414a0dccbd Mon Sep 17 00:00:00 2001 From: theonlytails Date: Tue, 28 Jun 2022 13:30:59 +0300 Subject: [PATCH 12/15] chore(l10n): added descriptions to every generic parameter Signed-off-by: theonlytails --- src/main/resources/localization/en_us.json | 276 ++++++++++----------- 1 file changed, 138 insertions(+), 138 deletions(-) diff --git a/src/main/resources/localization/en_us.json b/src/main/resources/localization/en_us.json index 5ef8de7..01b8b67 100644 --- a/src/main/resources/localization/en_us.json +++ b/src/main/resources/localization/en_us.json @@ -14,116 +14,116 @@ "list": { "noAutoRoles": "Use `/auto-role add ` to set your first auto role!", "premium": "Add additional roles with `/premium`", - "roleCount": "There are {} auto roles given to new members:", - "role": "**{}**. {role}" + "roleCount": "There are {count} auto roles given to new members:", + "role": "**{num}**. {role}" } } }, "economy": { - "replyId": "Reply #{}", + "replyId": "Reply #{num}", "balance": { - "leaderboardRank": "Leaderboard Rank: #{}", + "leaderboardRank": "Leaderboard Rank: #{rank}", "cash": "Cash:", "bank": "Bank:", "total": "Total:" }, "crime": { - "timeout": ":stopwatch: You can next commit a crime {}.", + "timeout": ":stopwatch: You can next commit a crime {timestamp}.", "success": [ - "You work for the Juarez cartel as a brick-presser and earn {currency} {}! They'll probably kill you and your family tomorrow. Just saying.", - "You rob an orphanage for {currency} {}.", - "You break into the house next door and sell their gaming PC on E-Bay for {currency} {}.", - "You work as a scam seller on Amazon selling fake airpods for {currency} {}.", - "You break into Rapunzel's kingdom, steal her hair, and sell it on the black market for {currency} {}.", - "You are a high school chemistry teacher diagnosed with lung cancer & turn to selling meth for {currency} {} to secure your family's future.", - "You punched some random person and they gave you {currency} {} to stop.", - "You smashed a kid's piggy bank and got {currency} {} from it.", - "What you did was too horrible to speak of. I can't believe you would do that. Was the {currency} {} even worth it for those horrible crimes you did? No.", - "You were hired as an assassin and you succeeded, earning {currency} {}.", - "You need some extra cash for your drug habit. You break into the local dirty video store and rob them of {currency} {}! You also take a few \"items\" for yourself..." + "You work for the Juarez cartel as a brick-presser and earn {currency} {amount}! They'll probably kill you and your family tomorrow. Just saying.", + "You rob an orphanage for {currency} {amount}.", + "You break into the house next door and sell their gaming PC on E-Bay for {currency} {amount}.", + "You work as a scam seller on Amazon selling fake airpods for {currency} {amount}.", + "You break into Rapunzel's kingdom, steal her hair, and sell it on the black market for {currency} {amount}.", + "You are a high school chemistry teacher diagnosed with lung cancer & turn to selling meth for {currency} {amount} to secure your family's future.", + "You punched some random person and they gave you {currency} {amount} to stop.", + "You smashed a kid's piggy bank and got {currency} {amount} from it.", + "What you did was too horrible to speak of. I can't believe you would do that. Was the {currency} {amount} even worth it for those horrible crimes you did? No.", + "You were hired as an assassin and you succeeded, earning {currency} {amount}.", + "You need some extra cash for your drug habit. You break into the local dirty video store and rob them of {currency} {amount}! You also take a few \"items\" for yourself..." ], "failure": [ - "You break into the house next door only to find the whole family eating dinner together. Your bail cost {currency} {}.", - "You got shot trying to smuggle drugs across the border. The medical bills cost you a whopping {currency} {}.", - "You get caught shoplifting by the local mall cop, who fines you for {currency} {}.", - "You tried to do a prank call but called the police instead and were fined {currency} {}.", - "You tried to rob a McDonalds but Ronald Mcdonald Big Mac'd you in the face and stole {currency} {} from you.", - "You tried to rob someone but they just mugged you instead. You lost {currency} {}.", - "You attempted to steal a bar of chocolate from a local store but were caught and had to pay {currency} {}. It was bad chocolate.", - "You tried to jump the old lady walking down the street. Turns out she had a gun, and robbed you blind of {currency} {}.", - "You attempted to cook up some drugs to sell on the black market, but the chemicals exploded in your face, costing you {currency} {} in medical bills." + "You break into the house next door only to find the whole family eating dinner together. Your bail cost {currency} {amount}.", + "You got shot trying to smuggle drugs across the border. The medical bills cost you a whopping {currency} {amount}.", + "You get caught shoplifting by the local mall cop, who fines you for {currency} {amount}.", + "You tried to do a prank call but called the police instead and were fined {currency} {amount}.", + "You tried to rob a McDonalds but Ronald Mcdonald Big Mac'd you in the face and stole {currency} {amount} from you.", + "You tried to rob someone but they just mugged you instead. You lost {currency} {amount}.", + "You attempted to steal a bar of chocolate from a local store but were caught and had to pay {currency} {amount}. It was bad chocolate.", + "You tried to jump the old lady walking down the street. Turns out she had a gun, and robbed you blind of {currency} {amount}.", + "You attempted to cook up some drugs to sell on the black market, but the chemicals exploded in your face, costing you {currency} {amount} in medical bills." ] }, "deposit": { "noMoney": "{red_x} You don't have any money to deposit!", - "notEnough": "{red_x} You cannot deposit more than {currency} {}!", - "success": "{green_tick} Deposited {currency} {} to your bank!" + "notEnough": "{red_x} You cannot deposit more than {currency} {amount}!", + "success": "{green_tick} Deposited {currency} {amount} to your bank!" }, "pay": { "paySelf": "{red_x} You cannot pay yourself!", "payBots": "{red_x} You cannot pay bots!", - "notEnough": "{red_x} You don't have that much money to give. You currently have {currency} {} on hand.", - "success": "{green_tick} {mention} has received your {currency} {}." + "notEnough": "{red_x} You don't have that much money to give. You currently have {currency} {amount} on hand.", + "success": "{green_tick} {mention} has received your {currency} {amount}." }, "rob": { "robSelf": "{red_x} You cannot rob yourself!", "robBots": "{red_x} You cannot rob bots, they are too powerful for you!", - "timeout": ":stopwatch: You can attempt to rob another member {}.", - "failure": "You were caught attempting to rob {mention}, and have been fined {currency} {}.", - "success": "{green_tick} You robbed {currency} {} from {mention}!" + "timeout": ":stopwatch: You can attempt to rob another member {timestamp}.", + "failure": "You were caught attempting to rob {mention}, and have been fined {currency} {amount}.", + "success": "{green_tick} You robbed {currency} {amount} from {mention}!" }, "withdraw": { "noMoney": "{red_x} You don't have any money in your bank to withdraw!", - "tooMuch": "{red_x} You cannot withdraw more than {currency} {}!", - "success": "{green_tick} Withdrew {currency} {} from your bank!" + "tooMuch": "{red_x} You cannot withdraw more than {currency} {amount}!", + "success": "{green_tick} Withdrew {currency} {amount} from your bank!" }, "work": { - "timeout": ":stopwatch: You can next work {}.", + "timeout": ":stopwatch: You can next work {timestamp}.", "success": [ - "You suggest something good and get rewarded {currency} {}.", - "You drove the school bus today and were only 5 minutes late, but you still got {currency} {} for your efforts!", - "You dig up some buried treasure on an island and find {currency} {} worth of gold jewelry!", - "You work as a teacher and earn {currency} {} for inspiring young minds.", - "Your boring nine-to-five office job pays you {currency} {}.", - "You've worked on a farm cultivating wheat from dawn to dusk. The land lord pays you {currency} {} for your struggles.", - "You discover a cure for a rare disease and earn {currency} {} in grant money!", - "Your recent novel becomes a hit, earning you {currency} {} in royalties.", - "You find a rare fossil on the beach and sell it to the museum for {currency} {}.", - "You invested in the right stocks a the right time, earning {currency} {}.", - "Your NFT collection surges in price, so you sell them for {currency} {}.", - "You finished digging in the mines for the day. It's hard work, but they paid you {currency} {}.", - "Dogecoin went to the moon! Your patient waiting got you {currency} {}.", - "The lemonade sold well. Your efforts gathered you {currency} {}.", - "Your dog dug up some cash. Finders keepers! {currency} {}", - "You decided to buy a lottery ticket. You won {currency} {}.", - "You made a viral video on the internet and got {currency} {} from ad revenue.", - "You found a lost cat and were given {currency} {} as a thanks.", - "You decided to become a web developer (why). Anyway you earned {currency} {}." + "You suggest something good and get rewarded {currency} {amount}.", + "You drove the school bus today and were only 5 minutes late, but you still got {currency} {amount} for your efforts!", + "You dig up some buried treasure on an island and find {currency} {amount} worth of gold jewelry!", + "You work as a teacher and earn {currency} {amount} for inspiring young minds.", + "Your boring nine-to-five office job pays you {currency} {amount}.", + "You've worked on a farm cultivating wheat from dawn to dusk. The land lord pays you {currency} {amount} for your struggles.", + "You discover a cure for a rare disease and earn {currency} {amount} in grant money!", + "Your recent novel becomes a hit, earning you {currency} {amount} in royalties.", + "You find a rare fossil on the beach and sell it to the museum for {currency} {amount}.", + "You invested in the right stocks a the right time, earning {currency} {amount}.", + "Your NFT collection surges in price, so you sell them for {currency} {amount}.", + "You finished digging in the mines for the day. It's hard work, but they paid you {currency} {amount}.", + "Dogecoin went to the moon! Your patient waiting got you {currency} {amount}.", + "The lemonade sold well. Your efforts gathered you {currency} {amount}.", + "Your dog dug up some cash. Finders keepers! {currency} {amount}", + "You decided to buy a lottery ticket. You won {currency} {amount}.", + "You made a viral video on the internet and got {currency} {amount} from ad revenue.", + "You found a lost cat and were given {currency} {amount} as a thanks.", + "You decided to become a web developer (why). Anyway you earned {currency} {amount}." ] } }, "fun": { "action": { "failure": "I was unable to fetch that emote!", - "bite": "takes a bit out of {}.", - "brofist": "and {} brofist!", - "cuddle": "cuddles with {}.", - "handhold": "and {} hold hands. How sweet <3", - "hug": "gives {} a big hug!", - "kiss": "kisses {}.", - "lick": "licks {}... gross!", - "pat": "gives {} a little pat on the head", - "pinch": "pinches {}. Ouch!", - "poke": "gives {} a little poke.", - "punch": "punches {} right in the face!", - "slap": "slaps {}. They deserved it!", - "smack": "gives {} a smack they will remember.", - "sorry": "apologizes to {}.", - "stare": "won't stop staring at {}...", - "thumbsup": "gives {} two thumbs up!", - "tickle": "tickles {}.", - "wave": "waves at {}. ", - "wink": "winks at {}." + "bite": "takes a bit out of {target}.", + "brofist": "and {target} brofist!", + "cuddle": "cuddles with {target}.", + "handhold": "and {target} hold hands. How sweet <3", + "hug": "gives {target} a big hug!", + "kiss": "kisses {target}.", + "lick": "licks {target}... gross!", + "pat": "gives {target} a little pat on the head", + "pinch": "pinches {target}. Ouch!", + "poke": "gives {target} a little poke.", + "punch": "punches {target} right in the face!", + "slap": "slaps {target}. They deserved it!", + "smack": "gives {target} a smack they will remember.", + "sorry": "apologizes to {target}.", + "stare": "won't stop staring at {target}...", + "thumbsup": "gives {target} two thumbs up!", + "tickle": "tickles {target}.", + "wave": "waves at {target}. ", + "wink": "winks at {target}." }, "cute": "I was unable to fetch any cute pictures!", "eightBall": { @@ -186,10 +186,10 @@ "removed": "{blue_x} Welcome channel successfully removed!", "set": "{blue_x} Welcome channel set to {channel}", "reset": "Would you like to reset the greeting system?\nThis will delete **ALL** data!", - "welcomeConfig": "**Welcome Channel:** {}", - "greetingConfig": "**Greeting:** {}", - "farewellConfig": "**Farewell:** {}", - "joinDmConfig": "**Join DM:** {}" + "welcomeConfig": "**Welcome Channel:** {channel_or_none}", + "greetingConfig": "**Greeting:** {message}", + "farewellConfig": "**Farewell:** {message}", + "joinDmConfig": "**Join DM:** {message}" }, "joinDm": { "reset": "{blue_x} Join DM message successfully removed!", @@ -211,7 +211,7 @@ "disable": "{blue_tick} Level-up messages will no longer be sent through DMs." }, "mod": { - "set": "{blue_tick} Leveling messages will now only display every **{}** levels.", + "set": "{blue_tick} Leveling messages will now only display every **{modulus}** levels.", "reset": "{blue_tick} Leveling messages have been reset to display every level." }, "serverBackground": { @@ -224,19 +224,19 @@ "disable": "{blue_tick} Leveling messages will now be displayed!" }, "reward": { - "add": "{blue_tick} Users will now receive the {role} role at level **{}**.", + "add": "{blue_tick} Users will now receive the {role} role at level **{level}**.", "remove": "{blue_tick Successfully removed the {role} reward role.", "failure": "I cannot reward that role! Please check my permissions and role position." }, "config": { - "channel": "**Level-up Channel:** {}", - "modulus": "**Leveling Modulus:** {}", - "muted": "**Is Muted:** {}", - "dms": "**Level-Up DMs:** {}", - "message": "**Custom Message:** {}", - "background": "**Custom Background:** {}" + "channel": "**Level-up Channel:** {channel_or_none}", + "modulus": "**Leveling Modulus:** {modulus}", + "muted": "**Is Muted:** {boolean}", + "dms": "**Level-Up DMs:** {boolean}", + "message": "**Custom Message:** {message}", + "background": "**Custom Background:** {url}" }, - "reset": "{blue_tick} All leveling data was reset for **{}**.", + "reset": "{blue_tick} All leveling data was reset for **{username}**.", "resetAll": "Would you like to reset the leveling system?\nThis will delete **ALL** data!" }, "rankCard": { @@ -246,14 +246,14 @@ "failure": "Unable to set that URL as your background!" }, "color": { - "success": "Successfully updated your color to **{}**", + "success": "Successfully updated your color to **{color}**", "failure": "That is not a valid hex code, please use a valid color." }, "accent": { - "success": "Successfully updated your accent color to **{}**", + "success": "Successfully updated your accent color to **{color}**", "failure": "That is not a valid hex code, please use a valid color." }, - "opacity": "Successfully updated your opacity to **{}%**", + "opacity": "Successfully updated your opacity to **{opacity}%**", "reset": "Successfully reset your rank card to default settings!" }, "rank": { @@ -262,27 +262,27 @@ "accessFailure": "An error occurred while trying to access that rank card!" }, "rewards": { - "reward": "Level {} ----> {role}", + "reward": "Level {level} ----> {role}", "title": ":crown: Leveling Rewards", "noRewards": "{blue_x} No leveling rewards have been set for this server!" }, "top": { "guild": { "name": "Guild Leaderboards", - "more": ":sparkles: **More?** `/top {}`", - "title": "TOP 5 {} {}" + "more": ":sparkles: **More?** `/top {type}`", + "title": "TOP 5 {type} {emote}" }, "leveling": { "name": "Leveling Leaderboard", "empty": "Nobody has earned any XP or levels yet!\nSend some messages in chat and use `/rank` to get started!", - "entry": "#{} | {user} XP: `{}`" + "entry": "#{rank} | {user} XP: `{xp}`" }, "economy": { "name": "Economy Leaderboard", "empty": "Nobody has earned any money yet!\nUse `/work` and `/balance` to get started!", - "entry": "#{} | {user} {currency} {}" + "entry": "#{rank} | {user} {currency} {amount}" }, - "footer": "Page {}/{} • Your rank: #{}" + "footer": "Page {current}/{max} • Your rank: #{rank}" } }, "music": { @@ -292,9 +292,9 @@ "differentChannel": "You are not in the same voice channel as TechnoBot!", "songDuration": "Song Duration", "position": "Position in Queue", - "addedBy": "Added By {}", - "addSong": "{blue_tick} **{}** successfully added!", - "addPlaylist": ":ballot_box_with_check: Added {} tracks from playlist `{}`", + "addedBy": "Added By {username}", + "addSong": "{blue_tick} **{song}** successfully added!", + "addPlaylist": ":ballot_box_with_check: Added {amount} tracks from playlist `{name}`", "invalidSong": "That is not a valid song!", "invalidLink": "That is not a valid link!" }, @@ -303,7 +303,7 @@ "title": "Now Playing :musical_note:", "positionTitle": "Position", "progressTitle": "Progress", - "progress": "{} / {}" + "progress": "{current} / {max}" }, "pause": { "success": ":pause_button: Paused the music player!", @@ -319,7 +319,7 @@ "title": "Music Queue :musical_note:", "song": "Song", "songPlural": "Songs", - "footer": "**{} {} in Queue | {} Total Length**", + "footer": "**{count} {songs} in Queue | {time} Total Length**", "nowPlaying": "__Now Playing:__", "upNext": "__Up Next:__" }, @@ -332,7 +332,7 @@ "failure": "The player is not paused!" }, "seek": { - "success": ":fast_forward: Set position to `{}`", + "success": ":fast_forward: Set position to `{time}`", "tooLong": "Time cannot be longer than the song!", "invalidTimestamp": "That is not a valid timestamp!" }, @@ -345,7 +345,7 @@ "failure": "The music player is already stopped!" }, "volume": { - "success": ":loud_sound: Set volume to {}%", + "success": ":loud_sound: Set volume to {volume}%", "failure": "You must specify a volume between 0 and 100!" } }, @@ -356,27 +356,27 @@ "kick": "Kick", "warn": "Warn" }, - "server": "**Server:** {}", + "server": "**Server:** {name}", "actionedBy": "**Actioned By:** {mention}", - "action": "**Action:** {}", - "duration": "**Duration:** {}", - "reason": "**Reason:** {}" + "action": "**Action:** {action}", + "duration": "**Duration:** {time}", + "reason": "**Reason:** {reason}" }, "ban": { "banBot": "Did you seriously expect me to ban myself?", "tooHighRole": "This member cannot be banned. I need my role moved higher than theirs.", - "duration": "{} Days", - "message": "{} has been banned{}" + "duration": "{amount} Days", + "message": "{name} has been banned{time}" }, "clear": { - "success": ":ballot_box_with_check: I have deleted `{} messages!`", + "success": ":ballot_box_with_check: I have deleted `{count} messages!`", "failure": "You cannot clear messages older than 2 weeks!" }, "kick": { "kickForeign": "That user is not in this server!", "kickBot": "Did you seriously expect me to kick myself?", "tooHighRole": "This member cannot be kicked. I need my role moved higher than theirs.", - "message": "{} has been kicked" + "message": "{name} has been kicked" }, "lock": { "success": ":lock: {channel} has been locked.", @@ -388,7 +388,7 @@ "tooHighRole": "This member cannot be muted. I need my role moved higher than theirs.", "noRole": "This server does not have a mute role, use `/mute-role ` to set one or `/mute-role create [name]` to create one.", "alreadyMuted": "This user is already muted!", - "message": "{} has been muted" + "message": "{name} has been muted" }, "muteRole": { "noPerm": "I am unable to create roles. Please check my permissions and role position.", @@ -396,9 +396,9 @@ "success": "{blue_tick} The {mention} role will be user for the `/mute` command." }, "removeWarn": { - "successId": "{green_tick} Warning #{} has been removed.", + "successId": "{green_tick} Warning #{id} has been removed.", "failureId": "Unable to find a warning with that ID!", - "successUser": "{green_tick} {} warnings have been removed for {mention}.", + "successUser": "{green_tick} {count} warnings have been removed for {mention}.", "failureUser": "That user has no warnings!", "failure": "You must specify a user or a warning ID!" }, @@ -406,29 +406,29 @@ "roleForeign": "That user is not in this server!", "botManagedRole": "I cannot give/remove bot/managed roles!", "tooHighRole": "This member cannot be updated. I need my role moved higher than theirs.", - "message": "{green_tick} Changed roles for {}, " + "message": "{green_tick} Changed roles for {name}, " }, "setNick": { "nickForeign": "That user is not in this server!", - "set": "{green_tick} **{}**'s nickname has been changed to **{}**.", - "reset": "{green_tick} **{}**'s nickname has been reset.", + "set": "{green_tick} **{name}**'s nickname has been changed to **{nickname}**.", + "reset": "{green_tick} **{name}**'s nickname has been reset.", "tooHighRole": "This member cannot be updated. I need my role moved higher than theirs." }, "slowMode": { "failureThread": "You cannot set slow mode on threads!", "disable": ":stopwatch: Slow mode has been disabled in this channel.", "tooHigh": "Time should be less than or equal to **6 hours**.", - "set": ":stopwatch: This channel slow mode delay has been set to **{}**.", - "display": ":stopwatch: This channel slow mode delay is **{}**.", + "set": ":stopwatch: This channel slow mode delay has been set to **{amount}**.", + "display": ":stopwatch: This channel slow mode delay is **{amount}**.", "format": { - "hours": "{} hours", - "minutes": "{} minutes", - "seconds": "{} seconds" + "hours": "{amount} hours", + "minutes": "{amount} minutes", + "seconds": "{amount} seconds" } }, "unban": { "unbanSelf": "Ah yes, let me just unban myself...", - "success": "{} has been unbanned", + "success": "{name} has been unbanned", "noUser": "That user does not exist!", "invalidUser": "That is not a valid user ID!" }, @@ -443,29 +443,29 @@ "tooHighRole": "This member cannot be unmuted. I need my role moved higher than theirs.", "noRole": "This server does not have a mute role, use `/mute-role ` to set one or `/mute-role create [name]` to create one.", "notMuted": "This user is not muted!", - "message": "{} has been unmuted" + "message": "{name} has been unmuted" }, "warn": { "warnForeign": "That user is not in this server!", "warnBot": "Why would I warn myself... silly human!", "warnSelf": "You cannot warn yourself!", - "message": "{} has been warned" + "message": "{name} has been warned" }, "warnings": { - "noWarnings": "{} has no infractions!", - "title": "{}'s Infractions", + "noWarnings": "{name} has no infractions!", + "title": "{name}'s Infractions", "lastDay": "Last 24 hours", "lastWeek": "Last 7 days", "total": "Total", "last10": "[ID] Last 10 Warnings", - "message": "{} warnings" + "message": "{count} warnings" }, "reasonUnspecified": "Unspecified" }, "starboard": { "create": "{blue_tick} Set the starboard channel to {channel}", "limit": { - "set": "{blue_tick} Messages now require {} stars to show up on the starboard.", + "set": "{blue_tick} Messages now require {amount} stars to show up on the starboard.", "reset": "{blue_tick} Reset the star limit to default." }, "blacklist": { @@ -493,13 +493,13 @@ "disable": "{blue_x} Users can no longer star their own messages!" }, "config": { - "threshold": "**Threshold:** {}", - "channel": "**Channel:** {}", - "allowNsfw": "**Allow NSFW:** {}", - "allowSelf": "**Allow Self Stars:** {}", - "showJumpLinks": "**Show Jump Links:** {}", - "locked": "**Locked:** {}", - "blacklistedChannels": "**Blacklisted Channels:** {}" + "threshold": "**Threshold:** {amount}", + "channel": "**Channel:** {channel_or_none}", + "allowNsfw": "**Allow NSFW:** {boolean}", + "allowSelf": "**Allow Self Stars:** {boolean}", + "showJumpLinks": "**Show Jump Links:** {boolean}", + "locked": "**Locked:** {boolean}", + "blacklistedChannels": "**Blacklisted Channels:** {list}" } }, "suggestions": { @@ -540,9 +540,9 @@ "disable": "{blue_x} Anonymous suggestions have been **disabled**!" }, "config": { - "channel": "**Channel:** {}", - "dm": "**Reponse DMs:** {}", - "anonymous": "**Anonymous Suggestions:** {}" + "channel": "**Channel:** {channel_or_none}", + "dm": "**Reponse DMs:** {boolean}", + "anonymous": "**Anonymous Suggestions:** {booolean}" }, "reset": "Would you like to reset the suggestions system?\nThis will delete **ALL** data!" } From 20952d75788b44f7beb2a38dcd6f33d8a2df9a05 Mon Sep 17 00:00:00 2001 From: theonlytails Date: Tue, 28 Jun 2022 13:31:21 +0300 Subject: [PATCH 13/15] fix(l10n): i misspelled "boolean" Signed-off-by: theonlytails --- src/main/resources/localization/en_us.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/localization/en_us.json b/src/main/resources/localization/en_us.json index 01b8b67..6964863 100644 --- a/src/main/resources/localization/en_us.json +++ b/src/main/resources/localization/en_us.json @@ -542,7 +542,7 @@ "config": { "channel": "**Channel:** {channel_or_none}", "dm": "**Reponse DMs:** {boolean}", - "anonymous": "**Anonymous Suggestions:** {booolean}" + "anonymous": "**Anonymous Suggestions:** {boolean}" }, "reset": "Would you like to reset the suggestions system?\nThis will delete **ALL** data!" } From f62b8761ec22e23ffedbcf2091c4c84c33d58b7b Mon Sep 17 00:00:00 2001 From: theonlytails Date: Wed, 29 Jun 2022 14:48:23 +0300 Subject: [PATCH 14/15] fix(economy): replaced pojo methods with records methods Signed-off-by: theonlytails --- dependency-reduced-pom.xml | 22 +++++++++++++++++++ .../commands/economy/CrimeCommand.java | 4 ++-- .../commands/economy/RobCommand.java | 2 +- .../commands/economy/WorkCommand.java | 4 ++-- 4 files changed, 27 insertions(+), 5 deletions(-) diff --git a/dependency-reduced-pom.xml b/dependency-reduced-pom.xml index edaf8c9..24e147f 100644 --- a/dependency-reduced-pom.xml +++ b/dependency-reduced-pom.xml @@ -26,6 +26,28 @@ + + org.jsonschema2pojo + jsonschema2pojo-maven-plugin + 1.1.2 + + + + generate + + + + + src/main/resources/localization/en_us.json + technobot.util.localization + false + true + false + false + gson + json + + diff --git a/src/main/java/technobot/commands/economy/CrimeCommand.java b/src/main/java/technobot/commands/economy/CrimeCommand.java index a9c1c2a..d0c6db0 100644 --- a/src/main/java/technobot/commands/economy/CrimeCommand.java +++ b/src/main/java/technobot/commands/economy/CrimeCommand.java @@ -43,9 +43,9 @@ public void execute(SlashCommandInteractionEvent event) { // Commit crime EconomyReply reply = economyHandler.crime(user); int color = reply.isSuccess() ? EmbedColor.SUCCESS.color : EmbedColor.ERROR.color; - embed.setDescription(reply.getResponse()); + embed.setDescription(reply.response()); embed.setColor(color); - embed.setFooter(get(s -> s.economy.replyId, reply.getId())); + embed.setFooter(get(s -> s.economy.replyId, reply.id())); event.replyEmbeds(embed.build()).queue(); } } diff --git a/src/main/java/technobot/commands/economy/RobCommand.java b/src/main/java/technobot/commands/economy/RobCommand.java index 3ed8fa5..5216f36 100644 --- a/src/main/java/technobot/commands/economy/RobCommand.java +++ b/src/main/java/technobot/commands/economy/RobCommand.java @@ -62,7 +62,7 @@ public void execute(SlashCommandInteractionEvent event) { // Rob target EconomyReply reply = economyHandler.rob(user.getIdLong(), target.getIdLong()); embed.setColor(reply.isSuccess() ? EmbedColor.SUCCESS.color : EmbedColor.ERROR.color); - embed.setDescription(reply.getResponse()); + embed.setDescription(reply.response()); event.replyEmbeds(embed.build()).queue(); } } diff --git a/src/main/java/technobot/commands/economy/WorkCommand.java b/src/main/java/technobot/commands/economy/WorkCommand.java index adefacf..37b4d0e 100644 --- a/src/main/java/technobot/commands/economy/WorkCommand.java +++ b/src/main/java/technobot/commands/economy/WorkCommand.java @@ -42,9 +42,9 @@ public void execute(SlashCommandInteractionEvent event) { } else { // Work EconomyReply reply = economyHandler.work(user); - embed.setDescription(reply.getResponse()); + embed.setDescription(reply.response()); embed.setColor(EmbedColor.SUCCESS.color); - embed.setFooter(get(s -> s.economy.replyId, reply.getId())); + embed.setFooter(get(s -> s.economy.replyId, reply.id())); event.replyEmbeds(embed.build()).queue(); } } From ce87b4a2ebbd1eb987b32e577f9e90121060420f Mon Sep 17 00:00:00 2001 From: theonlytails Date: Thu, 30 Jun 2022 16:16:55 +0300 Subject: [PATCH 15/15] feat(l10): migrated all the new features to the l10n system Signed-off-by: theonlytails --- .../commands/economy/BalanceCommand.java | 5 +- .../commands/economy/BuyCommand.java | 12 +- .../commands/economy/EconomyCommand.java | 2 +- .../commands/economy/InspectCommand.java | 6 +- .../commands/economy/InventoryCommand.java | 9 +- .../commands/economy/ItemCommand.java | 56 +++++--- .../commands/economy/ShopCommand.java | 11 +- .../commands/fun/InspireCommand.java | 9 +- .../commands/fun/WouldYouRatherCommand.java | 19 +-- .../commands/music/PauseCommand.java | 4 +- .../technobot/commands/music/PlayCommand.java | 4 +- .../commands/music/RepeatCommand.java | 11 +- .../technobot/commands/music/SeekCommand.java | 2 +- .../technobot/commands/music/SkipCommand.java | 2 + .../commands/utility/AfkCommand.java | 4 +- .../commands/utility/HelpCommand.java | 4 +- .../commands/utility/InviteCommand.java | 15 +- .../commands/utility/PollCommand.java | 9 +- .../commands/utility/SupportCommand.java | 28 ++-- .../commands/utility/TwitterCommand.java | 20 +-- .../commands/utility/UserCommand.java | 2 +- .../commands/utility/VoteCommand.java | 20 ++- .../commands/utility/YouTubeCommand.java | 19 ++- .../java/technobot/handlers/MusicHandler.java | 105 +++++++------- .../handlers/economy/EconomyHandler.java | 11 +- .../java/technobot/listeners/AfkListener.java | 20 ++- .../technobot/listeners/ButtonListener.java | 26 +++- .../technobot/listeners/GuildListener.java | 4 +- .../technobot/listeners/LevelingListener.java | 4 +- .../technobot/listeners/MusicListener.java | 26 ++-- .../listeners/StarboardListener.java | 20 ++- .../java/technobot/util/Localization.java | 3 +- src/main/resources/localization/en_us.json | 128 ++++++++++++++++-- 33 files changed, 417 insertions(+), 203 deletions(-) diff --git a/src/main/java/technobot/commands/economy/BalanceCommand.java b/src/main/java/technobot/commands/economy/BalanceCommand.java index 930fc26..efac8ca 100644 --- a/src/main/java/technobot/commands/economy/BalanceCommand.java +++ b/src/main/java/technobot/commands/economy/BalanceCommand.java @@ -33,8 +33,7 @@ public BalanceCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { // Get user - OptionMapping userOption = event.getOption("user"); - User user = (userOption != null) ? userOption.getAsUser() : event.getUser(); + User user = event.getOption("user", event.getUser(), OptionMapping::getAsUser); // Get balance and bank values EconomyHandler economyHandler = GuildData.get(event.getGuild()).economyHandler; @@ -61,7 +60,7 @@ public void execute(SlashCommandInteractionEvent event) { .addField(get(s -> s.economy.balance.cash), currency + " " + EconomyHandler.FORMATTER.format(balance), true) .addField(get(s -> s.economy.balance.bank), currency + " " + EconomyHandler.FORMATTER.format(bank), true) .addField(get(s -> s.economy.balance.total), currency + " " + EconomyHandler.FORMATTER.format(total), true) - .setColor(EmbedColor.DEFAULT.color); + .setColor(EmbedColor.DEFAULT.color); event.replyEmbeds(embed.build()).queue(); } } diff --git a/src/main/java/technobot/commands/economy/BuyCommand.java b/src/main/java/technobot/commands/economy/BuyCommand.java index 89523b4..5a0ce62 100644 --- a/src/main/java/technobot/commands/economy/BuyCommand.java +++ b/src/main/java/technobot/commands/economy/BuyCommand.java @@ -13,6 +13,8 @@ import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that buys an item from the server shop. * @@ -37,7 +39,9 @@ public void execute(SlashCommandInteractionEvent event) { String itemName = event.getOption("item").getAsString(); Item item = guildData.configHandler.getItem(itemName); if (item == null) { - event.replyEmbeds(EmbedUtils.createError("That item doesn't exist! See all valid items with `/shop`")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.economy.buy.noItem) + )).setEphemeral(true).queue(); return; } @@ -47,8 +51,7 @@ public void execute(SlashCommandInteractionEvent event) { // Purchase was successful econ.buyItem(event.getUser().getIdLong(), item); if (item.getShowInInventory()) { - String price = econ.getCurrency() + " " + item.getPrice(); - String text = EmbedUtils.GREEN_TICK + " You have bought 1 " + item.getName() + " for " + price + "! This is now in your inventory.\nUse this item with the `/use ` command."; + String text = get(s -> s.economy.buy.success, item.getName(), item.getPrice()); EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.SUCCESS.color) .setAuthor(event.getUser().getAsTag(), null, event.getUser().getEffectiveAvatarUrl()) @@ -60,8 +63,7 @@ public void execute(SlashCommandInteractionEvent event) { } } else { // Not enough money to purchase - String value = econ.getCurrency() + " " + EconomyHandler.FORMATTER.format(balance); - String text = " You do not have enough money to buy this item. You currently have "+value+" on hand."; + String text = get(s -> s.economy.buy.noMoney, EconomyHandler.FORMATTER.format(balance)); EmbedBuilder embed = new EmbedBuilder().setDescription(EmbedUtils.RED_X + text).setColor(EmbedColor.ERROR.color); event.replyEmbeds(embed.build()).setEphemeral(true).queue(); } diff --git a/src/main/java/technobot/commands/economy/EconomyCommand.java b/src/main/java/technobot/commands/economy/EconomyCommand.java index 216f665..3d6bf7b 100644 --- a/src/main/java/technobot/commands/economy/EconomyCommand.java +++ b/src/main/java/technobot/commands/economy/EconomyCommand.java @@ -36,7 +36,7 @@ public void execute(SlashCommandInteractionEvent event) { EconomyHandler economyHandler = GuildData.get(event.getGuild()).economyHandler; String text = ""; - switch(event.getSubcommandName()) { + switch (event.getSubcommandName()) { case "currency" -> { OptionMapping symbolOption = event.getOption("symbol"); if (symbolOption != null) { diff --git a/src/main/java/technobot/commands/economy/InspectCommand.java b/src/main/java/technobot/commands/economy/InspectCommand.java index 7c8ab11..a721666 100644 --- a/src/main/java/technobot/commands/economy/InspectCommand.java +++ b/src/main/java/technobot/commands/economy/InspectCommand.java @@ -10,6 +10,8 @@ import technobot.data.cache.Item; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that displays details about a shop item * @@ -32,7 +34,9 @@ public void execute(SlashCommandInteractionEvent event) { Item item = guildData.configHandler.getItem(event.getOption("item").getAsString()); if (item == null) { - event.replyEmbeds(EmbedUtils.createError("That item doesn't exist!")).setEphemeral(true).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.economy.inspect) + )).setEphemeral(true).queue(); return; } event.replyEmbeds(item.toEmbed(currency)).queue(); diff --git a/src/main/java/technobot/commands/economy/InventoryCommand.java b/src/main/java/technobot/commands/economy/InventoryCommand.java index 57f89c7..19b9c1f 100644 --- a/src/main/java/technobot/commands/economy/InventoryCommand.java +++ b/src/main/java/technobot/commands/economy/InventoryCommand.java @@ -9,10 +9,11 @@ import technobot.data.GuildData; import technobot.data.cache.Item; import technobot.util.embeds.EmbedColor; -import technobot.util.embeds.EmbedUtils; import java.util.LinkedHashMap; +import static technobot.util.Localization.get; + /** * Command that shows a user's inventory. * @@ -36,12 +37,12 @@ public void execute(SlashCommandInteractionEvent event) { EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setAuthor(user.getAsTag()+"'s Inventory", null, user.getEffectiveAvatarUrl()) - .setDescription("Use an item with the `/use ` command."); + .setAuthor(get(s -> s.economy.inventory.user, user.getAsTag()), null, user.getEffectiveAvatarUrl()) + .setDescription(get(s -> s.economy.inventory.description)); LinkedHashMap inv = guildData.economyHandler.getInventory(user.getIdLong()); if (inv == null || inv.isEmpty()) { - embed.setDescription("You do not have any items!"); + embed.setDescription(get(s -> s.economy.inventory.noItems)); event.replyEmbeds(embed.build()).queue(); return; } diff --git a/src/main/java/technobot/commands/economy/ItemCommand.java b/src/main/java/technobot/commands/economy/ItemCommand.java index 36f20c5..767e766 100644 --- a/src/main/java/technobot/commands/economy/ItemCommand.java +++ b/src/main/java/technobot/commands/economy/ItemCommand.java @@ -15,6 +15,8 @@ import technobot.handlers.ConfigHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that performs CRUD operations for economy shop items. * @@ -68,61 +70,63 @@ public void execute(SlashCommandInteractionEvent event) { String text = ""; String name = event.getOption("name").getAsString(); - switch(event.getSubcommandName()) { + switch (event.getSubcommandName()) { case "create" -> { if (configHandler.getConfig().getShop().size() >= MAX_SHOP_SIZE) { - text = "You have reached the maximum item limit! Use `/item remove` to make some room before adding a new item."; + text = get(s -> s.economy.item.create.maxReached); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); return; } if (name.length() < 3) { - text = "The minimum length for an item name is 3 characters."; + text = get(s -> s.economy.item.create.tooShort); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); return; } if (configHandler.containsItem(name)) { - text = "There is already an item with that name!"; + text = get(s -> s.economy.item.create.alreadyExists); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); return; } ItemResult result = updateItem(new Item(name), event); MessageEmbed embed = configHandler.addItem(result.item()).toEmbed(currency); - text = EmbedUtils.GREEN_TICK + " Item created successfully!"; + text = get(s -> s.economy.item.create.success); event.reply(text).addEmbeds(embed).queue(); } case "edit" -> { // Get existing item Item item = configHandler.getItem(name); if (item == null) { - text = "That item name doesn't exist!"; + text = get(s -> s.economy.item.noItem); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); return; } // Update item in cache and database ItemResult result = updateItem(item, event); if (!result.isUpdated) { - text = "Use one of the available command options to edit this item!"; + text = get(s -> s.economy.item.edit.notUpdated); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); } else { configHandler.updateItem(item); - text = EmbedUtils.GREEN_TICK + " Item updated successfully!"; + text = get(s -> s.economy.item.edit.success); event.reply(text).addEmbeds(item.toEmbed(currency)).queue(); } } case "remove" -> { if (configHandler.containsItem(name)) { configHandler.removeItem(name); - text = EmbedUtils.BLUE_TICK + " Item has been removed from the store."; + text = get(s -> s.economy.item.remove); event.replyEmbeds(EmbedUtils.createDefault(text)).queue(); } else { - text = "That item name doesn't exist!"; + text = get(s -> s.economy.item.noItem); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); } } case "info" -> { Item item = configHandler.getItem(name); if (item == null) { - event.replyEmbeds(EmbedUtils.createError("That item does not exist!")).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.economy.item.noItem)) + ).queue(); return; } event.replyEmbeds(configHandler.getItem(name).toEmbed(currency)).queue(); @@ -147,37 +151,47 @@ private ItemResult updateItem(Item item, SlashCommandInteractionEvent event) { if (descOption != null) { isUpdated = true; item.setDescription(descOption.getAsString()); - } if (priceOption != null) { + } + if (priceOption != null) { isUpdated = true; item.setPrice(priceOption.getAsLong()); - } if (inventoryOption != null) { + } + if (inventoryOption != null) { isUpdated = true; item.setShowInInventory(inventoryOption.getAsBoolean()); - } if (durationOption != null) { + } + if (durationOption != null) { isUpdated = true; long timestamp = (3600000 * durationOption.getAsLong()) + System.currentTimeMillis(); item.setExpireTimestamp(timestamp); - } if (stockOption != null) { + } + if (stockOption != null) { isUpdated = true; item.setStock(stockOption.getAsLong()); - } if (reqRoleOption != null) { + } + if (reqRoleOption != null) { isUpdated = true; item.setRequiredRole(reqRoleOption.getAsRole().getIdLong()); - } if (roleGivenOption != null) { + } + if (roleGivenOption != null) { isUpdated = true; item.setGivenRole(roleGivenOption.getAsRole().getIdLong()); - } if (roleRemovedOption != null) { + } + if (roleRemovedOption != null) { isUpdated = true; item.setRemovedRole(roleRemovedOption.getAsRole().getIdLong()); - } if (reqBalOption != null) { + } + if (reqBalOption != null) { isUpdated = true; item.setRequiredBalance(reqBalOption.getAsLong()); - } if (replyOption != null) { + } + if (replyOption != null) { isUpdated = true; item.setReplyMessage(replyOption.getAsString()); } return new ItemResult(item, isUpdated); } - record ItemResult(Item item, boolean isUpdated) { } + record ItemResult(Item item, boolean isUpdated) { + } } diff --git a/src/main/java/technobot/commands/economy/ShopCommand.java b/src/main/java/technobot/commands/economy/ShopCommand.java index 80702b5..eeaf3c1 100644 --- a/src/main/java/technobot/commands/economy/ShopCommand.java +++ b/src/main/java/technobot/commands/economy/ShopCommand.java @@ -16,6 +16,8 @@ import java.util.ArrayList; import java.util.List; +import static technobot.util.Localization.get; + /** * Command that displays the server shop and available items. * @@ -36,17 +38,16 @@ public void execute(SlashCommandInteractionEvent event) { // Create base embed template EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setAuthor(event.getGuild().getName()+" Store", null, event.getGuild().getIconUrl()); + .setAuthor(event.getGuild().getName() + " Store", null, event.getGuild().getIconUrl()); // Check if shop is empty GuildData guildData = GuildData.get(event.getGuild()); if (guildData.configHandler.getConfig().getShop().isEmpty()) { - embed.setDescription("There are no items in this shop!\nUse the `/item create ` command to add some."); + embed.setDescription(get(s -> s.economy.shop.empty)); event.replyEmbeds(embed.build()).queue(); return; } - String info = "Buy an item with the `/buy [quantity]` command.\n"+"For more information on an item use the `/inspect ` command."; - embed.setDescription(info); + embed.setDescription(get(s -> s.economy.shop.info)); // Create paginated embeds List embeds = new ArrayList<>(); @@ -58,7 +59,7 @@ public void execute(SlashCommandInteractionEvent event) { count++; if (count % ITEMS_PER_PAGE == 0) { embeds.add(embed.build()); - embed.setDescription(info); + embed.setDescription(get(s -> s.economy.shop.info)); } } if (count % ITEMS_PER_PAGE != 0) { diff --git a/src/main/java/technobot/commands/fun/InspireCommand.java b/src/main/java/technobot/commands/fun/InspireCommand.java index 00ce3bb..02bd181 100644 --- a/src/main/java/technobot/commands/fun/InspireCommand.java +++ b/src/main/java/technobot/commands/fun/InspireCommand.java @@ -6,10 +6,15 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedUtils; -import java.io.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; +import static technobot.util.Localization.get; + /** * Command that generates a funny inspiring quote. * Uses the InspiroBot API. @@ -33,7 +38,7 @@ public void execute(SlashCommandInteractionEvent event) { String pictureUrl = new BufferedReader(new InputStreamReader(input)).readLine(); event.reply(pictureUrl).queue(); } catch (IOException e) { - String text = "I was unable to fetch an inspiring quote!"; + String text = get(s -> s.fun.inspire); event.replyEmbeds(EmbedUtils.createError(text)).queue(); } } diff --git a/src/main/java/technobot/commands/fun/WouldYouRatherCommand.java b/src/main/java/technobot/commands/fun/WouldYouRatherCommand.java index 83fba8b..27297f7 100644 --- a/src/main/java/technobot/commands/fun/WouldYouRatherCommand.java +++ b/src/main/java/technobot/commands/fun/WouldYouRatherCommand.java @@ -15,6 +15,8 @@ import java.io.IOException; +import static technobot.util.Localization.get; + /** * Command that creates a fun 'would you rather' poll using an API. * @@ -40,33 +42,32 @@ public void execute(SlashCommandInteractionEvent event) { bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { - String text = "I was unable to fetch any questions!"; + String text = get(s -> s.fun.wouldYouRather.failure); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } @Override public void onResponse(Call call, final Response response) throws IOException { if (!response.isSuccessful()) { - String text = "I was unable to fetch any questions!"; + String text = get(s -> s.fun.wouldYouRather.failure); event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); return; } - // Build 'Would you Rathe' embed from API response + // Build 'Would you Rather' embed from API response String questions = bot.gson.fromJson(response.body().string(), JsonObject.class).get("data").getAsString(); String[] split = questions.split(" or "); String optionA = ":regional_indicator_a: "+split[0].substring(17); - String optionB = ":regional_indicator_b: "+split[1].substring(0, split[1].length()-1); + String optionB = ":regional_indicator_b: " + split[1].substring(0, split[1].length() - 1); EmbedBuilder embed = new EmbedBuilder() - .setTitle("Would you rather...") + .setTitle(get(s -> s.fun.wouldYouRather.title)) .setColor(EmbedColor.DEFAULT.color) - .setDescription(optionA) - .addField("or", optionB, false); + .setDescription(get(s -> s.fun.wouldYouRather.message, optionA, optionB)); // Send embed and add emoji reactions event.getHook().sendMessageEmbeds(embed.build()).queue(msg -> { - msg.addReaction("\uD83C\uDDE6").queue(); - msg.addReaction("\uD83C\uDDE7").queue(); + msg.addReaction("🇦").queue(); + msg.addReaction("🇧").queue(); }); } }); diff --git a/src/main/java/technobot/commands/music/PauseCommand.java b/src/main/java/technobot/commands/music/PauseCommand.java index de03715..f17af9f 100644 --- a/src/main/java/technobot/commands/music/PauseCommand.java +++ b/src/main/java/technobot/commands/music/PauseCommand.java @@ -29,10 +29,10 @@ public void execute(SlashCommandInteractionEvent event) { if (music == null) return; if (music.isPaused()) { - String text = "The player is already paused!"; + String text = get(s -> s.music.pause.failure); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); } else { - String text = ":pause_button: Paused the music player."; + String text = get(s -> s.music.pause.success); music.pause(); event.replyEmbeds(EmbedUtils.createDefault(text)).queue(); } diff --git a/src/main/java/technobot/commands/music/PlayCommand.java b/src/main/java/technobot/commands/music/PlayCommand.java index e7e1e00..592fdf9 100644 --- a/src/main/java/technobot/commands/music/PlayCommand.java +++ b/src/main/java/technobot/commands/music/PlayCommand.java @@ -38,14 +38,14 @@ public void execute(SlashCommandInteractionEvent event) { // Check if member is in the right voice channel AudioChannel channel = event.getMember().getVoiceState().getChannel(); if (music.getPlayChannel() != channel) { - String text = "You are not in the same voice channel as TechnoBot!"; + String text = get(s -> s.music.play.differentChannel); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); return; } // Cannot have more than 100 songs in the queue if (music.getQueue().size() >= 100) { - String text = "You cannot queue more than 100 songs!"; + String text = get(s -> s.music.play.tooManySongs); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); return; } diff --git a/src/main/java/technobot/commands/music/RepeatCommand.java b/src/main/java/technobot/commands/music/RepeatCommand.java index 9ee5578..2d7ce2e 100644 --- a/src/main/java/technobot/commands/music/RepeatCommand.java +++ b/src/main/java/technobot/commands/music/RepeatCommand.java @@ -6,6 +6,7 @@ import technobot.commands.Command; import technobot.handlers.MusicHandler; import technobot.util.embeds.EmbedUtils; +import technobot.util.localization.Repeat; import static technobot.util.Localization.get; @@ -30,12 +31,10 @@ public void execute(SlashCommandInteractionEvent event) { if (music == null) return; music.loop(); - String text; - if (music.isLoop()) { - text = ":repeat: Repeat has been enabled."; - } else { - text = ":repeat: Repeat has been disabled."; - } + + Repeat repeatText = get(s -> s.music.repeat); + String text = music.isLoop() ? repeatText.enabled : repeatText.disabled; + event.replyEmbeds(EmbedUtils.createDefault(text)).queue(); } } diff --git a/src/main/java/technobot/commands/music/SeekCommand.java b/src/main/java/technobot/commands/music/SeekCommand.java index 08417ae..aea345f 100644 --- a/src/main/java/technobot/commands/music/SeekCommand.java +++ b/src/main/java/technobot/commands/music/SeekCommand.java @@ -52,7 +52,7 @@ public void execute(SlashCommandInteractionEvent event) { // Make sure pos is not longer than track if (pos >= music.getQueue().getFirst().getDuration()) { - String text = "The timestamp cannot be longer than the song!"; + String text = get(s -> s.music.seek.tooLong); event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue(); return; } diff --git a/src/main/java/technobot/commands/music/SkipCommand.java b/src/main/java/technobot/commands/music/SkipCommand.java index c35fc77..72086bf 100644 --- a/src/main/java/technobot/commands/music/SkipCommand.java +++ b/src/main/java/technobot/commands/music/SkipCommand.java @@ -8,6 +8,8 @@ import technobot.handlers.MusicHandler; import technobot.util.embeds.EmbedUtils; +import static technobot.util.Localization.get; + /** * Command that skips the current song. * diff --git a/src/main/java/technobot/commands/utility/AfkCommand.java b/src/main/java/technobot/commands/utility/AfkCommand.java index cc3db01..cf86b1f 100644 --- a/src/main/java/technobot/commands/utility/AfkCommand.java +++ b/src/main/java/technobot/commands/utility/AfkCommand.java @@ -11,6 +11,8 @@ import java.util.Date; +import static technobot.util.Localization.get; + /** * Command that allows a user to set their AFK status message. * @@ -30,6 +32,6 @@ public void execute(SlashCommandInteractionEvent event) { OptionMapping option = event.getOption("message"); String message = option != null ? option.getAsString() : ""; AfkListener.AFK_MESSAGES.put(event.getMember(), new AfkListener.AfkStatus(message, new Date().toInstant())); - event.reply(":wave: | **"+event.getMember().getEffectiveName()+"** has gone AFK. See you later!").queue(); + event.reply(get(s -> s.utility.afk) + "").queue(); } } diff --git a/src/main/java/technobot/commands/utility/HelpCommand.java b/src/main/java/technobot/commands/utility/HelpCommand.java index 6099a8a..92ee41d 100644 --- a/src/main/java/technobot/commands/utility/HelpCommand.java +++ b/src/main/java/technobot/commands/utility/HelpCommand.java @@ -55,7 +55,9 @@ public void execute(SlashCommandInteractionEvent event) { OptionMapping option = event.getOption("category"); OptionMapping commandOption = event.getOption("command"); if (option != null && commandOption != null) { - event.replyEmbeds(EmbedUtils.createError("Please only give one optional argument and try again.")).queue(); + event.replyEmbeds(EmbedUtils.createError( + get(s -> s.utility.help.oneArgument) + )).queue(); } else if (option != null) { // Display category commands menu Category category = Category.valueOf(option.getAsString().toUpperCase()); diff --git a/src/main/java/technobot/commands/utility/InviteCommand.java b/src/main/java/technobot/commands/utility/InviteCommand.java index f2dee9f..6d38eaf 100644 --- a/src/main/java/technobot/commands/utility/InviteCommand.java +++ b/src/main/java/technobot/commands/utility/InviteCommand.java @@ -6,6 +6,7 @@ import technobot.commands.Category; import technobot.commands.Command; import technobot.util.embeds.EmbedUtils; +import technobot.util.localization.Invite; import static technobot.util.Localization.get; @@ -25,12 +26,12 @@ public InviteCommand(TechnoBot bot) { @Override public void execute(SlashCommandInteractionEvent event) { - Button botInvite = Button.link("https://discord.com/oauth2/authorize?client_id=979590525428580363&permissions=2088234238&scope=applications.commands%20bot", "Invite TechnoBot"); - Button supportServerInvite = Button.link("https://discord.gg/2TKJqfUQas", "Support Server"); - Button dashboardLink = Button.link("https://technobot.app", "Dashboard"); - event.replyEmbeds(EmbedUtils.createDefault( - get(s -> s.utility.invite) - )) - .addActionRow(botInvite, supportServerInvite, dashboardLink).queue(); + Invite inviteText = get(s -> s.utility.invite); + Button botInvite = Button.link("https://discord.com/oauth2/authorize?client_id=979590525428580363&permissions=2088234238&scope=applications.commands%20bot", inviteText.inviteButton); + Button supportServerInvite = Button.link("https://discord.gg/2TKJqfUQas", inviteText.serverButton); + Button dashboardLink = Button.link("https://technobot.app", inviteText.dashboardButton); + event.replyEmbeds(EmbedUtils.createDefault(inviteText.message)) + .addActionRow(botInvite, supportServerInvite, dashboardLink) + .queue(); } } diff --git a/src/main/java/technobot/commands/utility/PollCommand.java b/src/main/java/technobot/commands/utility/PollCommand.java index 970b5b3..8a51d07 100644 --- a/src/main/java/technobot/commands/utility/PollCommand.java +++ b/src/main/java/technobot/commands/utility/PollCommand.java @@ -1,6 +1,5 @@ package technobot.commands.utility; -import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.exceptions.InsufficientPermissionException; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -10,10 +9,12 @@ import technobot.commands.Category; import technobot.commands.Command; import technobot.util.embeds.EmbedUtils; +import technobot.util.localization.Poll; import java.util.Arrays; import java.util.List; +import static technobot.util.Localization.format; import static technobot.util.Localization.get; /** @@ -40,7 +41,9 @@ public void execute(SlashCommandInteractionEvent event) { // Get user event.deferReply().queue(); String question = event.getOption("question").getAsString(); - StringBuilder poll = new StringBuilder("**" + event.getUser().getName() + " asks:** " + question); + + Poll pollText = get(s -> s.utility.poll); + StringBuilder poll = new StringBuilder(format(pollText.message, event.getUser().getName())); OptionMapping choicesOption = event.getOption("choices"); if (choicesOption != null) { @@ -48,7 +51,7 @@ public void execute(SlashCommandInteractionEvent event) { String[] choices = choicesOption.getAsString().strip().split("\\s+"); if (choices.length > 10) { event.getHook().sendMessageEmbeds(EmbedUtils.createError( - get(s -> s.utility.poll.tooManyChoices) + pollText.tooManyChoices )).queue(); return; } diff --git a/src/main/java/technobot/commands/utility/SupportCommand.java b/src/main/java/technobot/commands/utility/SupportCommand.java index b569875..569eb1f 100644 --- a/src/main/java/technobot/commands/utility/SupportCommand.java +++ b/src/main/java/technobot/commands/utility/SupportCommand.java @@ -1,20 +1,15 @@ package technobot.commands.utility; import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import technobot.TechnoBot; import technobot.commands.Category; import technobot.commands.Command; import technobot.util.embeds.EmbedColor; -import technobot.util.embeds.EmbedUtils; +import technobot.util.localization.Support; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.net.URLConnection; +import static technobot.util.Localization.format; +import static technobot.util.Localization.get; /** * Command that generates a link to the support server. @@ -32,11 +27,20 @@ public SupportCommand(TechnoBot bot) { @Override public void execute(SlashCommandInteractionEvent event) { + Support supportText = get(s -> s.utility.support); event.replyEmbeds(new EmbedBuilder() - .setTitle("TechnoBot Support") - .setDescription("Hey "+event.getUser().getName()+", how can I help you?") - .addField("Server", "[Ask a question.](https://discord.com/invite/2TKJqfUQas)", true) - .addField("Bug Report", "[Report an issue.](https://github.com/TechnoVisionDev/TechnoBot/issues)", true) + .setTitle(supportText.title) + .setDescription(format(supportText.description, event.getUser().getName())) + .addField( + supportText.serverTitle, + format(supportText.askAQuestion, "https://discord.com/invite/2TKJqfUQas"), + true + ) + .addField( + supportText.bugReportTitle, + format(supportText.askAQuestion, "https://github.com/TechnoVisionDev/TechnoBot/issues"), + true + ) .setThumbnail(event.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(EmbedColor.DEFAULT.color) .build() diff --git a/src/main/java/technobot/commands/utility/TwitterCommand.java b/src/main/java/technobot/commands/utility/TwitterCommand.java index 1a108b0..6fbfa89 100644 --- a/src/main/java/technobot/commands/utility/TwitterCommand.java +++ b/src/main/java/technobot/commands/utility/TwitterCommand.java @@ -19,6 +19,8 @@ import java.io.IOException; import java.text.DecimalFormat; +import static technobot.util.Localization.get; + /** * Command that retrieves information about a Twitter account. * Uses the Twitter API v2 with bearer token. @@ -43,10 +45,10 @@ public TwitterCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { event.deferReply().queue(); String username = event.getOption("user").getAsString(); - String url = "https://api.twitter.com/2/users/by/username/"+username+"?user.fields=profile_image_url%2Cpublic_metrics%2Clocation%2Cdescription%2Curl"; + String url = "https://api.twitter.com/2/users/by/username/" + username + "?user.fields=profile_image_url%2Cpublic_metrics%2Clocation%2Cdescription%2Curl"; // Asynchronous API call - Request request = new Request.Builder().url(url).addHeader("Authorization", "Bearer "+TWITTER_TOKEN).build(); + Request request = new Request.Builder().url(url).addHeader("Authorization", "Bearer " + TWITTER_TOKEN).build(); bot.httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { @@ -78,12 +80,14 @@ public void onResponse(Call call, final Response response) throws IOException { EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setAuthor(name + "(@" + username + ")", "https://twitter.com/"+username, avatar) + .setAuthor(name + "(@" + username + ")", "https://twitter.com/" + username, avatar) .setThumbnail(avatar) - .setFooter("Following: " + following + " | Followers: " + followers); - if (!location.isEmpty()) embed.appendDescription("\n:pushpin: "+location); - if (!url.isEmpty()) embed.appendDescription("\n:link: "+url); - if (!bio.isEmpty()) embed.appendDescription("\n:information_source: "+bio); + .setFooter( + get(s -> s.utility.twitter.footer, following, followers) + ); + if (!location.isEmpty()) embed.appendDescription("\n:pushpin: " + location); + if (!url.isEmpty()) embed.appendDescription("\n:link: " + url); + if (!bio.isEmpty()) embed.appendDescription("\n:information_source: " + bio); event.getHook().sendMessageEmbeds(embed.build()).queue(); } @@ -91,7 +95,7 @@ public void onResponse(Call call, final Response response) throws IOException { } private void sendErrorMessage(InteractionHook hook) { - String text = "I was unable to find that user!"; + String text = get(s -> s.utility.twitter.failure); hook.sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } } diff --git a/src/main/java/technobot/commands/utility/UserCommand.java b/src/main/java/technobot/commands/utility/UserCommand.java index 5a86df3..69fbc54 100644 --- a/src/main/java/technobot/commands/utility/UserCommand.java +++ b/src/main/java/technobot/commands/utility/UserCommand.java @@ -46,6 +46,6 @@ public void execute(SlashCommandInteractionEvent event) { .setThumbnail(user.getEffectiveAvatarUrl()) .setFooter(user.getAsTag(), user.getEffectiveAvatarUrl()); event.replyEmbeds(embed.build()).queue(); - }) + }); } } diff --git a/src/main/java/technobot/commands/utility/VoteCommand.java b/src/main/java/technobot/commands/utility/VoteCommand.java index 478dd3b..c9f52bd 100644 --- a/src/main/java/technobot/commands/utility/VoteCommand.java +++ b/src/main/java/technobot/commands/utility/VoteCommand.java @@ -14,9 +14,13 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import technobot.util.localization.Vote; import java.io.IOException; +import static technobot.util.Localization.format; +import static technobot.util.Localization.get; + /** * Command that retrieves information about a Twitter account. * Uses the Twitter API v2 with bearer token. @@ -62,14 +66,16 @@ public void onResponse(Call call, final Response response) throws IOException { EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) .setThumbnail(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + + Vote voteText = get(s -> s.utility.vote); if (voted == 1) { - embed.setTitle(":stopwatch: Your daily vote is on cooldown!"); - embed.appendDescription("Thanks so much for voting for me today! :heart_eyes:"); - embed.appendDescription("\nDon't forget to vote every 12 hours [here]("+VOTE_LINK+")."); + embed.setTitle(voteText.cooldown); + embed.appendDescription(voteText.thanks); + embed.appendDescription("\n" + format(voteText.dontForget, VOTE_LINK)); } else { - embed.setTitle(EmbedUtils.BLUE_TICK + " Your daily vote is available!"); - embed.appendDescription("Click [here]("+VOTE_LINK+") to vote for me!"); - embed.appendDescription("\nYou can vote every 12 hours."); + embed.setTitle(voteText.voteAvailable); + embed.appendDescription(format(voteText.clickHere, VOTE_LINK)); + embed.appendDescription("\n" + voteText.voteEvery12h); } event.getHook().sendMessageEmbeds(embed.build()).addActionRow(Button.link(VOTE_LINK, "Vote Here")).queue(); } @@ -77,7 +83,7 @@ public void onResponse(Call call, final Response response) throws IOException { } private void sendErrorMessage(InteractionHook hook) { - String text = "I was unable to find the vote link!"; + String text = get(s -> s.utility.vote.noLink); hook.sendMessageEmbeds(EmbedUtils.createError(text)).queue(); } } diff --git a/src/main/java/technobot/commands/utility/YouTubeCommand.java b/src/main/java/technobot/commands/utility/YouTubeCommand.java index 7396d2e..52e4453 100644 --- a/src/main/java/technobot/commands/utility/YouTubeCommand.java +++ b/src/main/java/technobot/commands/utility/YouTubeCommand.java @@ -16,10 +16,14 @@ import technobot.commands.Command; import technobot.util.embeds.EmbedColor; import technobot.util.embeds.EmbedUtils; +import technobot.util.localization.Youtube; import java.io.IOException; import java.text.DecimalFormat; +import static technobot.util.Localization.format; +import static technobot.util.Localization.get; + /** * Command that retrieves information about a YouTube channel. * Uses the YouTube API v3 with token. @@ -44,7 +48,7 @@ public YouTubeCommand(TechnoBot bot) { public void execute(SlashCommandInteractionEvent event) { event.deferReply().queue(); String channel = event.getOption("channel").getAsString().replace(" ", "+"); - String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=channel&maxResults=1&q="+channel+"&key="+YOUTUBE_TOKEN; + String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=channel&maxResults=1&q=" + channel + "&key=" + YOUTUBE_TOKEN; // Asynchronous API call Request request = new Request.Builder().url(url).build(); @@ -74,7 +78,7 @@ public void onResponse(Call call, final Response response) throws IOException { String avatar = channelSnippet.getAsJsonObject("thumbnails").getAsJsonObject("default").get("url").getAsString(); // Second Asynchronous API call - String statsURL = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id="+channelID+"&key="+YOUTUBE_TOKEN; + String statsURL = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=" + channelID + "&key=" + YOUTUBE_TOKEN; Request request2 = new Request.Builder().url(statsURL).build(); bot.httpClient.newCall(request2).enqueue(new Callback() { @Override @@ -94,15 +98,20 @@ public void onResponse(Call call, final Response response2) throws IOException { String views = FORMATTER.format(stats.get("viewCount").getAsLong()); String subs = FORMATTER.format(stats.get("subscriberCount").getAsLong()); String videos = FORMATTER.format(stats.get("videoCount").getAsLong()); - String link = "https://www.youtube.com/channel/"+channelID; + String link = "https://www.youtube.com/channel/" + channelID; + Youtube youtubeText = get(s -> s.utility.youtube); // Build nice embed displaying all info EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setAuthor(title + " | YouTube Channel", link, avatar) + .setAuthor(format(youtubeText.channel, title), link, avatar) .setThumbnail(avatar) .setDescription(desc) - .addField("Statistics", "**Subscribers:** "+subs+"\n**Views:** "+views+"\n**Videos:** "+videos, false); + .addField( + youtubeText.statsTitle, + format(youtubeText.stats, subs, views, videos), + false + ); event.getHook().sendMessageEmbeds(embed.build()).queue(); } }); diff --git a/src/main/java/technobot/handlers/MusicHandler.java b/src/main/java/technobot/handlers/MusicHandler.java index eb6802b..a1a4e4a 100644 --- a/src/main/java/technobot/handlers/MusicHandler.java +++ b/src/main/java/technobot/handlers/MusicHandler.java @@ -22,6 +22,8 @@ import java.nio.ByteBuffer; import java.util.LinkedList; +import static technobot.util.Localization.get; + /** * Handles music for each guild with a unique queue and audio player for each. * @@ -29,20 +31,30 @@ */ public class MusicHandler implements AudioSendHandler { - /** LavaPlayer essentials. */ + /** + * LavaPlayer essentials. + */ public final @NotNull AudioPlayer audioPlayer; private AudioFrame lastFrame; - /** Queue of music tacks in FIFO order. */ + /** + * Queue of music tacks in FIFO order. + */ private final @NotNull LinkedList queue; - /** The text channel in which the bot is logging music actions. */ + /** + * The text channel in which the bot is logging music actions. + */ private TextChannel logChannel; - /** The voice channel in which the bot is playing music. */ + /** + * The voice channel in which the bot is playing music. + */ private @Nullable AudioChannel playChannel; - /** Whether the music player is on loop. */ + /** + * Whether the music player is on loop. + */ private boolean isLoop; private boolean isSkip; @@ -213,6 +225,46 @@ public ByteBuffer provide20MsAudio() { return ByteBuffer.wrap(lastFrame.getData()); } + /** + * Creates a thumbnail URL with the track image. + * + * @param track the AudioTrack object from the music player. + * @return a URL to the song video thumbnail. + */ + private static String getThumbnail(AudioTrack track) { + String domain = SecurityUtils.getDomain(track.getInfo().uri); + if (domain.equalsIgnoreCase("spotify") || domain.equalsIgnoreCase("apple")) { + return ((ISRCAudioTrack) track).getArtworkURL(); + } + return String.format("https://img.youtube.com/vi/%s/0.jpg", track.getIdentifier()); + } + + /** + * Creates an embed displaying details about a track. + * + * @param track the track to display details about. + * @param handler the music handler instance. + * @return a MessageEmbed displaying track details. + */ + public static MessageEmbed displayTrack(AudioTrack track, MusicHandler handler) { + var nowPlaying = get(s -> s.music.nowPlaying); + String duration = MusicListener.formatTrackLength(track.getInfo().length); + String repeat = (handler.isLoop()) ? nowPlaying.enabled : nowPlaying.disabled; + String userMention = "<@!" + track.getUserData(String.class) + ">"; + return new EmbedBuilder() + .setTitle(nowPlaying.title) + .setDescription("[" + track.getInfo().title + "](" + track.getInfo().uri + ")") + .addField(nowPlaying.durationTitle, "`" + duration + "`", true) + .addField(nowPlaying.queueTitle, "`" + (handler.queue.size() - 1) + "`", true) + .addField(nowPlaying.volumeTitle, "`" + handler.audioPlayer.getVolume() + "%`", true) + .addField(nowPlaying.requesterTitle, userMention, true) + .addField(nowPlaying.linkTitle, get(s -> nowPlaying.link, track.getInfo().uri), true) + .addField(nowPlaying.repeatTitle, "`" + repeat + "`", true) + .setColor(EmbedColor.DEFAULT.color) + .setThumbnail(getThumbnail(track)) + .build(); + } + /** * Manages audio events and schedules tracks. */ @@ -253,57 +305,18 @@ public void onTrackEnd(@NotNull AudioPlayer player, @NotNull AudioTrack track, @ @Override public void onTrackException(AudioPlayer player, AudioTrack track, @NotNull FriendlyException exception) { - String msg = "An error occurred! " + exception.getMessage(); + String msg = get(s -> s.error, exception.getMessage()); handler.logChannel.sendMessageEmbeds(EmbedUtils.createError(msg)).queue(); exception.printStackTrace(); } @Override public void onTrackStuck(@NotNull AudioPlayer player, AudioTrack track, long thresholdMs) { - String msg = "Track got stuck, attempting to fix..."; + String msg = get(s -> s.music.listener.trackStuck); handler.logChannel.sendMessageEmbeds(EmbedUtils.createError(msg)).queue(); handler.queue.remove(track); player.stopTrack(); player.playTrack(handler.queue.getFirst()); } } - - /** - * Creates a thumbnail URL with the track image. - * @param track the AudioTrack object from the music player. - * - * @return a URL to the song video thumbnail. - */ - private static String getThumbnail(AudioTrack track) { - String domain = SecurityUtils.getDomain(track.getInfo().uri); - if (domain.equalsIgnoreCase("spotify") || domain.equalsIgnoreCase("apple")) { - return ((ISRCAudioTrack) track).getArtworkURL(); - } - return String.format("https://img.youtube.com/vi/%s/0.jpg", track.getIdentifier()); - } - - /** - * Creates an embed displaying details about a track. - * - * @param track the track to display details about. - * @param handler the music handler instance. - * @return a MessageEmbed displaying track details. - */ - public static MessageEmbed displayTrack(AudioTrack track, MusicHandler handler) { - String duration = MusicListener.formatTrackLength(track.getInfo().length); - String repeat = (handler.isLoop()) ? "Enabled" : "Disabled"; - String userMention = "<@!"+track.getUserData(String.class)+">"; - return new EmbedBuilder() - .setTitle("Now Playing") - .setDescription("[" + track.getInfo().title + "](" + track.getInfo().uri + ")") - .addField("Duration", "`"+duration+"`", true) - .addField("Queue", "`"+(handler.queue.size()-1)+"`", true) - .addField("Volume", "`"+handler.audioPlayer.getVolume()+"%`", true) - .addField("Requester", userMention, true) - .addField("Link", "[`Click Here`]("+track.getInfo().uri+")", true) - .addField("Repeat", "`"+repeat+"`", true) - .setColor(EmbedColor.DEFAULT.color) - .setThumbnail(getThumbnail(track)) - .build(); - } } diff --git a/src/main/java/technobot/handlers/economy/EconomyHandler.java b/src/main/java/technobot/handlers/economy/EconomyHandler.java index 73c1814..8adf032 100644 --- a/src/main/java/technobot/handlers/economy/EconomyHandler.java +++ b/src/main/java/technobot/handlers/economy/EconomyHandler.java @@ -7,14 +7,15 @@ import net.dv8tion.jda.api.utils.TimeFormat; import org.bson.conversions.Bson; import technobot.TechnoBot; -import technobot.data.GuildData; import technobot.data.cache.Economy; import technobot.data.cache.Item; import technobot.handlers.ConfigHandler; -import technobot.util.embeds.EmbedUtils; import java.text.DecimalFormat; -import java.util.*; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import static technobot.util.Localization.get; @@ -26,7 +27,7 @@ */ public class EconomyHandler { - public static final String DEFAULT_CURRENCY = "\uD83E\uDE99"; + public static final String DEFAULT_CURRENCY = "🪙"; public static final long WORK_TIMEOUT = 14400000; public static final long ROB_TIMEOUT = 86400000; public static final DecimalFormat FORMATTER = new DecimalFormat("#,###"); @@ -80,7 +81,7 @@ public EconomyReply crime(long userID) { // Crime successful amount = ThreadLocalRandom.current().nextInt(450) + 250; addMoney(userID, amount); - reply = responses.getCrimeSuccessResponse(amount, getCurrency()); + reply = responses.getCrimeSuccessResponse(amount); } else { // Crime failed amount = calculateFine(userID); diff --git a/src/main/java/technobot/listeners/AfkListener.java b/src/main/java/technobot/listeners/AfkListener.java index 865a56d..b015f76 100644 --- a/src/main/java/technobot/listeners/AfkListener.java +++ b/src/main/java/technobot/listeners/AfkListener.java @@ -10,6 +10,8 @@ import java.time.Instant; import java.util.HashMap; +import static technobot.util.Localization.get; + /** * Listens for message mentions and handles afk message responses. * @@ -18,12 +20,15 @@ public class AfkListener extends ListenerAdapter { - /** Map of User objects to a pair containing the AFK message to be sent and the time created */ + /** + * Map of User objects to a pair containing the AFK message to be sent and the time created + */ public static HashMap AFK_MESSAGES = new HashMap<>(); /** * Sends AFK messages if necessary. * Also removes users from AFK list if they sent a message. + * * @param event executes whenever a message in sent in chat. */ @Override @@ -31,7 +36,7 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { // Check if AFK user has returned if (AFK_MESSAGES.containsKey(event.getMember())) { AFK_MESSAGES.remove(event.getMember()); - event.getMessage().addReaction("\uD83D\uDC4B").queue(); + event.getMessage().addReaction("👋").queue(); return; } @@ -42,7 +47,11 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { // Mentioned user was AFK -- send message response EmbedBuilder embed = new EmbedBuilder() .setColor(EmbedColor.DEFAULT.color) - .setAuthor(member.getEffectiveName()+" is currently AFK", null, member.getEffectiveAvatarUrl()) + .setAuthor( + get(s -> s.general.afk, member.getEffectiveName()), + null, + member.getEffectiveAvatarUrl() + ) .setDescription(status.message()) .setTimestamp(status.timestamp()); event.getChannel().sendMessageEmbeds(embed.build()).queue(); @@ -54,8 +63,9 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { /** * represents an AFK status message and timestamp. * - * @param message the afk message to be sent. + * @param message the afk message to be sent. * @param timestamp the time the user when afk. */ - public record AfkStatus(String message, Instant timestamp) {} + public record AfkStatus(String message, Instant timestamp) { + } } diff --git a/src/main/java/technobot/listeners/ButtonListener.java b/src/main/java/technobot/listeners/ButtonListener.java index 9e15c89..41a912a 100644 --- a/src/main/java/technobot/listeners/ButtonListener.java +++ b/src/main/java/technobot/listeners/ButtonListener.java @@ -21,6 +21,8 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import static technobot.util.Localization.get; + /** * Listens for button input and handles all button backend. * @@ -87,9 +89,15 @@ public static void sendResetMenu(String userID, String systemName, WebhookMessag */ private static List