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/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..24e147f
--- /dev/null
+++ b/dependency-reduced-pom.xml
@@ -0,0 +1,69 @@
+
+
+ 4.0.0
+ technobot
+ TechnoBot
+ 1.0
+
+
+
+ maven-shade-plugin
+ 3.3.0
+
+
+ package
+
+ shade
+
+
+
+
+ ${mainClass}
+
+
+
+
+
+
+
+ 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
+
+
+
+
+
+
+ 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 f709cb9..add387a 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
@@ -67,7 +67,7 @@
com.squareup.okhttp3
okhttp
- 4.9.3
+ 4.10.0
@@ -98,7 +98,8 @@
-
+
${mainClass}
@@ -106,6 +107,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/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/automation/AutoRoleCommand.java b/src/main/java/technobot/commands/automation/AutoRoleCommand.java
index 93d6bb8..38122b3 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.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.failure, 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.success, 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..efac8ca 100644
--- a/src/main/java/technobot/commands/economy/BalanceCommand.java
+++ b/src/main/java/technobot/commands/economy/BalanceCommand.java
@@ -14,6 +14,8 @@
import technobot.handlers.economy.EconomyHandler;
import technobot.util.embeds.EmbedColor;
+import static technobot.util.Localization.get;
+
/**
* Command that shows your current cash and bank balance on the server.
*
@@ -31,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;
@@ -54,12 +55,12 @@ public void execute(SlashCommandInteractionEvent event) {
// Send embed message
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)
- .setColor(EmbedColor.DEFAULT.color);
+ .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/BuyCommand.java b/src/main/java/technobot/commands/economy/BuyCommand.java
index 9a3a353..4fe2b83 100644
--- a/src/main/java/technobot/commands/economy/BuyCommand.java
+++ b/src/main/java/technobot/commands/economy/BuyCommand.java
@@ -16,6 +16,8 @@
import technobot.util.placeholders.Placeholder;
import technobot.util.placeholders.PlaceholderFactory;
+import static technobot.util.Localization.get;
+
/**
* Command that buys an item from the server shop.
*
@@ -40,7 +42,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;
}
@@ -59,8 +63,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())
@@ -81,8 +84,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/CrimeCommand.java b/src/main/java/technobot/commands/economy/CrimeCommand.java
index 7eb97ec..d0c6db0 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.get;
+
/**
* Command that risks losing money for a greater potential reward.
*
@@ -34,16 +36,16 @@ 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 {
// 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("Reply #" + 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/DepositCommand.java b/src/main/java/technobot/commands/economy/DepositCommand.java
index 41a5f70..0efc0ca 100644
--- a/src/main/java/technobot/commands/economy/DepositCommand.java
+++ b/src/main/java/technobot/commands/economy/DepositCommand.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.get;
/**
* Command that deposits cash into user's bank.
@@ -38,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(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 +51,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 +65,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/EconomyCommand.java b/src/main/java/technobot/commands/economy/EconomyCommand.java
index 88eabc0..43e93db 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 314360f..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 is not currently in the store!")).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 ad123c4..6cb3ad5 100644
--- a/src/main/java/technobot/commands/economy/InventoryCommand.java
+++ b/src/main/java/technobot/commands/economy/InventoryCommand.java
@@ -18,6 +18,8 @@
import java.util.*;
+import static technobot.util.Localization.get;
+
/**
* Command that shows a user's inventory.
*
@@ -38,20 +40,17 @@ public InventoryCommand(TechnoBot bot) {
@Override
public void execute(SlashCommandInteractionEvent event) {
GuildData guildData = GuildData.get(event.getGuild());
- OptionMapping userOption = event.getOption("user");
- User user = (userOption != null) ? userOption.getAsUser() : event.getUser();
+ User user = event.getOption("user", event.getUser(), OptionMapping::getAsUser);
- // Build embed template
- String info = "Use an item with the `/use
- ` command.";
EmbedBuilder embed = new EmbedBuilder()
.setColor(EmbedColor.DEFAULT.color)
- .setAuthor(user.getAsTag()+"'s Inventory", null, user.getEffectiveAvatarUrl())
- .setDescription(info);
+ .setAuthor(get(s -> s.economy.inventory.user, user.getAsTag()), null, user.getEffectiveAvatarUrl())
+ .setDescription(get(s -> s.economy.inventory.description));
// Get inventory data for user
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;
}
@@ -71,7 +70,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.inventory.description));
}
}
}
diff --git a/src/main/java/technobot/commands/economy/ItemCommand.java b/src/main/java/technobot/commands/economy/ItemCommand.java
index 1c0f524..fe8ba3f 100644
--- a/src/main/java/technobot/commands/economy/ItemCommand.java
+++ b/src/main/java/technobot/commands/economy/ItemCommand.java
@@ -17,6 +17,8 @@
import technobot.util.embeds.EmbedColor;
import technobot.util.embeds.EmbedUtils;
+import static technobot.util.Localization.get;
+
/**
* Command that performs CRUD operations for economy shop items.
*
@@ -72,16 +74,17 @@ public void execute(SlashCommandInteractionEvent event) {
String currency = guildData.economyHandler.getCurrency();
String text = "";
- switch(event.getSubcommandName()) {
+ String name = event.getOption("name").getAsString();
+ switch (event.getSubcommandName()) {
case "create" -> {
String name = event.getOption("name").getAsString();
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;
}
@@ -91,13 +94,13 @@ public void execute(SlashCommandInteractionEvent event) {
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" -> {
@@ -112,11 +115,11 @@ public void execute(SlashCommandInteractionEvent event) {
// 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();
}
}
@@ -138,7 +141,7 @@ public void execute(SlashCommandInteractionEvent event) {
text = EmbedUtils.BLUE_X + " Item has been erased and can never be purchased or used.";
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();
}
}
@@ -146,7 +149,9 @@ public void execute(SlashCommandInteractionEvent event) {
String name = event.getOption("name").getAsString();
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();
@@ -189,14 +194,21 @@ 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 (durationOption.getAsLong() == 0) {
item.setExpireTimestamp(null);
} else {
@@ -205,10 +217,16 @@ private ItemResult updateItem(Item item, SlashCommandInteractionEvent event) {
}
} if (stockOption != null) {
isUpdated = true;
+ item.setStock(stockOption.getAsLong());
+ }
+ if (reqRoleOption != null) {
Long stock = stockOption.getAsLong() == -1 ? null : stockOption.getAsLong();
item.setStock(stock);
} if (reqRoleOption != null) {
isUpdated = true;
+ item.setRequiredRole(reqRoleOption.getAsRole().getIdLong());
+ }
+ if (roleGivenOption != null) {
Long roleID = reqRoleOption.getAsRole().getIdLong();
if (item.getRequiredRole() != null && item.getRequiredRole().equals(roleID)) {
roleID = null;
@@ -222,6 +240,9 @@ private ItemResult updateItem(Item item, SlashCommandInteractionEvent event) {
}
item.setGivenRole(roleID);
} if (roleRemovedOption != null) {
+ item.setGivenRole(roleGivenOption.getAsRole().getIdLong());
+ }
+ if (roleRemovedOption != null) {
isUpdated = true;
Long roleID = roleRemovedOption.getAsRole().getIdLong();
if (item.getRemovedRole() != null && item.getRemovedRole().equals(roleID)) {
@@ -229,10 +250,16 @@ private ItemResult updateItem(Item item, SlashCommandInteractionEvent event) {
}
item.setRemovedRole(roleID);
} if (reqBalOption != null) {
+ item.setRemovedRole(roleRemovedOption.getAsRole().getIdLong());
+ }
+ if (reqBalOption != null) {
isUpdated = true;
Long reqBal = reqBalOption.getAsLong() == 0 ? null : reqBalOption.getAsLong();
item.setRequiredBalance(reqBal);
} if (replyOption != null) {
+ item.setRequiredBalance(reqBalOption.getAsLong());
+ }
+ if (replyOption != null) {
isUpdated = true;
String reply = replyOption.getAsString().isBlank() ? null : replyOption.getAsString();
item.setReplyMessage(reply);
@@ -240,5 +267,6 @@ private ItemResult updateItem(Item item, SlashCommandInteractionEvent event) {
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/PayCommand.java b/src/main/java/technobot/commands/economy/PayCommand.java
index 3283ea1..a59daa7 100644
--- a/src/main/java/technobot/commands/economy/PayCommand.java
+++ b/src/main/java/technobot/commands/economy/PayCommand.java
@@ -11,7 +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.get;
/**
* Command that transfer cash from one user to another.
@@ -36,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 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 +52,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 +67,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..5216f36 100644
--- a/src/main/java/technobot/commands/economy/RobCommand.java
+++ b/src/main/java/technobot/commands/economy/RobCommand.java
@@ -12,7 +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.get;
/**
* Command that steals money from another user.
@@ -35,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(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,14 +55,14 @@ 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 {
// 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/ShopCommand.java b/src/main/java/technobot/commands/economy/ShopCommand.java
index 5765099..888fb38 100644
--- a/src/main/java/technobot/commands/economy/ShopCommand.java
+++ b/src/main/java/technobot/commands/economy/ShopCommand.java
@@ -15,6 +15,8 @@
import java.util.*;
+import static technobot.util.Localization.get;
+
/**
* Command that displays the server shop and available items.
*
@@ -35,17 +37,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<>();
@@ -61,7 +62,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/economy/WithdrawCommand.java b/src/main/java/technobot/commands/economy/WithdrawCommand.java
index d4d082b..ad6d545 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.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..37b4d0e 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.get;
+
/**
* Command that adds money to your balance.
*
@@ -34,15 +36,15 @@ 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 {
// Work
EconomyReply reply = economyHandler.work(user);
- embed.setDescription(reply.getResponse());
+ embed.setDescription(reply.response());
embed.setColor(EmbedColor.SUCCESS.color);
- embed.setFooter("Reply #"+reply.getId());
+ embed.setFooter(get(s -> s.economy.replyId, reply.id()));
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 93fe3cd..8856c39 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.get;
+
/**
* Command that generates an image to match an emotion with another user
*
@@ -59,28 +61,28 @@ 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);
+ default -> "";
+ };
// Asynchronous API call
Request request = new Request.Builder().url(url).build();
@@ -88,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 = "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 36538bb..1821d0e 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.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);
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..9a70883 100644
--- a/src/main/java/technobot/commands/fun/EightBallCommand.java
+++ b/src/main/java/technobot/commands/fun/EightBallCommand.java
@@ -10,10 +10,10 @@
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.get;
+
/**
* Command that generates a cute picture from reddit.
*
@@ -21,22 +21,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,10 +33,14 @@ 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;
}
+ var responses = get(s -> s.fun.eightBall.responses);
+
int index = ThreadLocalRandom.current().nextInt(responses.size());
EmbedBuilder embed = new EmbedBuilder()
.setColor(EmbedColor.DEFAULT.color)
diff --git a/src/main/java/technobot/commands/fun/EmoteCommand.java b/src/main/java/technobot/commands/fun/EmoteCommand.java
index 770ce6c..4e4e0fd 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.get;
+
/**
* Command that generates an image to match an emotion.
*
@@ -56,27 +58,27 @@ 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);
+ default -> "";
+ };
// 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..86c84af 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.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)
+ )).queue();
return;
}
String query = URLEncoder.encode(question, StandardCharsets.UTF_8);
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/JokeCommand.java b/src/main/java/technobot/commands/fun/JokeCommand.java
index 0189f0e..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,6 +12,8 @@
import java.io.IOException;
+import static technobot.util.Localization.get;
+
/**
* Command that generates a joke from a joke API.
*
@@ -35,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 = "I was unable to fetch any jokes!";
+ String text = get(s -> s.fun.joke);
event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue();
}
@@ -43,7 +48,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 +57,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 496f735..0d7c6e7 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,6 +19,8 @@
import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;
+import static technobot.util.Localization.get;
+
/**
* Command that generates a meme from the r/dankmemes subreddit.
*
@@ -55,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 memes!";
+ 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 62ef24b..0c09b80 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.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);
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 a741f3a..6b4c60f 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.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);
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..5c55d74 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.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);
event.getHook().sendMessageEmbeds(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/greetings/FarewellCommand.java b/src/main/java/technobot/commands/greetings/FarewellCommand.java
index d21382f..585eea6 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.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.reset);
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..c1d3bf7 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.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.reset);
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.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 1252dbf..7110e46 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.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..23948c8 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.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.reset);
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/commands/levels/LevelingCommand.java b/src/main/java/technobot/commands/levels/LevelingCommand.java
index 031ea30..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,6 +27,8 @@
import java.io.IOException;
import java.net.URL;
+import static technobot.util.Localization.get;
+
/**
* Command that displays and modifies leveling config.
*
@@ -66,18 +71,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.user);
}
}
case "message" -> {
@@ -86,11 +91,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 +103,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 +113,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 +130,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 +146,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 +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("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 +181,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 +204,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..84be340 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.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..1d2b28e 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.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..e1a2138 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.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..d317248 100644
--- a/src/main/java/technobot/commands/levels/TopCommand.java
+++ b/src/main/java/technobot/commands/levels/TopCommand.java
@@ -23,7 +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.get;
/**
* Command that displays various leaderboards.
@@ -36,7 +40,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 +71,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 +84,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 +93,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 +105,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 +113,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 +161,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 +172,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 +179,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 +202,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 +212,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 +223,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 +231,24 @@ 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(get(
+ s -> s.levels.top.footer,
+ page,
+ maxPages,
+ currRank
+ ));
embeds.add(embed.build());
description = new StringBuilder();
counter = 0;
@@ -238,7 +257,12 @@ private List buildLevelingLeaderboard(LevelingHandler levelingHand
}
if (counter != 0) {
embed.setDescription(description);
- embed.setFooter("Page "+page+"/"+maxPages + " ā¢ Your rank: " + rank);
+ embed.setFooter(get(
+ s -> s.levels.top.footer,
+ page,
+ maxPages,
+ currRank
+ ));
embeds.add(embed.build());
}
return embeds;
@@ -248,32 +272,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/music/NowPlayingCommand.java b/src/main/java/technobot/commands/music/NowPlayingCommand.java
index c1017ef..b1d11eb 100644
--- a/src/main/java/technobot/commands/music/NowPlayingCommand.java
+++ b/src/main/java/technobot/commands/music/NowPlayingCommand.java
@@ -9,6 +9,8 @@
import technobot.handlers.MusicHandler;
import technobot.util.embeds.EmbedUtils;
+import static technobot.util.Localization.get;
+
/**
* Command that displays the currently playing song.
*
@@ -28,7 +30,7 @@ public void execute(SlashCommandInteractionEvent event) {
// Verify the Music Manager isn't null.
MusicHandler music = GuildData.get(event.getGuild()).musicHandler;
if (music == null) {
- String text = ":sound: Not currently playing any music!";
+ String text = get(s -> s.music.nowPlaying.notPlaying);
event.replyEmbeds(EmbedUtils.createDefault(text)).setEphemeral(true).queue();
return;
}
@@ -36,7 +38,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;
}
diff --git a/src/main/java/technobot/commands/music/PauseCommand.java b/src/main/java/technobot/commands/music/PauseCommand.java
index aaa9bb4..f17af9f 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.
*
@@ -27,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 0cda635..592fdf9 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.
*
@@ -36,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;
}
@@ -56,13 +58,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, userID);
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];
@@ -71,7 +73,7 @@ public void execute(SlashCommandInteractionEvent event) {
music.setLogChannel(event.getTextChannel());
bot.musicListener.addTrack(event, url, userID);
} catch (IndexOutOfBoundsException e) {
- String text = "Please specify a song a to play.";
+ String text = get(s -> s.music.play.specifySong);
event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).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 ae79566..2d7ce2e 100644
--- a/src/main/java/technobot/commands/music/RepeatCommand.java
+++ b/src/main/java/technobot/commands/music/RepeatCommand.java
@@ -6,6 +6,9 @@
import technobot.commands.Command;
import technobot.handlers.MusicHandler;
import technobot.util.embeds.EmbedUtils;
+import technobot.util.localization.Repeat;
+
+import static technobot.util.Localization.get;
/**
* Command that toggles repeat mode for music queue.
@@ -23,16 +26,15 @@ public RepeatCommand(TechnoBot bot) {
@Override
public void execute(SlashCommandInteractionEvent event) {
+ event.deferReply().queue();
MusicHandler music = bot.musicListener.getMusic(event, false);
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/ResumeCommand.java b/src/main/java/technobot/commands/music/ResumeCommand.java
index 2ba10e5..2ad40c9 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.
*
@@ -28,11 +30,11 @@ 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.replyEmbeds(EmbedUtils.createDefault(text)).queue();
} else {
- String text = "The player is not paused!";
- event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue();
+ String text = get(s -> s.music.resume.failure);
+ event.replyEmbeds(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 648aa54..aea345f 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.
*
@@ -50,20 +52,23 @@ 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;
}
// 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.replyEmbeds(EmbedUtils.createDefault(text)).queue();
} catch ( NumberFormatException | ArrayIndexOutOfBoundsException e) {
// Invalid timestamps
- String text = "That is not a valid timestamp!";
- event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue();
+ String text = get(s -> s.music.seek.invalidTimestamp);
+ event.replyEmbeds(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 1d580f5..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.
*
@@ -23,13 +25,18 @@ public SkipCommand(TechnoBot bot) {
}
public void execute(SlashCommandInteractionEvent event) {
+ event.deferReply().queue();
MusicHandler music = bot.musicListener.getMusic(event, false);
if (music == null) return;
music.skipTrack();
- ReplyCallbackAction action = event.reply(":fast_forward: Skipping...");
+ ReplyCallbackAction action = event.reply(
+ 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 81cb731..ee8492d 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,12 +28,13 @@ public StopCommand(TechnoBot bot) {
public void execute(SlashCommandInteractionEvent event) {
MusicHandler musicHandler = GuildData.get(event.getGuild()).musicHandler;
if (musicHandler == null) {
- String text = "The music player is already stopped!";
- event.replyEmbeds(EmbedUtils.createError(text)).setEphemeral(true).queue();
+ String text = get(s -> s.music.stop.failure);
+ event.replyEmbeds(EmbedUtils.createError(text)).queue();
} else {
musicHandler.disconnect();
event.getGuild().getAudioManager().closeAudioConnection();
- String text = ":stop_button: 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 241fea3..6caba00 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.
*
@@ -37,12 +39,12 @@ public void execute(SlashCommandInteractionEvent event) {
throw new NumberFormatException();
}
music.setVolume(volume);
- String text = String.format(":loud_sound: Set the volume to `%s%%`", volume);
+ String text = get(s -> s.music.volume.success, volume);
event.replyEmbeds(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.replyEmbeds(EmbedUtils.createError(text)).queue();
}
}
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 731cf82..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 removed.");
+ 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 removed for <@!"+target.getId()+">.");
- } else if (count == 1) {
- embed = EmbedUtils.createDefault(GREEN_TICK+" 1 warning has been removed 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/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/java/technobot/commands/suggestions/RespondCommand.java b/src/main/java/technobot/commands/suggestions/RespondCommand.java
index 3112a21..ca39718 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/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/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..92ee41d 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,9 +53,11 @@ public void execute(SlashCommandInteractionEvent event) {
}
OptionMapping option = event.getOption("category");
- OptionMapping option2 = event.getOption("command");
- if (option != null && option2 != null) {
- event.replyEmbeds(EmbedUtils.createError("Please only give one optional argument and try again.")).queue();
+ OptionMapping commandOption = event.getOption("command");
+ if (option != null && commandOption != null) {
+ 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());
@@ -58,8 +65,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 +81,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 +95,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 +124,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 +168,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 +186,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 +201,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..6d38eaf 100644
--- a/src/main/java/technobot/commands/utility/InviteCommand.java
+++ b/src/main/java/technobot/commands/utility/InviteCommand.java
@@ -6,6 +6,9 @@
import technobot.commands.Category;
import technobot.commands.Command;
import technobot.util.embeds.EmbedUtils;
+import technobot.util.localization.Invite;
+
+import static technobot.util.Localization.get;
/**
* Creates button links to invite bot and join the support server.
@@ -23,10 +26,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();
+ 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/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 8c8a0d4..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,14 @@
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;
+
/**
* Command that creates a quick poll with options and reactions.
*
@@ -22,16 +25,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);
@@ -46,14 +41,18 @@ 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) {
// 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(
+ pollText.tooManyChoices
+ )).queue();
return;
}
poll.append("\n");
@@ -69,9 +68,10 @@ 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();
- } catch (InsufficientPermissionException ignored) { }
+ msg.addReaction("š").queue();
+ msg.addReaction("š").queue();
+ } catch (InsufficientPermissionException ignored) {
+ }
});
}
}
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/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 813edd6..69fbc54 100644
--- a/src/main/java/technobot/commands/utility/UserCommand.java
+++ b/src/main/java/technobot/commands/utility/UserCommand.java
@@ -12,6 +12,8 @@
import technobot.commands.Command;
import technobot.util.embeds.EmbedColor;
+import static technobot.util.Localization.get;
+
/**
* Command that displays information about a user.
*
@@ -30,17 +32,17 @@ 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);
+
event.getGuild().retrieveMember(user).queue(member -> {
// Create and send embed
String joinedDiscord = TimeFormat.RELATIVE.format(member.getTimeCreated().toInstant().toEpochMilli());
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/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/data/cache/Config.java b/src/main/java/technobot/data/cache/Config.java
index 1c18c29..df28d6e 100644
--- a/src/main/java/technobot/data/cache/Config.java
+++ b/src/main/java/technobot/data/cache/Config.java
@@ -44,6 +44,9 @@ public class Config {
private LinkedHashMap shop; //Maps item names to ids
+ @BsonProperty("locale")
+ private String locale;
+
public Config() {
this.autoRoles = new HashSet<>();
this.items = new LinkedHashMap<>();
@@ -63,6 +66,7 @@ public Config(long guild) {
this.autoRoles = new HashSet<>();
this.items = new LinkedHashMap<>();
this.shop = new LinkedHashMap<>();
+ this.locale = "en_US";
}
public long getGuild() {
@@ -195,4 +199,12 @@ public Item eraseItem(String name) {
String uuid = this.shop.remove(name.toLowerCase());
return this.items.remove(uuid);
}
+
+ 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/ConfigHandler.java b/src/main/java/technobot/handlers/ConfigHandler.java
index 8396904..20d9abd 100644
--- a/src/main/java/technobot/handlers/ConfigHandler.java
+++ b/src/main/java/technobot/handlers/ConfigHandler.java
@@ -84,7 +84,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/handlers/ModerationHandler.java b/src/main/java/technobot/handlers/ModerationHandler.java
index 7a9f71d..4261c00 100644
--- a/src/main/java/technobot/handlers/ModerationHandler.java
+++ b/src/main/java/technobot/handlers/ModerationHandler.java
@@ -19,6 +19,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.
*
@@ -107,11 +109,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/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/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/handlers/economy/EconomyHandler.java b/src/main/java/technobot/handlers/economy/EconomyHandler.java
index e64b22b..cb1ff89 100644
--- a/src/main/java/technobot/handlers/economy/EconomyHandler.java
+++ b/src/main/java/technobot/handlers/economy/EconomyHandler.java
@@ -9,16 +9,19 @@
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;
+
/**
* Handles the server economy backend.
*
@@ -26,7 +29,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("#,###");
@@ -63,7 +66,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);
}
/**
@@ -80,12 +83,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, amount);
- reply = responses.getCrimeFailResponse(amount, getCurrency());
+ reply = responses.getCrimeFailResponse(amount);
}
setTimeout(userID, TIMEOUT_TYPE.CRIME);
return reply;
@@ -94,7 +97,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.
*/
@@ -118,15 +121,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);
}
@@ -176,9 +185,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);
@@ -252,7 +261,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"))
)
);
@@ -293,7 +302,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;
@@ -301,7 +310,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);
@@ -313,7 +322,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) {
@@ -322,7 +331,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 7bb6fe1..be6545e 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;
-import java.io.BufferedReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
+import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
+import static technobot.util.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 List work;
+ private final List crimeSuccess;
+ private final List 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();
+ var responses = Localization.get(s -> s.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) {
- 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);
+ public EconomyReply getWorkResponse(long amount) {
+ int index = ThreadLocalRandom.current().nextInt(work.size());
+
+ return new EconomyReply(format(work.get(index), amount), index + 1);
}
/**
@@ -53,11 +46,13 @@ 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) {
- int index = ThreadLocalRandom.current().nextInt(crimeSuccess.length);
- String value = currency+" "+EconomyHandler.FORMATTER.format(amount);
- String reply = crimeSuccess[index].replaceAll("\\{amount}", value);
- return new EconomyReply(reply, index+1, true);
+ public EconomyReply getCrimeSuccessResponse(long amount) {
+ int index = ThreadLocalRandom.current().nextInt(crimeSuccess.size());
+
+ return new EconomyReply(
+ format(crimeSuccess.get(index), amount),
+ index + 1
+ );
}
/**
@@ -66,10 +61,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].replaceAll("\\{amount}", value);
- return new EconomyReply(reply, index+1, false);
+ public EconomyReply getCrimeFailResponse(long amount) {
+ int index = ThreadLocalRandom.current().nextInt(crimeFailure.size());
+
+ return new EconomyReply(
+ format(crimeFailure.get(index), amount),
+ index + 1,
+ false
+ );
}
}
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);
}
}
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