Improve various small code quality issues
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Bea 2023-01-16 03:53:51 +01:00
parent d315b3f38a
commit 546637c188
11 changed files with 46 additions and 44 deletions

View File

@ -263,10 +263,10 @@ public class UrbanDictionary
htmlContributor.indexOf("</a>") + 4); htmlContributor.indexOf("</a>") + 4);
contributorsNames.add(htmlContributorName contributorsNames.add(htmlContributorName
.replaceAll("<.*?>", "")); // remove all html tags; .replaceAll("<.*?>", "")); // remove all html tags
submissionDates.add(htmlSubmitDate submissionDates.add(htmlSubmitDate
.replaceAll("<.*?>", "")); // remove all html tags; .replaceAll("<.*?>", "")); // remove all html tags
} }
} }

View File

@ -70,6 +70,7 @@ public class AvatarCommand implements MessageCommand
resFound = true; resFound = true;
break; break;
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {
// ignored because we're running a check after this block
} }
} }

View File

@ -70,6 +70,7 @@ public class BannerCommand implements MessageCommand
resFound = true; resFound = true;
break; break;
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {
// ignored because we're running a check after this block
} }
} }

View File

@ -52,8 +52,6 @@ public class ClearCommand implements MessageCommand
@Override @Override
public void runCommand(MessageReceivedEvent event, String label, String[] args) public void runCommand(MessageReceivedEvent event, String label, String[] args)
{ {
String senderId = event.getMessage().getAuthor().getId();
// check if user is trying to run command in dms. // check if user is trying to run command in dms.
String error = ClearChat.checkDMs(event.getChannel()); String error = ClearChat.checkDMs(event.getChannel());
if (error != null) { if (error != null) {

View File

@ -33,13 +33,16 @@ public class DiceRollCommand implements MessageCommand
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
return "Roll dice. You can roll multiple dice at the same time." + {
"\nExamples:" + return """
"\n - `d8 10` to roll an 8-sided die 10 times." + Roll dice. You can roll multiple dice at the same time.
"\n - `d12 3 d5 10` to roll a 12-sided die 3 times, and then a 5-sided die 10 times." + Examples:
"\n - `30` to roll a standard 6-sided die 30 times." + - `d8 10` to roll an 8-sided die 10 times.
"\n - `d10` to roll a 10-sided die once."; - `d12 3 d5 10` to roll a 12-sided die 3 times, and then a 5-sided die 10 times.
- `30` to roll a standard 6-sided die 30 times.
- `d10` to roll a 10-sided die once.
""";
} }
@Nullable @Nullable

View File

@ -11,10 +11,7 @@ import wtf.beatrice.hidekobot.commands.base.Alias;
import wtf.beatrice.hidekobot.objects.commands.CommandCategory; import wtf.beatrice.hidekobot.objects.commands.CommandCategory;
import wtf.beatrice.hidekobot.objects.commands.MessageCommand; import wtf.beatrice.hidekobot.objects.commands.MessageCommand;
import java.util.Collections; import java.util.*;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
public class HelpCommand implements MessageCommand public class HelpCommand implements MessageCommand
{ {
@ -82,10 +79,11 @@ public class HelpCommand implements MessageCommand
"\nYou will find a list of commands organized in categories below.", "\nYou will find a list of commands organized in categories below.",
false); false);
for(CommandCategory category : commandCategories.keySet()) for(Map.Entry<CommandCategory, LinkedList<MessageCommand>> entry : commandCategories.entrySet())
{ {
StringBuilder commandsList = new StringBuilder(); StringBuilder commandsList = new StringBuilder();
LinkedList<MessageCommand> commandsOfThisCategory = commandCategories.get(category); CommandCategory category = entry.getKey();
LinkedList<MessageCommand> commandsOfThisCategory = entry.getValue();
for(int pos = 0; pos < commandsOfThisCategory.size(); pos++) for(int pos = 0; pos < commandsOfThisCategory.size(); pos++)
{ {

View File

@ -9,6 +9,7 @@ import wtf.beatrice.hidekobot.HidekoBot;
import java.io.*; import java.io.*;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map;
public class ConfigurationSource public class ConfigurationSource
{ {
@ -94,15 +95,18 @@ public class ConfigurationSource
// create a new mixed map that will take existing values from the non-missing keys // create a new mixed map that will take existing values from the non-missing keys
// and fill everything else with the default values // and fill everything else with the default values
LinkedHashMap<String, Object> filledEntries = new LinkedHashMap<>(); LinkedHashMap<String, Object> filledEntries = new LinkedHashMap<>();
for(String key : internalConfigContents.keySet())
for(Map.Entry<String, Object> entry : internalConfigContents.entrySet())
{ {
String key = entry.getKey();
if(fsConfigContents.containsKey(key)) if(fsConfigContents.containsKey(key))
{ {
// if the key already exists, copy the original value // if the key already exists, copy the original value
filledEntries.put(key, fsConfigContents.get(key)); filledEntries.put(key, fsConfigContents.get(key));
} else { } else {
// else, copy the value from the example config file // else, copy the value from the example config file
filledEntries.put(key, internalConfigContents.get(key)); filledEntries.put(key, entry.getValue());
} }
} }

View File

@ -11,7 +11,6 @@ import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.objects.commands.CommandCategory; import wtf.beatrice.hidekobot.objects.commands.CommandCategory;
import wtf.beatrice.hidekobot.objects.commands.MessageCommand; import wtf.beatrice.hidekobot.objects.commands.MessageCommand;
import wtf.beatrice.hidekobot.objects.comparators.MessageCommandAliasesComparator; import wtf.beatrice.hidekobot.objects.comparators.MessageCommandAliasesComparator;
import wtf.beatrice.hidekobot.util.Logger;
import java.util.*; import java.util.*;
@ -20,13 +19,13 @@ public class MessageCommandListener extends ListenerAdapter
// map storing command labels and command object alphabetically. // map storing command labels and command object alphabetically.
private final TreeMap<LinkedList<String>, MessageCommand> registeredCommands = private final TreeMap<LinkedList<String>, MessageCommand> registeredCommands =
new TreeMap<LinkedList<String>, MessageCommand>(new MessageCommandAliasesComparator()); new TreeMap<>(new MessageCommandAliasesComparator());
// map commands and their categories. // map commands and their categories.
// this is not strictly needed but it's better to have it so we avoid looping every time we need to check the cat. // this is not strictly needed but it's better to have it so we avoid looping every time we need to check the cat.
LinkedHashMap<CommandCategory, LinkedList<MessageCommand>> commandCategories = new LinkedHashMap<>(); LinkedHashMap<CommandCategory, LinkedList<MessageCommand>> commandCategories = new LinkedHashMap<>();
private final String commandRegex = "(?i)^(hideko|hde)\\b"; private static final String COMMAND_REGEX = "(?i)^(hideko|hde)\\b";
// (?i) -> case insensitive flag // (?i) -> case insensitive flag
// ^ -> start of string (not in middle of a sentence) // ^ -> start of string (not in middle of a sentence)
// \b -> the word has to end here // \b -> the word has to end here
@ -39,12 +38,14 @@ public class MessageCommandListener extends ListenerAdapter
public MessageCommand getRegisteredCommand(String label) public MessageCommand getRegisteredCommand(String label)
{ {
for(LinkedList<String> aliases : registeredCommands.keySet()) for(Map.Entry<LinkedList<String>, MessageCommand> entry : registeredCommands.entrySet())
{ {
LinkedList<String> aliases = entry.getKey();
for(String currentAlias : aliases) for(String currentAlias : aliases)
{ {
if(label.equals(currentAlias)) if(label.equals(currentAlias))
{ return registeredCommands.get(aliases); } { return entry.getValue(); }
} }
} }
@ -54,9 +55,6 @@ public class MessageCommandListener extends ListenerAdapter
public LinkedList<MessageCommand> getRegisteredCommands() public LinkedList<MessageCommand> getRegisteredCommands()
{ return new LinkedList<>(registeredCommands.values()); } { return new LinkedList<>(registeredCommands.values()); }
private final Logger logger = new Logger(MessageCommandListener.class);
@Override @Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) public void onMessageReceived(@NotNull MessageReceivedEvent event)
{ {
@ -67,11 +65,11 @@ public class MessageCommandListener extends ListenerAdapter
String eventMessage = event.getMessage().getContentRaw(); String eventMessage = event.getMessage().getContentRaw();
// check if the sent message matches the bot activation regex (prefix, name, ...) // check if the sent message matches the bot activation regex (prefix, name, ...)
if(!eventMessage.toLowerCase().matches("(?s)" + commandRegex + ".*")) if(!eventMessage.toLowerCase().matches("(?s)" + COMMAND_REGEX + ".*"))
return; return;
// generate args from the string // generate args from the string
String argsString = eventMessage.replaceAll(commandRegex + "\\s*", ""); String argsString = eventMessage.replaceAll(COMMAND_REGEX + "\\s*", "");
// if no args were specified apart from the bot prefix // if no args were specified apart from the bot prefix
@ -115,16 +113,13 @@ public class MessageCommandListener extends ListenerAdapter
{ {
Member member = event.getMember(); Member member = event.getMember();
GuildChannel channel = event.getGuildChannel(); //todo: what about forum post GuildChannel channel = event.getGuildChannel(); //todo: what about forum post
if(member != null) if(member != null && !member.hasPermission(channel, requiredPermissions))
{ {
if(!member.hasPermission(channel, requiredPermissions)) event.getMessage()
{ .reply("You do not have permissions to run this command!")
event.getMessage() .queue(); // todo prettier
.reply("You do not have permissions to run this command!") // todo: queue message deletion in 15 seconds or so
.queue(); // todo prettier return;
// todo: queue message deletion in 15 seconds or so
return;
}
} }
} }

View File

@ -70,7 +70,9 @@ public class FormatUtil
if(hours == 0) if(hours == 0)
{ {
if(minutes == 0) if(minutes == 0)
{} else { // i know this if has an empty body but i feel like this reads better {
// empty code block because it makes the code easier to read
} else {
uptimeStringBuilder.append(minutes).append("m "); uptimeStringBuilder.append(minutes).append("m ");
} }
} else { } else {

View File

@ -5,8 +5,8 @@ import java.time.format.DateTimeFormatter;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@Deprecated @Deprecated(since = "0.5.16", forRemoval = true)
public class Logger public class Logger<T>
{ {
// objects that we need to have for a properly formatted message // objects that we need to have for a properly formatted message
@ -17,7 +17,7 @@ public class Logger
// when initializing a new logger, save variables in that instance // when initializing a new logger, save variables in that instance
public Logger(Class logClass) public Logger(Class<T> logClass)
{ {
className = logClass.getSimpleName(); className = logClass.getSimpleName();
} }

View File

@ -10,7 +10,7 @@ import java.util.List;
public class SerializationUtil public class SerializationUtil
{ {
public static String serializeBase64(List dataList) { public static <T> String serializeBase64(List<T> dataList) {
try (ByteArrayOutputStream bo = new ByteArrayOutputStream(); try (ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo)) { ObjectOutputStream so = new ObjectOutputStream(bo)) {
@ -23,7 +23,7 @@ public class SerializationUtil
} }
} }
public static LinkedList deserializeBase64(String dataStr) { public static <T> LinkedList<T> deserializeBase64(String dataStr) {
byte[] b = Base64.getDecoder().decode(dataStr); byte[] b = Base64.getDecoder().decode(dataStr);
ByteArrayInputStream bi = new ByteArrayInputStream(b); ByteArrayInputStream bi = new ByteArrayInputStream(b);