4 Commits

Author SHA1 Message Date
fd2970fa59 cleanup and reformat
All checks were successful
continuous-integration/drone/push Build is passing
2025-09-05 00:06:35 +02:00
14b54501fd update drone
All checks were successful
continuous-integration/drone/push Build is passing
2025-09-04 23:42:30 +02:00
1928cfe858 update readme
All checks were successful
continuous-integration/drone/push Build is passing
2025-09-04 23:41:54 +02:00
0b7880af88 fix drone
All checks were successful
continuous-integration/drone/push Build is passing
2025-09-04 23:36:49 +02:00
85 changed files with 1337 additions and 769 deletions

View File

@@ -5,6 +5,7 @@ data:
os: linux os: linux
build_branches: build_branches:
- main - main
- develop
build_events: build_events:
- push - push
- pull_request - pull_request

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
target/ target/
.idea/ .idea/
scripts/
*.sqlite *.sqlite

View File

@@ -0,0 +1,88 @@
---
kind: pipeline
type: docker
name: build
platform:
os: {{ .input.os }}
arch: {{ .input.arch }}
trigger:
branch:
{{- range .input.build_branches }}
- {{ . }}
{{- end }}
event:
{{- range .input.build_events }}
- {{ . }}
{{- end }}
# Global project-specific environment variables
environment:
{{- range .input.envs }}
{{ .name }}: {{ .value }}
{{- end }}
steps:
# Test if it compiles correctly
- name: build
image: maven:3-eclipse-temurin-21
commands:
- mvn verify --no-transfer-progress -DskipTests=true -Dmaven.javadoc.skip=true -B -V
# Run unit tests
- name: test
image: maven:3-eclipse-temurin-21
commands:
- mvn test --no-transfer-progress -B -V
# Check maven dependencies
- name: dependency-check
image: owasp/dependency-check:latest
commands:
- dependency-check --scan /src --format ALL --out /src/target --nvdApiKey $NVD_API_KEY
environment:
NVD_API_KEY:
from_secret: nvd_api_key
# Run code analysis
- name: code-analysis
when:
event:
- push
image: maven:3-eclipse-temurin-21
commands:
- mvn sonar:sonar --no-transfer-progress -Dsonar.projectKey={{ .input.sonar_project_key }} -Dsonar.host.url=$SONAR_INSTANCE_URL -Dsonar.token=$SONAR_LOGIN_KEY -B -V
environment:
SONAR_INSTANCE_URL:
from_secret: sonar_instance_url
SONAR_LOGIN_KEY:
from_secret: sonar_login_key
---
kind: pipeline
type: kubernetes
name: deploy
trigger:
event:
- promote
target:
{{- range .input.deploy_targets }}
- {{ . }}
{{- end }}
# Global project-specific environment variables
environment:
{{- range .input.envs }}
{{ .name }}: {{ .value }}
{{- end }}
steps:
# Upload to Maven repository
- name: maven-deploy
image: maven:3-eclipse-temurin-21
commands:
- mvn deploy --no-transfer-progress -DskipTests=true -Dmaven.javadoc.skip=true -B -V -gs settings.xml -Dmaven.repo.username=$MAVEN_REPO_USERNAME -Dmaven.repo.password=$MAVEN_REPO_PASSWORD
environment:
MAVEN_REPO_USERNAME:
from_secret: maven_repo_username
MAVEN_REPO_PASSWORD:
from_secret: maven_repo_password

View File

@@ -2,7 +2,7 @@
[![Reliability Rating](https://sonar.beatrice.wtf/api/project_badges/measure?project=HidekoBot&metric=reliability_rating&token=0a63c149148555d6d2ee40665af1afae8f67cc3f)](https://sonar.beatrice.wtf/dashboard?id=HidekoBot) [![Reliability Rating](https://sonar.beatrice.wtf/api/project_badges/measure?project=HidekoBot&metric=reliability_rating&token=0a63c149148555d6d2ee40665af1afae8f67cc3f)](https://sonar.beatrice.wtf/dashboard?id=HidekoBot)
[![Maintainability Rating](https://sonar.beatrice.wtf/api/project_badges/measure?project=HidekoBot&metric=sqale_rating&token=0a63c149148555d6d2ee40665af1afae8f67cc3f)](https://sonar.beatrice.wtf/dashboard?id=HidekoBot) [![Maintainability Rating](https://sonar.beatrice.wtf/api/project_badges/measure?project=HidekoBot&metric=sqale_rating&token=0a63c149148555d6d2ee40665af1afae8f67cc3f)](https://sonar.beatrice.wtf/dashboard?id=HidekoBot)
[![Security Rating](https://sonar.beatrice.wtf/api/project_badges/measure?project=HidekoBot&metric=security_rating&token=0a63c149148555d6d2ee40665af1afae8f67cc3f)](https://sonar.beatrice.wtf/dashboard?id=HidekoBot) [![Security Rating](https://sonar.beatrice.wtf/api/project_badges/measure?project=HidekoBot&metric=security_rating&token=0a63c149148555d6d2ee40665af1afae8f67cc3f)](https://sonar.beatrice.wtf/dashboard?id=HidekoBot)
[![Build Status](https://drone.prod.panic.haus/api/badges/bea/HidekoBot/status.svg)](https://drone.prod.panic.haus/bea/HidekoBot) [![Build Status](https://drone.beatrice.wtf/api/badges/bea/HidekoBot/status.svg)](https://drone.beatrice.wtf/bea/HidekoBot)
[![Lines of Code](https://sonar.beatrice.wtf/api/project_badges/measure?project=HidekoBot&metric=ncloc&token=0a63c149148555d6d2ee40665af1afae8f67cc3f)](https://sonar.beatrice.wtf/dashboard?id=HidekoBot) [![Lines of Code](https://sonar.beatrice.wtf/api/project_badges/measure?project=HidekoBot&metric=ncloc&token=0a63c149148555d6d2ee40665af1afae8f67cc3f)](https://sonar.beatrice.wtf/dashboard?id=HidekoBot)
Hideko is a general-purpose Discord bot. Hideko is a general-purpose Discord bot.

View File

@@ -22,7 +22,7 @@
<dependency> <dependency>
<groupId>net.dv8tion</groupId> <groupId>net.dv8tion</groupId>
<artifactId>JDA</artifactId> <artifactId>JDA</artifactId>
<version>5.6.0</version> <version>5.5.1</version>
</dependency> </dependency>
<!-- JDA depends on SLF4J for logging --> <!-- JDA depends on SLF4J for logging -->
<dependency> <dependency>

View File

@@ -22,7 +22,8 @@ import java.util.concurrent.ScheduledExecutorService;
public class Cache public class Cache
{ {
private Cache() { private Cache()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -70,7 +71,7 @@ public class Cache
private static String botApplicationId = ""; private static String botApplicationId = "";
// discord api returns a broken image if you don't use specific sizes (powers of 2), so we limit it to these // discord api returns a broken image if you don't use specific sizes (powers of 2), so we limit it to these
private static final int[] supportedAvatarResolutions = { 16, 32, 64, 128, 256, 512, 1024 }; private static final int[] supportedAvatarResolutions = {16, 32, 64, 128, 256, 512, 1024};
/** /**
* Get an array of all the Discord-supported avatar resolutions. * Get an array of all the Discord-supported avatar resolutions.
@@ -78,7 +79,10 @@ public class Cache
* *
* @return array of supported resolutions. * @return array of supported resolutions.
*/ */
public static int[] getSupportedAvatarResolutions() { return supportedAvatarResolutions; } public static int[] getSupportedAvatarResolutions()
{
return supportedAvatarResolutions;
}
/** /**
@@ -86,7 +90,10 @@ public class Cache
* *
* @return a boolean which is true if the bot is in verbose-mode * @return a boolean which is true if the bot is in verbose-mode
*/ */
public static synchronized boolean isVerbose() { return verbose; } public static synchronized boolean isVerbose()
{
return verbose;
}
/** /**
* Set the bot's verbosity status at runtime. * Set the bot's verbosity status at runtime.
@@ -98,13 +105,13 @@ public class Cache
{ {
verbose = v; verbose = v;
if(verbosityLogger != null) if (verbosityLogger != null)
{ {
HidekoBot.getAPI().removeEventListener(verbosityLogger); HidekoBot.getAPI().removeEventListener(verbosityLogger);
verbosityLogger = null; verbosityLogger = null;
} }
if(v) if (v)
{ {
verbosityLogger = new MessageLogger(); verbosityLogger = new MessageLogger();
HidekoBot.getAPI().addEventListener(verbosityLogger); HidekoBot.getAPI().addEventListener(verbosityLogger);
@@ -116,7 +123,8 @@ public class Cache
* *
* @return a long of the account's id * @return a long of the account's id
*/ */
public static long getBotOwnerId() { public static long getBotOwnerId()
{
return configurationSource == null ? 0L : (Long) configurationSource.getConfigValue(ConfigurationEntry.BOT_OWNER_ID); return configurationSource == null ? 0L : (Long) configurationSource.getConfigValue(ConfigurationEntry.BOT_OWNER_ID);
} }
@@ -126,7 +134,8 @@ public class Cache
* *
* @return a String of the bot's token. * @return a String of the bot's token.
*/ */
public static String getBotToken() { public static String getBotToken()
{
return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.BOT_TOKEN); return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.BOT_TOKEN);
} }
@@ -137,7 +146,10 @@ public class Cache
* @return a long of the account's id * @return a long of the account's id
*/ */
public static long getBotMaintainerId() { return BOT_MAINTAINER_ID; } public static long getBotMaintainerId()
{
return BOT_MAINTAINER_ID;
}
/** /**
* Set the bot's application id. * Set the bot's application id.
@@ -154,14 +166,18 @@ public class Cache
* *
* @return a string of the bot's application id * @return a string of the bot's application id
*/ */
public static String getBotApplicationId() { return botApplicationId; } public static String getBotApplicationId()
{
return botApplicationId;
}
/** /**
* Function to generate an invite link for the bot * Function to generate an invite link for the bot
* *
* @return a string containing the invite link * @return a string containing the invite link
*/ */
public static String getInviteUrl() { public static String getInviteUrl()
{
return DEFAULT_INVITE_LINK.replace("%userid%", botApplicationId); return DEFAULT_INVITE_LINK.replace("%userid%", botApplicationId);
} }
@@ -180,7 +196,10 @@ public class Cache
* *
* @return the DatabaseSource instance. * @return the DatabaseSource instance.
*/ */
public static @Nullable DatabaseSource getDatabaseSource() { return databaseSource; } public static @Nullable DatabaseSource getDatabaseSource()
{
return databaseSource;
}
/** /**
* Set the properties source instance loaded from the JAR archive. * Set the properties source instance loaded from the JAR archive.
@@ -197,24 +216,34 @@ public class Cache
* *
* @return the String of the DateTimeFormatter format. * @return the String of the DateTimeFormatter format.
*/ */
public static String getExpiryTimestampFormat(){ return EXPIRY_TIMESTAMP_FORMAT; } public static String getExpiryTimestampFormat()
{
return EXPIRY_TIMESTAMP_FORMAT;
}
/** /**
* Get the amount of seconds after which a message expires. * Get the amount of seconds after which a message expires.
* *
* @return long value of the expiry seconds. * @return long value of the expiry seconds.
*/ */
public static long getExpiryTimeSeconds() { return EXPIRY_TIME_SECONDS; } public static long getExpiryTimeSeconds()
{
return EXPIRY_TIME_SECONDS;
}
public static String getBotName() { return BOT_NAME; } public static String getBotName()
{
return BOT_NAME;
}
/** /**
* Get the bot's version. * Get the bot's version.
* *
* @return a String of the bot version. * @return a String of the bot version.
*/ */
public static String getBotVersion() { public static String getBotVersion()
{
return propertiesSource.getProperty("bot.version"); return propertiesSource.getProperty("bot.version");
} }
@@ -223,7 +252,8 @@ public class Cache
* *
* @return a String containing the base URL of the repository, including a <b>trailing slash</b>. * @return a String containing the base URL of the repository, including a <b>trailing slash</b>.
*/ */
public static String getRepositoryUrl() { public static String getRepositoryUrl()
{
String url = propertiesSource.getProperty("repo.base_url"); String url = propertiesSource.getProperty("repo.base_url");
return url.endsWith("/") ? url : url + "/"; return url.endsWith("/") ? url : url + "/";
} }
@@ -233,16 +263,19 @@ public class Cache
* *
* @return the Color object. * @return the Color object.
*/ */
public static Color getBotColor() { public static Color getBotColor()
{
Color defaultColor = Color.PINK; Color defaultColor = Color.PINK;
if(configurationSource == null) return defaultColor; if (configurationSource == null) return defaultColor;
String colorName = (String) configurationSource.getConfigValue(ConfigurationEntry.BOT_COLOR); String colorName = (String) configurationSource.getConfigValue(ConfigurationEntry.BOT_COLOR);
Color color = null; Color color = null;
try { try
{
Field field = Color.class.getField(colorName); Field field = Color.class.getField(colorName);
color = (Color)field.get(null); color = (Color) field.get(null);
} catch (RuntimeException | NoSuchFieldException | IllegalAccessException e) { } catch (RuntimeException | NoSuchFieldException | IllegalAccessException e)
{
LOGGER.error("Unknown color: {}", colorName); LOGGER.error("Unknown color: {}", colorName);
} }
return color == null ? defaultColor : color; return color == null ? defaultColor : color;
@@ -251,21 +284,36 @@ public class Cache
//todo javadocs //todo javadocs
public static void setSlashCommandListener(SlashCommandListener commandListener) public static void setSlashCommandListener(SlashCommandListener commandListener)
{ slashCommandListener = commandListener; } {
slashCommandListener = commandListener;
}
public static SlashCommandListener getSlashCommandListener() { return slashCommandListener; } public static SlashCommandListener getSlashCommandListener()
{
return slashCommandListener;
}
public static void setSlashCommandCompletionListener(SlashCommandCompletionListener commandCompletionListener) public static void setSlashCommandCompletionListener(SlashCommandCompletionListener commandCompletionListener)
{ slashCommandCompletionListener = commandCompletionListener; } {
slashCommandCompletionListener = commandCompletionListener;
}
public static SlashCommandCompletionListener getSlashCommandCompletionListener() { return slashCommandCompletionListener; } public static SlashCommandCompletionListener getSlashCommandCompletionListener()
{
return slashCommandCompletionListener;
}
public static void setMessageCommandListener(MessageCommandListener commandListener) public static void setMessageCommandListener(MessageCommandListener commandListener)
{ messageCommandListener = commandListener; } {
messageCommandListener = commandListener;
}
public static MessageCommandListener getMessageCommandListener() { return messageCommandListener; } public static MessageCommandListener getMessageCommandListener()
{
return messageCommandListener;
}
/** /**
* Set the bot's startup time. Generally only used at boot time. * Set the bot's startup time. Generally only used at boot time.
@@ -273,7 +321,9 @@ public class Cache
* @param time a LocalDateTime of the startup moment. * @param time a LocalDateTime of the startup moment.
*/ */
public static void setStartupTime(LocalDateTime time) public static void setStartupTime(LocalDateTime time)
{ startupTime = time; } {
startupTime = time;
}
/** /**
@@ -281,37 +331,54 @@ public class Cache
* *
* @return a LocalDateTime object of the startup instant. * @return a LocalDateTime object of the startup instant.
*/ */
public static LocalDateTime getStartupTime() { return startupTime; } public static LocalDateTime getStartupTime()
{
return startupTime;
}
/** /**
* Get the time of when the bot was created. * Get the time of when the bot was created.
* *
* @return a LocalDateTime object of the first commit's instant. * @return a LocalDateTime object of the first commit's instant.
*/ */
public static LocalDateTime getBotBirthDate() { return botBirthDate; } public static LocalDateTime getBotBirthDate()
{
return botBirthDate;
}
public static String getFullHeartBeatLink() { public static String getFullHeartBeatLink()
{
return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.HEARTBEAT_LINK); return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.HEARTBEAT_LINK);
} }
//todo javadocs //todo javadocs
public static String getExecPath() { return EXEC_PATH; } public static String getExecPath()
{
return EXEC_PATH;
}
/*private static ConfigurationSource getConfigurationSource() /*private static ConfigurationSource getConfigurationSource()
{ return configurationSource; }*/ { return configurationSource; }*/
public static String getRandomOrgApiKey() { public static String getRandomOrgApiKey()
{
return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.RANDOM_ORG_API_KEY); return configurationSource == null ? null : (String) configurationSource.getConfigValue(ConfigurationEntry.RANDOM_ORG_API_KEY);
} }
public static void setConfigurationSource(ConfigurationSource configurationSource) public static void setConfigurationSource(ConfigurationSource configurationSource)
{ Cache.configurationSource = configurationSource; } {
Cache.configurationSource = configurationSource;
}
/** /**
* Get the bot's prefix * Get the bot's prefix
* *
* @return a String of the bot's prefix. * @return a String of the bot's prefix.
*/ */
public static String getBotPrefix() { return BOT_PREFIX; } public static String getBotPrefix()
{
return BOT_PREFIX;
}
public static void cacheLoveCalculatorValue(String userId1, String userId2, int value) public static void cacheLoveCalculatorValue(String userId1, String userId2, int value)
{ {
@@ -326,7 +393,7 @@ public class Cache
String merged2 = userId2 + "|" + userId1; String merged2 = userId2 + "|" + userId1;
Integer value = null; Integer value = null;
value = loveCalculatorValues.get(merged1); value = loveCalculatorValues.get(merged1);
if(value == null) value = loveCalculatorValues.get(merged2); if (value == null) value = loveCalculatorValues.get(merged2);
return value; return value;
} }
@@ -336,7 +403,8 @@ public class Cache
loveCalculatorValues.remove(userId2 + "|" + userId1); loveCalculatorValues.remove(userId2 + "|" + userId1);
} }
public static ScheduledExecutorService getTaskScheduler() { public static ScheduledExecutorService getTaskScheduler()
{
return taskScheduler; return taskScheduler;
} }

View File

@@ -56,7 +56,7 @@ public class HidekoBot
// check loaded bot token // check loaded bot token
String botToken = Cache.getBotToken(); String botToken = Cache.getBotToken();
if(botToken == null || botToken.isEmpty()) if (botToken == null || botToken.isEmpty())
{ {
LOGGER.error("Invalid bot token!"); LOGGER.error("Invalid bot token!");
shutdown(); shutdown();
@@ -76,12 +76,12 @@ public class HidekoBot
); );
jda = jdaBuilder.build().awaitReady(); jda = jdaBuilder.build().awaitReady();
} catch (InterruptedException e) { } catch (InterruptedException e)
{
LOGGER.error(e.getMessage()); // print the error message, omit the stack trace. LOGGER.error(e.getMessage()); // print the error message, omit the stack trace.
Thread.currentThread().interrupt(); // send interrupt to the thread. Thread.currentThread().interrupt(); // send interrupt to the thread.
shutdown(); // if we failed connecting and authenticating, then quit. shutdown(); // if we failed connecting and authenticating, then quit.
} } catch (Exception e)
catch (Exception e)
{ {
LOGGER.error(e.getMessage()); // print the error message, omit the stack trace. LOGGER.error(e.getMessage()); // print the error message, omit the stack trace.
shutdown(); // if we failed connecting and authenticating, then quit. shutdown(); // if we failed connecting and authenticating, then quit.
@@ -96,19 +96,20 @@ public class HidekoBot
// if there is at least one arg, then iterate through them because we have additional things to do. // if there is at least one arg, then iterate through them because we have additional things to do.
// we are doing this at the end because we might need the API to be already initialized for some things. // we are doing this at the end because we might need the API to be already initialized for some things.
if(args.length > 0) { if (args.length > 0)
{
List<String> argsList = new ArrayList<>(Arrays.asList(args)); List<String> argsList = new ArrayList<>(Arrays.asList(args));
// NOTE: do not replace with enhanced for, since we might need // NOTE: do not replace with enhanced for, since we might need
// to know what position we're at or do further elaboration of the string. // to know what position we're at or do further elaboration of the string.
// we were using this for api key parsing in the past. // we were using this for api key parsing in the past.
for(int i = 0; i < argsList.size(); i++) for (int i = 0; i < argsList.size(); i++)
{ {
String arg = argsList.get(i); String arg = argsList.get(i);
if(arg.equals("verbose")) Cache.setVerbose(true); if (arg.equals("verbose")) Cache.setVerbose(true);
if(arg.equals("refresh")) forceUpdateCommands = true; if (arg.equals("refresh")) forceUpdateCommands = true;
} }
} }
@@ -117,7 +118,7 @@ public class HidekoBot
boolean enableRandomSeedUpdaterTask = false; boolean enableRandomSeedUpdaterTask = false;
// initialize random.org object if API key is provided // initialize random.org object if API key is provided
{ {
if(RandomUtil.isRandomOrgKeyValid()) if (RandomUtil.isRandomOrgKeyValid())
{ {
LOGGER.info("Enabling Random.org integration... This might take a while!"); LOGGER.info("Enabling Random.org integration... This might take a while!");
RandomUtil.initRandomOrg(); RandomUtil.initRandomOrg();
@@ -187,7 +188,8 @@ public class HidekoBot
// update slash commands (delayed) // update slash commands (delayed)
final boolean finalForceUpdateCommands = forceUpdateCommands; final boolean finalForceUpdateCommands = forceUpdateCommands;
try (ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor()) { try (ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor())
{
executor.schedule(() -> CommandUtil.updateSlashCommands(finalForceUpdateCommands), executor.schedule(() -> CommandUtil.updateSlashCommands(finalForceUpdateCommands),
1, TimeUnit.SECONDS); 1, TimeUnit.SECONDS);
} }
@@ -199,7 +201,7 @@ public class HidekoBot
LOGGER.info("Connecting to database..."); LOGGER.info("Connecting to database...");
String dbFilePath = Cache.getExecPath() + File.separator + "db.sqlite"; // in current directory String dbFilePath = Cache.getExecPath() + File.separator + "db.sqlite"; // in current directory
DatabaseSource databaseSource = new DatabaseSource(dbFilePath); DatabaseSource databaseSource = new DatabaseSource(dbFilePath);
if(databaseSource.connect() && databaseSource.initDb()) if (databaseSource.connect() && databaseSource.initDb())
{ {
LOGGER.info("Database connection initialized!"); LOGGER.info("Database connection initialized!");
Cache.setDatabaseSourceInstance(databaseSource); Cache.setDatabaseSourceInstance(databaseSource);
@@ -207,7 +209,8 @@ public class HidekoBot
// load data here... // load data here...
LOGGER.info("Database data loaded into memory!"); LOGGER.info("Database data loaded into memory!");
} else { } else
{
LOGGER.error("Error initializing database connection!"); LOGGER.error("Error initializing database connection!");
} }
@@ -219,7 +222,7 @@ public class HidekoBot
scheduler.scheduleAtFixedRate(heartBeatTask, 10L, 30L, TimeUnit.SECONDS); //every 30 seconds scheduler.scheduleAtFixedRate(heartBeatTask, 10L, 30L, TimeUnit.SECONDS); //every 30 seconds
StatusUpdateTask statusUpdateTask = new StatusUpdateTask(); StatusUpdateTask statusUpdateTask = new StatusUpdateTask();
scheduler.scheduleAtFixedRate(statusUpdateTask, 0L, 60L * 5L, TimeUnit.SECONDS); // every 5 minutes scheduler.scheduleAtFixedRate(statusUpdateTask, 0L, 60L * 5L, TimeUnit.SECONDS); // every 5 minutes
if(enableRandomSeedUpdaterTask) if (enableRandomSeedUpdaterTask)
{ {
RandomOrgSeedTask randomSeedTask = new RandomOrgSeedTask(); RandomOrgSeedTask randomSeedTask = new RandomOrgSeedTask();
scheduler.scheduleAtFixedRate(randomSeedTask, 15L, 15L, TimeUnit.MINUTES); // every 15 minutes scheduler.scheduleAtFixedRate(randomSeedTask, 15L, 15L, TimeUnit.MINUTES); // every 15 minutes
@@ -240,6 +243,7 @@ public class HidekoBot
LOGGER.info("Invite Link: {}", Cache.getInviteUrl()); LOGGER.info("Invite Link: {}", Cache.getInviteUrl());
} }
public static JDA getAPI() public static JDA getAPI()
{ {
return jda; return jda;
@@ -254,7 +258,7 @@ public class HidekoBot
private static void preShutdown() private static void preShutdown()
{ {
LOGGER.warn("WARNING! Shutting down!"); LOGGER.warn("WARNING! Shutting down!");
if(jda != null) jda.shutdown(); if (jda != null) jda.shutdown();
} }
} }

View File

@@ -6,7 +6,8 @@ import java.util.LinkedList;
public class Alias public class Alias
{ {
private Alias() { private Alias()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -14,11 +15,11 @@ public class Alias
{ {
LinkedList<String> aliases = command.getCommandLabels(); LinkedList<String> aliases = command.getCommandLabels();
StringBuilder aliasesStringBuilder = new StringBuilder(); StringBuilder aliasesStringBuilder = new StringBuilder();
for(int i = 0; i < aliases.size(); i++) for (int i = 0; i < aliases.size(); i++)
{ {
aliasesStringBuilder.append("`").append(aliases.get(i)).append("`"); aliasesStringBuilder.append("`").append(aliases.get(i)).append("`");
if(i + 1 != aliases.size()) if (i + 1 != aliases.size())
aliasesStringBuilder.append(", "); // separate with comma except on last iteration aliasesStringBuilder.append(", "); // separate with comma except on last iteration
} }

View File

@@ -13,7 +13,8 @@ import java.util.List;
public class BotInfo public class BotInfo
{ {
private BotInfo() { private BotInfo()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -25,7 +26,7 @@ public class BotInfo
// thumbnail // thumbnail
String botAvatarUrl = HidekoBot.getAPI().getSelfUser().getAvatarUrl(); String botAvatarUrl = HidekoBot.getAPI().getSelfUser().getAvatarUrl();
if(botAvatarUrl != null) embedBuilder.setThumbnail(botAvatarUrl); if (botAvatarUrl != null) embedBuilder.setThumbnail(botAvatarUrl);
// help field // help field
long ownerId = Cache.getBotOwnerId(); long ownerId = Cache.getBotOwnerId();
@@ -37,12 +38,12 @@ public class BotInfo
// type-specific commands list field // type-specific commands list field
StringBuilder commandsListBuilder = new StringBuilder(); StringBuilder commandsListBuilder = new StringBuilder();
commandsListBuilder.append(commandLabels.size()).append( " total - "); commandsListBuilder.append(commandLabels.size()).append(" total - ");
for(int i = 0; i < commandLabels.size(); i++) for (int i = 0; i < commandLabels.size(); i++)
{ {
commandsListBuilder.append("`").append(commandLabels.get(i)).append("`"); commandsListBuilder.append("`").append(commandLabels.get(i)).append("`");
if(i + 1 != commandLabels.size()) // don't add comma in last iteration if (i + 1 != commandLabels.size()) // don't add comma in last iteration
{ {
commandsListBuilder.append(", "); commandsListBuilder.append(", ");
} }
@@ -55,9 +56,10 @@ public class BotInfo
// message commands info field // message commands info field
String messageCommandsInfo; String messageCommandsInfo;
if(Cache.getMessageCommandListener() == null) if (Cache.getMessageCommandListener() == null)
messageCommandsInfo = "❌ disabled"; messageCommandsInfo = "❌ disabled";
else { else
{
messageCommandsInfo = "✅ available"; messageCommandsInfo = "✅ available";
commandsCount += Cache.getMessageCommandListener().getRegisteredCommands().size(); commandsCount += Cache.getMessageCommandListener().getRegisteredCommands().size();
} }
@@ -65,9 +67,10 @@ public class BotInfo
// slash commands info field // slash commands info field
String slashCommandsInfo; String slashCommandsInfo;
if(Cache.getMessageCommandListener() == null) if (Cache.getMessageCommandListener() == null)
slashCommandsInfo = "❌ disabled"; slashCommandsInfo = "❌ disabled";
else { else
{
slashCommandsInfo = "✅ available"; slashCommandsInfo = "✅ available";
commandsCount += Cache.getSlashCommandListener().getRegisteredCommands().size(); commandsCount += Cache.getSlashCommandListener().getRegisteredCommands().size();
} }
@@ -75,10 +78,11 @@ public class BotInfo
// random.org integration field // random.org integration field
String randomOrgInfo; String randomOrgInfo;
if(RandomUtil.isRandomOrgKeyValid()) if (RandomUtil.isRandomOrgKeyValid())
{ {
randomOrgInfo = "✅ connected"; randomOrgInfo = "✅ connected";
} else { } else
{
randomOrgInfo = "❌ disabled"; randomOrgInfo = "❌ disabled";
} }
embedBuilder.addField("Random.org", randomOrgInfo, true); embedBuilder.addField("Random.org", randomOrgInfo, true);

View File

@@ -14,34 +14,42 @@ import java.util.List;
public class ClearChat public class ClearChat
{ {
private ClearChat() { private ClearChat()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
public static String getLabel() { public static String getLabel()
{
return "clear"; return "clear";
} }
public static String getDescription() { public static String getDescription()
{
return "Clear the current channel's chat."; return "Clear the current channel's chat.";
} }
public static Permission getPermission() { public static Permission getPermission()
{
return Permission.MESSAGE_MANAGE; return Permission.MESSAGE_MANAGE;
} }
public static String checkDMs(Channel channel) public static String checkDMs(Channel channel)
{ {
if(!(channel instanceof TextChannel)) if (!(channel instanceof TextChannel))
{ return "\uD83D\uDE22 Sorry! I can't delete messages here."; } {
return "\uD83D\uDE22 Sorry! I can't delete messages here.";
}
return null; return null;
} }
public static String checkDeleteAmount(int toDeleteAmount) public static String checkDeleteAmount(int toDeleteAmount)
{ {
if(toDeleteAmount <= 0) if (toDeleteAmount <= 0)
{ return "\uD83D\uDE22 Sorry, I can't delete that amount of messages!"; } {
return "\uD83D\uDE22 Sorry, I can't delete that amount of messages!";
}
return null; return null;
} }
@@ -65,7 +73,7 @@ public class ClearChat
//if there are some messages left, but less than <limit>, we need one more iterations. //if there are some messages left, but less than <limit>, we need one more iterations.
int remainder = toDeleteAmount % limit; int remainder = toDeleteAmount % limit;
if(remainder != 0) iterations++; if (remainder != 0) iterations++;
// set the starting point. // set the starting point.
long messageId = startingMessageId; long messageId = startingMessageId;
@@ -74,59 +82,62 @@ public class ClearChat
boolean outOfBounds = false; boolean outOfBounds = false;
// do iterate. // do iterate.
for(int iteration = 0; iteration < iterations; iteration++) for (int iteration = 0; iteration < iterations; iteration++)
{ {
if(outOfBounds) break; if (outOfBounds) break;
// set how many messages to delete for this iteration (usually <limit> unless there's a remainder) // set how many messages to delete for this iteration (usually <limit> unless there's a remainder)
int iterationSize = limit; int iterationSize = limit;
// if we are at the last iteration... check if we have <limit> or fewer messages to delete // if we are at the last iteration... check if we have <limit> or fewer messages to delete
if(iteration+1 == iterations && remainder != 0) { if (iteration + 1 == iterations && remainder != 0)
{
iterationSize = remainder; iterationSize = remainder;
} }
if(iterationSize == 1) if (iterationSize == 1)
{ {
// grab the message // grab the message
Message toDelete = channel.retrieveMessageById(messageId).complete(); Message toDelete = channel.retrieveMessageById(messageId).complete();
//only delete one message //only delete one message
if(toDelete != null) toDelete.delete().queue(); if (toDelete != null) toDelete.delete().queue();
else outOfBounds = true; else outOfBounds = true;
// increase deleted counter by 1 // increase deleted counter by 1
deleted++; deleted++;
} else { } else
{
// get the last <iterationSize - 1> messages. // get the last <iterationSize - 1> messages.
MessageHistory.MessageRetrieveAction action = channel.getHistoryBefore(messageId, iterationSize - 1); MessageHistory.MessageRetrieveAction action = channel.getHistoryBefore(messageId, iterationSize - 1);
// note: first one is the most recent, last one is the oldest message. // note: first one is the most recent, last one is the oldest message.
List<Message> messages = new ArrayList<>(); List<Message> messages = new ArrayList<>();
// (we are skipping first iteration since it would return an error, given that the id is the slash command and not a message) // (we are skipping first iteration since it would return an error, given that the id is the slash command and not a message)
if(iteration!=0) messages.add(channel.retrieveMessageById(messageId).complete()); if (iteration != 0) messages.add(channel.retrieveMessageById(messageId).complete());
messages.addAll(action.complete().getRetrievedHistory()); messages.addAll(action.complete().getRetrievedHistory());
// check if we only have one or zero messages left (trying to delete more than possible) // check if we only have one or zero messages left (trying to delete more than possible)
if(messages.size() <= 1) if (messages.size() <= 1)
{ {
outOfBounds = true; outOfBounds = true;
} else { } else
{
// before deleting, we need to grab the <previous to the oldest> message's id for next iteration. // before deleting, we need to grab the <previous to the oldest> message's id for next iteration.
action = channel.getHistoryBefore(messages.getLast().getIdLong(), 1); action = channel.getHistoryBefore(messages.getLast().getIdLong(), 1);
List<Message> previousMessage = action.complete().getRetrievedHistory(); List<Message> previousMessage = action.complete().getRetrievedHistory();
// if that message exists (we are not out of bounds)... store it // if that message exists (we are not out of bounds)... store it
if(!previousMessage.isEmpty()) messageId = previousMessage.getFirst().getIdLong(); if (!previousMessage.isEmpty()) messageId = previousMessage.getFirst().getIdLong();
else outOfBounds = true; else outOfBounds = true;
} }
// queue messages for deletion // queue messages for deletion
if(messages.size() == 1) if (messages.size() == 1)
{ {
messages.getFirst().delete().queue(); messages.getFirst().delete().queue();
} } else if (!messages.isEmpty())
else if(!messages.isEmpty()) {
try
{ {
try {
((TextChannel) channel).deleteMessages(messages).complete(); ((TextChannel) channel).deleteMessages(messages).complete();
/* alternatively, we could use purgeMessages, which is smarter... /* alternatively, we could use purgeMessages, which is smarter...
however, it also tries to delete messages older than 2 weeks however, it also tries to delete messages older than 2 weeks
@@ -156,18 +167,22 @@ public class ClearChat
public static String parseAmount(int deleted) public static String parseAmount(int deleted)
{ {
if(deleted < 1) if (deleted < 1)
{ {
return "\uD83D\uDE22 Couldn't clear any message!"; return "\uD83D\uDE22 Couldn't clear any message!";
} else if(deleted == 1) } else if (deleted == 1)
{ {
return "✂ Cleared 1 message!"; return "✂ Cleared 1 message!";
} else { } else
{
return "✂ Cleared " + deleted + " messages!"; return "✂ Cleared " + deleted + " messages!";
} }
} }
// cap the amount to avoid abuse. // cap the amount to avoid abuse.
public static int getMaxAmount() { return 1000; } public static int getMaxAmount()
{
return 1000;
}
} }

View File

@@ -14,11 +14,13 @@ import java.util.List;
public class CoinFlip public class CoinFlip
{ {
private CoinFlip() { private CoinFlip()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
public static Button getReflipButton() { public static Button getReflipButton()
{
return Button.primary("coinflip_reflip", "Flip again") return Button.primary("coinflip_reflip", "Flip again")
.withEmoji(Emoji.fromUnicode("\uD83E\uDE99")); .withEmoji(Emoji.fromUnicode("\uD83E\uDE99"));
} }
@@ -28,10 +30,11 @@ public class CoinFlip
int rand = RandomUtil.getRandomNumber(0, 1); int rand = RandomUtil.getRandomNumber(0, 1);
String msg; String msg;
if(rand == 1) if (rand == 1)
{ {
msg = ":coin: It's **Heads**!"; msg = ":coin: It's **Heads**!";
} else { } else
{
msg = "It's **Tails**! :coin:"; msg = "It's **Tails**! :coin:";
} }
@@ -41,7 +44,7 @@ public class CoinFlip
public static void buttonReFlip(ButtonInteractionEvent event) public static void buttonReFlip(ButtonInteractionEvent event)
{ {
// check if the user interacting is the same one who ran the command // check if the user interacting is the same one who ran the command
if(!(Cache.getDatabaseSource().isUserTrackedFor(event.getUser().getId(), event.getMessageId()))) if (!(Cache.getDatabaseSource().isUserTrackedFor(event.getUser().getId(), event.getMessageId())))
{ {
event.reply("❌ You did not run this command!").setEphemeral(true).queue(); event.reply("❌ You did not run this command!").setEphemeral(true).queue();
return; return;
@@ -59,7 +62,8 @@ public class CoinFlip
{ {
// set the command as expiring and restrict it to the user who ran it // set the command as expiring and restrict it to the user who ran it
trackAndRestrict(message, event.getUser()); trackAndRestrict(message, event.getUser());
}, (error) -> {}); }, (error) -> {
});
} }
public static void trackAndRestrict(Message replyMessage, User user) public static void trackAndRestrict(Message replyMessage, User user)

View File

@@ -15,7 +15,8 @@ import java.util.UUID;
public class DiceRoll public class DiceRoll
{ {
private DiceRoll() { private DiceRoll()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -30,25 +31,26 @@ public class DiceRoll
UUID lastPushedDice = null; UUID lastPushedDice = null;
int totalRolls = 0; int totalRolls = 0;
for(String arg : args) for (String arg : args)
{ {
if(totalRolls > 200) if (totalRolls > 200)
{ {
return new MessageResponse("Too many total rolls!", null); return new MessageResponse("Too many total rolls!", null);
} }
if(arg.matches(amountRegex)) if (arg.matches(amountRegex))
{ {
currentAmount = Integer.parseInt(arg); currentAmount = Integer.parseInt(arg);
if(currentDice == null) if (currentDice == null)
{ {
currentDice = new Dice(6); currentDice = new Dice(6);
} else { } else
{
currentDice = new Dice(currentDice); currentDice = new Dice(currentDice);
} }
if(currentAmount > 100) if (currentAmount > 100)
{ {
return new MessageResponse("Too many rolls (`" + currentAmount + "`)!", null); return new MessageResponse("Too many rolls (`" + currentAmount + "`)!", null);
} }
@@ -56,25 +58,24 @@ public class DiceRoll
lastPushedDice = currentDice.getUUID(); lastPushedDice = currentDice.getUUID();
dicesToRoll.put(currentDice, currentAmount); dicesToRoll.put(currentDice, currentAmount);
totalRolls += currentAmount; totalRolls += currentAmount;
} } else if (arg.matches(diceRegex))
else if(arg.matches(diceRegex))
{ {
int sides = Integer.parseInt(arg.substring(1)); int sides = Integer.parseInt(arg.substring(1));
if(sides > 10000) if (sides > 10000)
{ {
return new MessageResponse("Too many sides (`" + sides + "`)!", null); return new MessageResponse("Too many sides (`" + sides + "`)!", null);
} }
if(args.length == 1) if (args.length == 1)
{ {
dicesToRoll.put(new Dice(sides), 1); dicesToRoll.put(new Dice(sides), 1);
totalRolls++; totalRolls++;
} else } else
{ {
if(currentDice != null) if (currentDice != null)
{ {
if(lastPushedDice == null || !lastPushedDice.equals(currentDice.getUUID())) if (lastPushedDice == null || !lastPushedDice.equals(currentDice.getUUID()))
{ {
dicesToRoll.put(currentDice, 1); dicesToRoll.put(currentDice, 1);
lastPushedDice = currentDice.getUUID(); lastPushedDice = currentDice.getUUID();
@@ -87,16 +88,16 @@ public class DiceRoll
} }
} }
if(lastPushedDice == null) if (lastPushedDice == null)
{ {
if(currentDice != null) if (currentDice != null)
{ {
dicesToRoll.put(currentDice, 1); dicesToRoll.put(currentDice, 1);
totalRolls++; totalRolls++;
} }
} else } else
{ {
if(!lastPushedDice.equals(currentDice.getUUID())) if (!lastPushedDice.equals(currentDice.getUUID()))
{ {
dicesToRoll.put(new Dice(currentDice), 1); dicesToRoll.put(new Dice(currentDice), 1);
totalRolls++; totalRolls++;
@@ -106,19 +107,19 @@ public class DiceRoll
LinkedList<Dice> rolledDices = new LinkedList<>(); LinkedList<Dice> rolledDices = new LinkedList<>();
// in case no dice was specified (or invalid), roll a standard 6-sided dice. // in case no dice was specified (or invalid), roll a standard 6-sided dice.
if(dicesToRoll.isEmpty()) if (dicesToRoll.isEmpty())
{ {
Dice standardDice = new Dice(6); Dice standardDice = new Dice(6);
dicesToRoll.put(standardDice, 1); dicesToRoll.put(standardDice, 1);
totalRolls = 1; totalRolls = 1;
} }
for(Map.Entry<Dice, Integer> entry : dicesToRoll.entrySet()) for (Map.Entry<Dice, Integer> entry : dicesToRoll.entrySet())
{ {
Dice dice = entry.getKey(); Dice dice = entry.getKey();
Integer rollsToMake = entry.getValue(); Integer rollsToMake = entry.getValue();
for(int roll = 0; roll < rollsToMake; roll++) for (int roll = 0; roll < rollsToMake; roll++)
{ {
dice.roll(); dice.roll();
rolledDices.add(new Dice(dice)); rolledDices.add(new Dice(dice));
@@ -131,20 +132,23 @@ public class DiceRoll
embedBuilder.setAuthor(author.getAsTag(), null, author.getAvatarUrl()); embedBuilder.setAuthor(author.getAsTag(), null, author.getAvatarUrl());
embedBuilder.setTitle("Dice Roll"); embedBuilder.setTitle("Dice Roll");
if(RandomUtil.isRandomOrgKeyValid()) if (RandomUtil.isRandomOrgKeyValid())
embedBuilder.setFooter("Seed provided by random.org"); embedBuilder.setFooter("Seed provided by random.org");
StringBuilder message = new StringBuilder(); StringBuilder message = new StringBuilder();
int total = 0; int total = 0;
int previousDiceSides = 0; int previousDiceSides = 0;
for (Dice dice : rolledDices) { for (Dice dice : rolledDices)
{
int diceSize = dice.getSides(); int diceSize = dice.getSides();
if (previousDiceSides != diceSize) { if (previousDiceSides != diceSize)
{
message.append("\nd").append(diceSize).append(": "); message.append("\nd").append(diceSize).append(": ");
previousDiceSides = diceSize; previousDiceSides = diceSize;
} else if (previousDiceSides != 0) { } else if (previousDiceSides != 0)
{
message.append(", "); message.append(", ");
} }
@@ -154,7 +158,7 @@ public class DiceRoll
} }
// discord doesn't allow embed fields to be longer than 1024 and errors out // discord doesn't allow embed fields to be longer than 1024 and errors out
if(message.length() > 1024) if (message.length() > 1024)
{ {
return new MessageResponse("Too many rolls!", null); return new MessageResponse("Too many rolls!", null);
} }

View File

@@ -10,7 +10,8 @@ import wtf.beatrice.hidekobot.HidekoBot;
public class Invite public class Invite
{ {
private Invite() { private Invite()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -22,7 +23,7 @@ public class Invite
{ {
embedBuilder.setColor(Cache.getBotColor()); embedBuilder.setColor(Cache.getBotColor());
String avatarUrl = HidekoBot.getAPI().getSelfUser().getAvatarUrl(); String avatarUrl = HidekoBot.getAPI().getSelfUser().getAvatarUrl();
if(avatarUrl != null) embedBuilder.setThumbnail(avatarUrl); if (avatarUrl != null) embedBuilder.setThumbnail(avatarUrl);
embedBuilder.setTitle("Invite"); embedBuilder.setTitle("Invite");
embedBuilder.appendDescription("Click on the button below to invite " + embedBuilder.appendDescription("Click on the button below to invite " +
Cache.getBotName() + Cache.getBotName() +

View File

@@ -11,7 +11,8 @@ import java.util.concurrent.TimeUnit;
public class LoveCalculator public class LoveCalculator
{ {
private LoveCalculator() { private LoveCalculator()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -21,7 +22,7 @@ public class LoveCalculator
String userId2 = user2.getId(); String userId2 = user2.getId();
Integer loveAmount = Cache.getLoveCalculatorValue(userId1, userId2); Integer loveAmount = Cache.getLoveCalculatorValue(userId1, userId2);
if(loveAmount == null) if (loveAmount == null)
{ {
loveAmount = RandomUtil.getRandomNumber(0, 100); loveAmount = RandomUtil.getRandomNumber(0, 100);
Cache.cacheLoveCalculatorValue(userId1, userId2, loveAmount); Cache.cacheLoveCalculatorValue(userId1, userId2, loveAmount);
@@ -30,9 +31,9 @@ public class LoveCalculator
} }
String formattedAmount = loveAmount + "%"; String formattedAmount = loveAmount + "%";
if(loveAmount <= 30) formattedAmount += "... \uD83D\uDE22"; if (loveAmount <= 30) formattedAmount += "... \uD83D\uDE22";
else if(loveAmount < 60) formattedAmount += "! \uD83E\uDDD0"; else if (loveAmount < 60) formattedAmount += "! \uD83E\uDDD0";
else if(loveAmount < 75) formattedAmount += "!!! \uD83E\uDD73"; else if (loveAmount < 75) formattedAmount += "!!! \uD83E\uDD73";
else formattedAmount = "" + formattedAmount + "!!! \uD83D\uDE0D\uD83D\uDCA5"; else formattedAmount = "" + formattedAmount + "!!! \uD83D\uDE0D\uD83D\uDCA5";
EmbedBuilder embedBuilder = new EmbedBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder();

View File

@@ -14,7 +14,8 @@ import java.util.List;
public class MagicBall public class MagicBall
{ {
private MagicBall() { private MagicBall()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -55,7 +56,7 @@ public class MagicBall
{ {
// add a question mark at the end, if missing. // add a question mark at the end, if missing.
// this might not always apply but it's fun // this might not always apply but it's fun
if(!question.endsWith("?")) question += "?"; if (!question.endsWith("?")) question += "?";
String answer = getRandomAnswer(); String answer = getRandomAnswer();

View File

@@ -9,7 +9,8 @@ import wtf.beatrice.hidekobot.objects.MessageResponse;
public class ProfileImage public class ProfileImage
{ {
private ProfileImage() { private ProfileImage()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -20,9 +21,11 @@ public class ProfileImage
// method to find closest value to accepted values // method to find closest value to accepted values
int distance = Math.abs(acceptedSizes[0] - resolution); int distance = Math.abs(acceptedSizes[0] - resolution);
int idx = 0; int idx = 0;
for(int c = 1; c < acceptedSizes.length; c++){ for (int c = 1; c < acceptedSizes.length; c++)
{
int cdistance = Math.abs(acceptedSizes[c] - resolution); int cdistance = Math.abs(acceptedSizes[c] - resolution);
if(cdistance < distance){ if (cdistance < distance)
{
idx = c; idx = c;
distance = cdistance; distance = cdistance;
} }
@@ -40,14 +43,15 @@ public class ProfileImage
User.Profile userProfile = user.retrieveProfile().complete(); User.Profile userProfile = user.retrieveProfile().complete();
ImageProxy bannerProxy = userProfile.getBanner(); ImageProxy bannerProxy = userProfile.getBanner();
if(imageType == ImageType.AVATAR) if (imageType == ImageType.AVATAR)
{ {
resolutionString = resolution + " × " + resolution; resolutionString = resolution + " × " + resolution;
imageLink = user.getEffectiveAvatar().getUrl(resolution); imageLink = user.getEffectiveAvatar().getUrl(resolution);
} else { } else
{
int verticalRes = 361 * resolution / 1024; int verticalRes = 361 * resolution / 1024;
resolutionString = resolution + " × " + verticalRes; resolutionString = resolution + " × " + verticalRes;
if(bannerProxy != null) if (bannerProxy != null)
imageLink = bannerProxy.getUrl(resolution); imageLink = bannerProxy.getUrl(resolution);
} }
@@ -64,21 +68,22 @@ public class ProfileImage
// string builder to create a string that links to all available resolutions // string builder to create a string that links to all available resolutions
StringBuilder links = new StringBuilder(); StringBuilder links = new StringBuilder();
for(int pos = 0; pos < acceptedSizes.length; pos++) for (int pos = 0; pos < acceptedSizes.length; pos++)
{ {
int currSize = acceptedSizes[pos]; int currSize = acceptedSizes[pos];
String currLink; String currLink;
if(imageType == ImageType.AVATAR) if (imageType == ImageType.AVATAR)
{ {
currLink = user.getEffectiveAvatar().getUrl(currSize); currLink = user.getEffectiveAvatar().getUrl(currSize);
} else { } else
if(bannerProxy == null) break; {
if (bannerProxy == null) break;
currLink = bannerProxy.getUrl(currSize); currLink = bannerProxy.getUrl(currSize);
} }
links.append("**[").append(currSize).append("px](").append(currLink).append(")**"); links.append("**[").append(currSize).append("px](").append(currLink).append(")**");
if(pos + 1 != acceptedSizes.length) // don't add a separator on the last iteration if (pos + 1 != acceptedSizes.length) // don't add a separator on the last iteration
{ {
links.append(" | "); links.append(" | ");
} }
@@ -87,15 +92,16 @@ public class ProfileImage
embedBuilder.addField("Available resolutions", links.toString(), false); embedBuilder.addField("Available resolutions", links.toString(), false);
if (imageLink != null)
if(imageLink != null)
embedBuilder.setImage(imageLink); embedBuilder.setImage(imageLink);
if(imageLink == null) { if (imageLink == null)
{
String error = "I couldn't find " + user.getAsMention() + "'s " + imageTypeName + "!"; String error = "I couldn't find " + user.getAsMention() + "'s " + imageTypeName + "!";
return new MessageResponse(error, null); return new MessageResponse(error, null);
} else { } else
{
return new MessageResponse(null, embedBuilder.build()); return new MessageResponse(null, embedBuilder.build());
} }
} }

View File

@@ -5,11 +5,13 @@ import net.dv8tion.jda.api.Permission;
public class Say public class Say
{ {
private Say() { private Say()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
public static Permission getPermission() { public static Permission getPermission()
{
return Permission.MESSAGE_MANAGE; return Permission.MESSAGE_MANAGE;
} }
} }

View File

@@ -36,7 +36,8 @@ import java.util.concurrent.TimeUnit;
public class Trivia public class Trivia
{ {
private Trivia() { private Trivia()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -52,14 +53,23 @@ public class Trivia
// first string is the channelId, the list contain all score records for that channel // first string is the channelId, the list contain all score records for that channel
public static HashMap<String, LinkedList<TriviaScore>> channelAndScores = new HashMap<>(); public static HashMap<String, LinkedList<TriviaScore>> channelAndScores = new HashMap<>();
public static String getTriviaLink(int categoryId) {return TRIVIA_API_LINK + categoryId; } public static String getTriviaLink(int categoryId)
public static String getCategoriesLink() {return TRIVIA_API_CATEGORIES_LINK; } {
return TRIVIA_API_LINK + categoryId;
}
public static String getNoDMsError() { public static String getCategoriesLink()
{
return TRIVIA_API_CATEGORIES_LINK;
}
public static String getNoDMsError()
{
return "\uD83D\uDE22 Sorry! Trivia doesn't work in DMs."; return "\uD83D\uDE22 Sorry! Trivia doesn't work in DMs.";
} }
public static String getTriviaAlreadyRunningError() { public static String getTriviaAlreadyRunningError()
{
// todo nicer looking // todo nicer looking
return "Trivia is already running here!"; return "Trivia is already running here!";
} }
@@ -67,10 +77,10 @@ public class Trivia
public static MessageResponse generateMainScreen() public static MessageResponse generateMainScreen()
{ {
JSONObject categoriesJson = Trivia.fetchJson(Trivia.getCategoriesLink()); JSONObject categoriesJson = Trivia.fetchJson(Trivia.getCategoriesLink());
if(categoriesJson == null) if (categoriesJson == null)
return new MessageResponse("Error fetching trivia!", null); // todo nicer with emojis return new MessageResponse("Error fetching trivia!", null); // todo nicer with emojis
List<TriviaCategory> categories = Trivia.parseCategories(categoriesJson); List<TriviaCategory> categories = Trivia.parseCategories(categoriesJson);
if(categories.isEmpty()) if (categories.isEmpty())
return new MessageResponse("Error parsing trivia categories!", null); // todo nicer with emojis return new MessageResponse("Error parsing trivia categories!", null); // todo nicer with emojis
categories.sort(new TriviaCategoryComparator()); categories.sort(new TriviaCategoryComparator());
@@ -90,7 +100,7 @@ public class Trivia
StringSelectMenu.Builder menuBuilder = StringSelectMenu.create("trivia_categories"); StringSelectMenu.Builder menuBuilder = StringSelectMenu.create("trivia_categories");
for(TriviaCategory category : categories) for (TriviaCategory category : categories)
{ {
String name = category.categoryName(); String name = category.categoryName();
int id = category.categoryId(); int id = category.categoryId();
@@ -102,20 +112,22 @@ public class Trivia
public static JSONObject fetchJson(String link) public static JSONObject fetchJson(String link)
{ {
try { try
{
URL url = new URL(link); URL url = new URL(link);
URLConnection connection = url.openConnection(); URLConnection connection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String currentChar; String currentChar;
StringBuilder jsonStrBuilder = new StringBuilder(); StringBuilder jsonStrBuilder = new StringBuilder();
while((currentChar = bufferedReader.readLine()) != null) while ((currentChar = bufferedReader.readLine()) != null)
{ {
jsonStrBuilder.append(currentChar); jsonStrBuilder.append(currentChar);
} }
bufferedReader.close(); bufferedReader.close();
return new JSONObject(jsonStrBuilder.toString()); return new JSONObject(jsonStrBuilder.toString());
} catch (IOException e) { } catch (IOException e)
{
LOGGER.error("JSON Parsing Exception", e); LOGGER.error("JSON Parsing Exception", e);
} }
@@ -128,7 +140,7 @@ public class Trivia
JSONArray results = jsonObject.getJSONArray("results"); JSONArray results = jsonObject.getJSONArray("results");
for(Object currentQuestionGeneric : results) for (Object currentQuestionGeneric : results)
{ {
JSONObject questionJson = (JSONObject) currentQuestionGeneric; JSONObject questionJson = (JSONObject) currentQuestionGeneric;
String question = StringEscapeUtils.unescapeHtml4(questionJson.getString("question")); String question = StringEscapeUtils.unescapeHtml4(questionJson.getString("question"));
@@ -137,7 +149,7 @@ public class Trivia
List<String> incorrectAnswersList = new ArrayList<>(); List<String> incorrectAnswersList = new ArrayList<>();
JSONArray incorrectAnswers = questionJson.getJSONArray("incorrect_answers"); JSONArray incorrectAnswers = questionJson.getJSONArray("incorrect_answers");
for(Object incorrectAnswerGeneric : incorrectAnswers) for (Object incorrectAnswerGeneric : incorrectAnswers)
{ {
String incorrectAnswer = (String) incorrectAnswerGeneric; String incorrectAnswer = (String) incorrectAnswerGeneric;
incorrectAnswersList.add(StringEscapeUtils.unescapeHtml4(incorrectAnswer)); incorrectAnswersList.add(StringEscapeUtils.unescapeHtml4(incorrectAnswer));
@@ -154,7 +166,7 @@ public class Trivia
{ {
List<TriviaCategory> categories = new ArrayList<>(); List<TriviaCategory> categories = new ArrayList<>();
JSONArray categoriesArray = jsonObject.getJSONArray("trivia_categories"); JSONArray categoriesArray = jsonObject.getJSONArray("trivia_categories");
for(Object categoryObject : categoriesArray) for (Object categoryObject : categoriesArray)
{ {
JSONObject categoryJson = (JSONObject) categoryObject; JSONObject categoryJson = (JSONObject) categoryObject;
@@ -172,14 +184,14 @@ public class Trivia
User user = event.getUser(); User user = event.getUser();
String channelId = event.getChannel().getId(); String channelId = event.getChannel().getId();
if(trackResponse(user, event.getChannel())) if (trackResponse(user, event.getChannel()))
{ {
LinkedList<TriviaScore> scores = channelAndScores.get(channelId); LinkedList<TriviaScore> scores = channelAndScores.get(channelId);
if(scores == null) scores = new LinkedList<>(); if (scores == null) scores = new LinkedList<>();
TriviaScore currentUserScore = null; TriviaScore currentUserScore = null;
for(TriviaScore score : scores) for (TriviaScore score : scores)
{ {
if(score.getUser().equals(user)) if (score.getUser().equals(user))
{ {
currentUserScore = score; currentUserScore = score;
scores.remove(score); scores.remove(score);
@@ -187,25 +199,27 @@ public class Trivia
} }
} }
if(currentUserScore == null) if (currentUserScore == null)
{ {
currentUserScore = new TriviaScore(user); currentUserScore = new TriviaScore(user);
} }
if(answerType.equals(AnswerType.CORRECT)) if (answerType.equals(AnswerType.CORRECT))
{ {
event.reply(user.getAsMention() + " got it right! \uD83E\uDD73 (**+3**)").queue(); event.reply(user.getAsMention() + " got it right! \uD83E\uDD73 (**+3**)").queue();
currentUserScore.changeScore(3); currentUserScore.changeScore(3);
} else { } else
{
event.reply("" + user.getAsMention() + ", that's not the right answer! (**-1**)").queue(); event.reply("" + user.getAsMention() + ", that's not the right answer! (**-1**)").queue();
currentUserScore.changeScore(-1); currentUserScore.changeScore(-1);
} }
scores.add(currentUserScore); scores.add(currentUserScore);
channelAndScores.put(channelId, scores); channelAndScores.put(channelId, scores);
} else { } else
{
event.reply("☹️ " + user.getAsMention() + ", you can't answer twice!") event.reply("☹️ " + user.getAsMention() + ", you can't answer twice!")
.queue(interaction -> .queue(interaction ->
Cache.getTaskScheduler().schedule(() -> Cache.getTaskScheduler().schedule(() ->
@@ -220,17 +234,18 @@ public class Trivia
List<String> responders = channelAndWhoResponded.get(channelId); List<String> responders = channelAndWhoResponded.get(channelId);
if(responders == null) if (responders == null)
{ {
responders = new ArrayList<>(); responders = new ArrayList<>();
} }
if(responders.isEmpty() || !responders.contains(userId)) if (responders.isEmpty() || !responders.contains(userId))
{ {
responders.add(userId); responders.add(userId);
channelAndWhoResponded.put(channelId, responders); channelAndWhoResponded.put(channelId, responders);
return true; // response was successfully tracked return true; // response was successfully tracked
} else { } else
{
return false; // response wasn't tracked because there already was an entry return false; // response wasn't tracked because there already was an entry
} }
} }
@@ -238,7 +253,7 @@ public class Trivia
public static void handleMenuSelection(StringSelectInteractionEvent event) public static void handleMenuSelection(StringSelectInteractionEvent event)
{ {
// check if the user interacting is the same one who ran the command // check if the user interacting is the same one who ran the command
if(!(Cache.getDatabaseSource().isUserTrackedFor(event.getUser().getId(), event.getMessageId()))) if (!(Cache.getDatabaseSource().isUserTrackedFor(event.getUser().getId(), event.getMessageId())))
{ {
event.reply("❌ You did not run this command!").setEphemeral(true).queue(); event.reply("❌ You did not run this command!").setEphemeral(true).queue();
return; return;
@@ -263,7 +278,7 @@ public class Trivia
Message message = event.getMessage(); Message message = event.getMessage();
MessageChannel channel = message.getChannel(); MessageChannel channel = message.getChannel();
if(Trivia.channelsRunningTrivia.contains(channel.getId())) if (Trivia.channelsRunningTrivia.contains(channel.getId()))
{ {
// todo nicer looking // todo nicer looking
// todo: also what if the bot stops (database...?) // todo: also what if the bot stops (database...?)
@@ -271,7 +286,8 @@ public class Trivia
Message err = event.reply("Trivia is already running here!").complete().retrieveOriginal().complete(); Message err = event.reply("Trivia is already running here!").complete().retrieveOriginal().complete();
Cache.getTaskScheduler().schedule(() -> err.delete().queue(), 10, TimeUnit.SECONDS); Cache.getTaskScheduler().schedule(() -> err.delete().queue(), 10, TimeUnit.SECONDS);
return; return;
} else { } else
{
// todo nicer looking // todo nicer looking
event.reply("Starting new Trivia session!").queue(); event.reply("Starting new Trivia session!").queue();
} }
@@ -288,7 +304,8 @@ public class Trivia
Trivia.channelsRunningTrivia.add(channel.getId()); Trivia.channelsRunningTrivia.add(channel.getId());
} }
public enum AnswerType { public enum AnswerType
{
CORRECT, WRONG CORRECT, WRONG
} }

View File

@@ -25,15 +25,19 @@ import java.util.List;
public class UrbanDictionary public class UrbanDictionary
{ {
private UrbanDictionary() { private UrbanDictionary()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
public static LinkedList<String> getCommandLabels() public static LinkedList<String> getCommandLabels()
{ return new LinkedList<>(Arrays.asList("urban", "urbandictionary", "ud")); } {
return new LinkedList<>(Arrays.asList("urban", "urbandictionary", "ud"));
}
public static String getBaseUrl() { public static String getBaseUrl()
{
return "https://www.urbandictionary.com/define.php?term="; return "https://www.urbandictionary.com/define.php?term=";
} }
@@ -55,7 +59,8 @@ public class UrbanDictionary
.withEmoji(Emoji.fromFormatted("\uD83D\uDDD1")); .withEmoji(Emoji.fromFormatted("\uD83D\uDDD1"));
} }
public static String getNoArgsError() { public static String getNoArgsError()
{
return "\uD83D\uDE22 I need to know what to search for!"; return "\uD83D\uDE22 I need to know what to search for!";
} }
@@ -63,7 +68,7 @@ public class UrbanDictionary
{ {
term = term.replaceAll("[^\\w\\s]", ""); // only keep letters, numbers and spaces term = term.replaceAll("[^\\w\\s]", ""); // only keep letters, numbers and spaces
term = WordUtils.capitalizeFully(term); // Make Every Word Start With A Capital Letter term = WordUtils.capitalizeFully(term); // Make Every Word Start With A Capital Letter
if(forUrl) term = term.replaceAll("\\s+", "+"); // replace all whitespaces with + for the url if (forUrl) term = term.replaceAll("\\s+", "+"); // replace all whitespaces with + for the url
if (term.length() > 64) term = term.substring(0, 64); // cut it to length to avoid abuse if (term.length() > 64) term = term.substring(0, 64); // cut it to length to avoid abuse
return term; return term;
} }
@@ -87,7 +92,7 @@ public class UrbanDictionary
embedBuilder.addField("\uD83D\uDCD6 Definition", search.getPlaintextMeanings().get(page), false); embedBuilder.addField("\uD83D\uDCD6 Definition", search.getPlaintextMeanings().get(page), false);
embedBuilder.addField("\uD83D\uDCAD Example", search.getPlaintextExamples().get(page), false); embedBuilder.addField("\uD83D\uDCAD Example", search.getPlaintextExamples().get(page), false);
embedBuilder.addField("\uD83D\uDCCC Submission", embedBuilder.addField("\uD83D\uDCCC Submission",
"*Entry " + (page+1) + " | Sent by " + search.getContributorsNames().get(page) + "*Entry " + (page + 1) + " | Sent by " + search.getContributorsNames().get(page) +
" on" + search.getSubmissionDates().get(page) + "*", " on" + search.getSubmissionDates().get(page) + "*",
false); false);
@@ -118,7 +123,8 @@ public class UrbanDictionary
DatabaseSource database = Cache.getDatabaseSource(); DatabaseSource database = Cache.getDatabaseSource();
// check if the user interacting is the same one who ran the command // check if the user interacting is the same one who ran the command
if (!(database.isUserTrackedFor(event.getUser().getId(), messageId))) { if (!(database.isUserTrackedFor(event.getUser().getId(), messageId)))
{
event.reply("❌ You did not run this command!").setEphemeral(true).queue(); event.reply("❌ You did not run this command!").setEphemeral(true).queue();
return; return;
} }
@@ -140,9 +146,9 @@ public class UrbanDictionary
serializedExamples, serializedContributors, serializedDates); serializedExamples, serializedContributors, serializedDates);
// move to new page // move to new page
if(changeType == ChangeType.NEXT) if (changeType == ChangeType.NEXT)
page++; page++;
else if(changeType == ChangeType.PREVIOUS) else if (changeType == ChangeType.PREVIOUS)
page--; page--;
term = UrbanDictionary.sanitizeArgs(term, false); term = UrbanDictionary.sanitizeArgs(term, false);
@@ -153,17 +159,19 @@ public class UrbanDictionary
// get all attached components and check which ones need to be enabled or disabled // get all attached components and check which ones need to be enabled or disabled
List<ItemComponent> components = new ArrayList<>(); List<ItemComponent> components = new ArrayList<>();
if(page > 0) if (page > 0)
{ {
components.add(UrbanDictionary.getPreviousPageButton().asEnabled()); components.add(UrbanDictionary.getPreviousPageButton().asEnabled());
} else { } else
{
components.add(UrbanDictionary.getPreviousPageButton().asDisabled()); components.add(UrbanDictionary.getPreviousPageButton().asDisabled());
} }
if(page + 1 == search.getPages()) if (page + 1 == search.getPages())
{ {
components.add(UrbanDictionary.getNextPageButton().asDisabled()); components.add(UrbanDictionary.getNextPageButton().asDisabled());
} else { } else
{
components.add(UrbanDictionary.getNextPageButton().asEnabled()); components.add(UrbanDictionary.getNextPageButton().asEnabled());
} }
@@ -216,10 +224,10 @@ public class UrbanDictionary
contributorsNames = new LinkedList<>(); contributorsNames = new LinkedList<>();
submissionDates = new LinkedList<>(); submissionDates = new LinkedList<>();
for(Element definition : definitions) for (Element definition : definitions)
{ {
Elements meaningSingleton = definition.getElementsByClass("meaning"); Elements meaningSingleton = definition.getElementsByClass("meaning");
if(meaningSingleton.isEmpty()) if (meaningSingleton.isEmpty())
{ {
plaintextMeanings.add(" "); plaintextMeanings.add(" ");
} else } else
@@ -231,13 +239,13 @@ public class UrbanDictionary
// this is used to fix eg. &amp; being shown literally instead of being parsed // this is used to fix eg. &amp; being shown literally instead of being parsed
text = StringEscapeUtils.unescapeHtml4(text); text = StringEscapeUtils.unescapeHtml4(text);
// discord only allows 1024 characters for embed fields // discord only allows 1024 characters for embed fields
if(text.length() > 1024) text = text.substring(0, 1020) + "..."; if (text.length() > 1024) text = text.substring(0, 1020) + "...";
plaintextMeanings.add(text); plaintextMeanings.add(text);
} }
Elements exampleSingleton = definition.getElementsByClass("example"); Elements exampleSingleton = definition.getElementsByClass("example");
if(exampleSingleton.isEmpty()) if (exampleSingleton.isEmpty())
{ {
plaintextExamples.add(" "); plaintextExamples.add(" ");
} else } else
@@ -249,12 +257,12 @@ public class UrbanDictionary
// this is used to fix eg. &amp; being shown literally instead of being parsed // this is used to fix eg. &amp; being shown literally instead of being parsed
text = StringEscapeUtils.unescapeHtml4(text); text = StringEscapeUtils.unescapeHtml4(text);
// discord only allows 1024 characters for embed fields // discord only allows 1024 characters for embed fields
if(text.length() > 1024) text = text.substring(0, 1020) + "..."; if (text.length() > 1024) text = text.substring(0, 1020) + "...";
plaintextExamples.add(text); plaintextExamples.add(text);
} }
Elements contributorSingleton = definition.getElementsByClass("contributor"); Elements contributorSingleton = definition.getElementsByClass("contributor");
if(contributorSingleton.isEmpty()) if (contributorSingleton.isEmpty())
{ {
contributorsNames.add("Unknown"); contributorsNames.add("Unknown");
} else } else
@@ -282,39 +290,48 @@ public class UrbanDictionary
pages = submissionDates.size(); pages = submissionDates.size();
} }
public List<String> getPlaintextMeanings() { public List<String> getPlaintextMeanings()
{
return this.plaintextMeanings; return this.plaintextMeanings;
} }
public List<String> getPlaintextExamples() { public List<String> getPlaintextExamples()
{
return this.plaintextExamples; return this.plaintextExamples;
} }
public List<String> getContributorsNames() { public List<String> getContributorsNames()
{
return this.contributorsNames; return this.contributorsNames;
} }
public List<String> getSubmissionDates() { public List<String> getSubmissionDates()
{
return this.submissionDates; return this.submissionDates;
} }
public String getSerializedMeanings() { public String getSerializedMeanings()
{
return serializedMeanings; return serializedMeanings;
} }
public String getSerializedExamples() { public String getSerializedExamples()
{
return serializedExamples; return serializedExamples;
} }
public String getSerializedContributors() { public String getSerializedContributors()
{
return serializedContributors; return serializedContributors;
} }
public String getSerializedDates() { public String getSerializedDates()
{
return serializedDates; return serializedDates;
} }
public int getPages() { public int getPages()
{
return pages; return pages;
} }
} }

View File

@@ -27,7 +27,8 @@ import java.util.concurrent.TimeUnit;
public class UserPunishment public class UserPunishment
{ {
private UserPunishment() { private UserPunishment()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -42,24 +43,24 @@ public class UserPunishment
User targetUser = null; User targetUser = null;
OptionMapping targetUserArg = event.getOption("target"); OptionMapping targetUserArg = event.getOption("target");
if(targetUserArg != null) if (targetUserArg != null)
{ {
targetUser = targetUserArg.getAsUser(); targetUser = targetUserArg.getAsUser();
} }
List<IMentionable> mentions = null; List<IMentionable> mentions = null;
if(targetUser != null) mentions = new ArrayList<>(Collections.singletonList(targetUser)); if (targetUser != null) mentions = new ArrayList<>(Collections.singletonList(targetUser));
String reason = null; String reason = null;
OptionMapping reasonArg = event.getOption("reason"); OptionMapping reasonArg = event.getOption("reason");
if(reasonArg != null) if (reasonArg != null)
{ {
reason = reasonArg.getAsString(); reason = reasonArg.getAsString();
} }
String timeDiff = null; String timeDiff = null;
OptionMapping timeDiffArg = event.getOption("duration"); OptionMapping timeDiffArg = event.getOption("duration");
if(timeDiffArg != null) if (timeDiffArg != null)
{ {
timeDiff = timeDiffArg.getAsString(); timeDiff = timeDiffArg.getAsString();
} }
@@ -71,13 +72,13 @@ public class UserPunishment
// we should probably rework the it so that it works better in both scenarios. // we should probably rework the it so that it works better in both scenarios.
String[] reasonSplit = null; String[] reasonSplit = null;
// generate the arguments array by splitting the string // generate the arguments array by splitting the string
if(reason != null) reasonSplit = reason.split("\\s+"); if (reason != null) reasonSplit = reason.split("\\s+");
//prepend timediff at index 0 //prepend timediff at index 0
if(timeDiff != null) reasonSplit = ArrayUtils.insert(0, reasonSplit, timeDiff); if (timeDiff != null) reasonSplit = ArrayUtils.insert(0, reasonSplit, timeDiff);
// in message-commands, the first arg would contain the user mention. since we have no one mentioned here, // in message-commands, the first arg would contain the user mention. since we have no one mentioned here,
// because it's in its own argument, we just prepend an empty string. note that this makes relying on the // because it's in its own argument, we just prepend an empty string. note that this makes relying on the
// first argument BAD, because it is no longer ensured that it contains the user mention. // first argument BAD, because it is no longer ensured that it contains the user mention.
if(timeDiff != null) reasonSplit = ArrayUtils.insert(0, reasonSplit, ""); if (timeDiff != null) reasonSplit = ArrayUtils.insert(0, reasonSplit, "");
MessageResponse response = getResponse(event.getUser(), MessageResponse response = getResponse(event.getUser(),
punishmentType, punishmentType,
@@ -85,9 +86,9 @@ public class UserPunishment
mentions, mentions,
reasonSplit); reasonSplit);
if(response.embed() != null) if (response.embed() != null)
event.getHook().editOriginalEmbeds(response.embed()).queue(); event.getHook().editOriginalEmbeds(response.embed()).queue();
else if(response.content() != null) else if (response.content() != null)
event.getHook().editOriginal(response.content()).queue(); event.getHook().editOriginal(response.content()).queue();
} }
@@ -102,9 +103,9 @@ public class UserPunishment
mentions, mentions,
args); args);
if(response.embed() != null) if (response.embed() != null)
event.getMessage().replyEmbeds(response.embed()).queue(); event.getMessage().replyEmbeds(response.embed()).queue();
else if(response.content() != null) else if (response.content() != null)
event.getMessage().reply(response.content()).queue(); event.getMessage().reply(response.content()).queue();
} }
@@ -117,13 +118,13 @@ public class UserPunishment
String punishmentTypeName = punishmentType.name().toLowerCase(); String punishmentTypeName = punishmentType.name().toLowerCase();
if(!(channel instanceof TextChannel)) if (!(channel instanceof TextChannel))
{ {
// todo nicer looking with emojis // todo nicer looking with emojis
return new MessageResponse("Sorry! I can't " + punishmentTypeName + " people in DMs.", null); return new MessageResponse("Sorry! I can't " + punishmentTypeName + " people in DMs.", null);
} }
if(mentions == null || mentions.isEmpty()) if (mentions == null || mentions.isEmpty())
{ {
// todo nicer looking with emojis // todo nicer looking with emojis
return new MessageResponse("You have to tell me who to " + punishmentTypeName + "!", null); return new MessageResponse("You have to tell me who to " + punishmentTypeName + "!", null);
@@ -132,7 +133,8 @@ public class UserPunishment
String mentionedId = mentions.get(0).getId(); String mentionedId = mentions.get(0).getId();
User mentioned = null; User mentioned = null;
try { try
{
mentioned = HidekoBot.getAPI().retrieveUserById(mentionedId).complete(); mentioned = HidekoBot.getAPI().retrieveUserById(mentionedId).complete();
} catch (RuntimeException ignored) } catch (RuntimeException ignored)
{ {
@@ -146,21 +148,21 @@ public class UserPunishment
// some commands require an additional parameter before the reason, so in that case, we should start at 2. // some commands require an additional parameter before the reason, so in that case, we should start at 2.
int startingPoint = punishmentType == PunishmentType.TIMEOUT ? 2 : 1; int startingPoint = punishmentType == PunishmentType.TIMEOUT ? 2 : 1;
if(args != null && args.length > startingPoint) if (args != null && args.length > startingPoint)
{ {
for(int i = startingPoint; i < args.length; i++) for (int i = startingPoint; i < args.length; i++)
{ {
String arg = args[i]; String arg = args[i];
reasonBuilder.append(arg); reasonBuilder.append(arg);
if(i + 1 != arg.length()) if (i + 1 != arg.length())
reasonBuilder.append(" "); // separate args with a space except on last iteration. reasonBuilder.append(" "); // separate args with a space except on last iteration.
} }
reason = reasonBuilder.toString(); reason = reasonBuilder.toString();
} }
if(mentioned == null) if (mentioned == null)
{ {
// todo nicer looking with emojis // todo nicer looking with emojis
return new MessageResponse("I can't " + punishmentTypeName + " that user!", null); return new MessageResponse("I can't " + punishmentTypeName + " that user!", null);
@@ -172,12 +174,15 @@ public class UserPunishment
AuditableRestAction<Void> punishmentAction = null; AuditableRestAction<Void> punishmentAction = null;
boolean impossible = false; boolean impossible = false;
try { try
switch (punishmentType) { {
switch (punishmentType)
{
case BAN -> punishmentAction = guild.ban(mentioned, 0, TimeUnit.SECONDS); case BAN -> punishmentAction = guild.ban(mentioned, 0, TimeUnit.SECONDS);
case KICK -> punishmentAction = guild.kick(mentioned); case KICK -> punishmentAction = guild.kick(mentioned);
case TIMEOUT -> { case TIMEOUT ->
if(args != null) {
if (args != null)
{ {
String durationStr = args[1]; String durationStr = args[1];
duration = FormatUtil.parseDuration(durationStr); duration = FormatUtil.parseDuration(durationStr);
@@ -185,14 +190,14 @@ public class UserPunishment
boolean isDurationValid = true; boolean isDurationValid = true;
if(duration == null) isDurationValid = false; if (duration == null) isDurationValid = false;
else else
{ {
if(duration.compareTo(maxTimeoutDuration) > 0) isDurationValid = false; if (duration.compareTo(maxTimeoutDuration) > 0) isDurationValid = false;
if(minTimeoutDuration.compareTo(duration) > 0) isDurationValid = false; if (minTimeoutDuration.compareTo(duration) > 0) isDurationValid = false;
} }
if(duration == null || !isDurationValid) if (duration == null || !isDurationValid)
{ {
// todo nicer looking with emojis // todo nicer looking with emojis
return new MessageResponse("Sorry, but the specified duration is invalid!", null); return new MessageResponse("Sorry, but the specified duration is invalid!", null);
@@ -201,24 +206,26 @@ public class UserPunishment
punishmentAction = guild.timeoutFor(mentioned, duration); punishmentAction = guild.timeoutFor(mentioned, duration);
} }
} }
} catch (RuntimeException ignored) { } catch (RuntimeException ignored)
{
impossible = true; impossible = true;
} }
if(punishmentAction == null) if (punishmentAction == null)
impossible = true; impossible = true;
if(impossible) if (impossible)
{ {
// todo nicer looking with emojis // todo nicer looking with emojis
return new MessageResponse("Sorry, I couldn't " + punishmentTypeName + " " + mentioned.getAsMention() + "!", return new MessageResponse("Sorry, I couldn't " + punishmentTypeName + " " + mentioned.getAsMention() + "!",
null); null);
} }
if(!reason.isEmpty() && !reasonBuilder.isEmpty()) if (!reason.isEmpty() && !reasonBuilder.isEmpty())
punishmentAction.reason("[" + author.getAsTag() + "] " + reason); punishmentAction.reason("[" + author.getAsTag() + "] " + reason);
try { try
{
punishmentAction.complete(); punishmentAction.complete();
} catch (RuntimeException ignored) } catch (RuntimeException ignored)
{ {
@@ -235,10 +242,10 @@ public class UserPunishment
embedBuilder.addField("\uD83D\uDC64 User", mentioned.getAsMention(), false); embedBuilder.addField("\uD83D\uDC64 User", mentioned.getAsMention(), false);
embedBuilder.addField("✂️ By", author.getAsMention(), false); embedBuilder.addField("✂️ By", author.getAsMention(), false);
if(duration != null) if (duration != null)
embedBuilder.addField("⏱️ Duration", FormatUtil.getNiceDuration(duration), false); embedBuilder.addField("⏱️ Duration", FormatUtil.getNiceDuration(duration), false);
if(reason.isEmpty()) if (reason.isEmpty())
reason = "*No reason specified*"; reason = "*No reason specified*";
embedBuilder.addField("\uD83D\uDCD6 Reason", reason, false); embedBuilder.addField("\uD83D\uDCD6 Reason", reason, false);
@@ -248,7 +255,8 @@ public class UserPunishment
} }
public enum PunishmentType { public enum PunishmentType
{
KICK("kicked"), KICK("kicked"),
BAN("banned"), BAN("banned"),
TIMEOUT("timed out"), TIMEOUT("timed out"),

View File

@@ -13,23 +13,25 @@ import java.util.List;
public class ProfileImageCommandCompleter extends SlashArgumentsCompleterImpl public class ProfileImageCommandCompleter extends SlashArgumentsCompleterImpl
{ {
public ProfileImageCommandCompleter(SlashCommand parentCommand) { public ProfileImageCommandCompleter(SlashCommand parentCommand)
{
super(parentCommand); super(parentCommand);
} }
@Override @Override
public void runCompletion(@NotNull CommandAutoCompleteInteractionEvent event) { public void runCompletion(@NotNull CommandAutoCompleteInteractionEvent event)
if(event.getFocusedOption().getName().equals("size")) {
if (event.getFocusedOption().getName().equals("size"))
{ {
List<Command.Choice> options = new ArrayList<>(); List<Command.Choice> options = new ArrayList<>();
for(int res : Cache.getSupportedAvatarResolutions()) for (int res : Cache.getSupportedAvatarResolutions())
{ {
String resString = String.valueOf(res); String resString = String.valueOf(res);
String userInput = event.getFocusedOption().getValue(); String userInput = event.getFocusedOption().getValue();
if(resString.startsWith(userInput)) if (resString.startsWith(userInput))
options.add(new Command.Choice(resString, res)); options.add(new Command.Choice(resString, res));
} }

View File

@@ -17,43 +17,49 @@ public class AliasCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Arrays.asList("alias", "aliases")); return new LinkedList<>(Arrays.asList("alias", "aliases"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return null; // anyone can use it return null; // anyone can use it
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.TOOLS; return CommandCategory.TOOLS;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "See other command aliases."; return "See other command aliases.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "<command>"; return "<command>";
} }
@Override @Override
public void runCommand(MessageReceivedEvent event, String label, String[] args) public void runCommand(MessageReceivedEvent event, String label, String[] args)
{ {
if(args.length == 0) if (args.length == 0)
{ {
event.getMessage().reply("\uD83D\uDE20 Hey, you have to specify a command!").queue(); event.getMessage().reply("\uD83D\uDE20 Hey, you have to specify a command!").queue();
return; return;
@@ -61,7 +67,7 @@ public class AliasCommand implements MessageCommand
String commandLabel = args[0].toLowerCase(); String commandLabel = args[0].toLowerCase();
MessageCommand command = Cache.getMessageCommandListener().getRegisteredCommand(commandLabel); MessageCommand command = Cache.getMessageCommandListener().getRegisteredCommand(commandLabel);
if(command == null) if (command == null)
{ {
event.getMessage().reply("Unrecognized command: `" + commandLabel + "`!").queue(); // todo prettier event.getMessage().reply("Unrecognized command: `" + commandLabel + "`!").queue(); // todo prettier
return; return;

View File

@@ -20,36 +20,42 @@ public class AvatarCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Collections.singletonList("avatar")); return new LinkedList<>(Collections.singletonList("avatar"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return null; // anyone can use it return null; // anyone can use it
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Get someone's avatar, or your own. You can additionally specify a resolution."; return "Get someone's avatar, or your own. You can additionally specify a resolution.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "[mentioned user] [resolution]"; return "[mentioned user] [resolution]";
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.TOOLS; return CommandCategory.TOOLS;
} }
@@ -63,23 +69,26 @@ public class AvatarCommand implements MessageCommand
// (mentions are handled differently by a specific method) // (mentions are handled differently by a specific method)
boolean resFound = false; boolean resFound = false;
for (String arg : args) { for (String arg : args)
try { {
try
{
int givenRes = Integer.parseInt(arg); int givenRes = Integer.parseInt(arg);
resolution = ProfileImage.parseResolution(givenRes); resolution = ProfileImage.parseResolution(givenRes);
resFound = true; resFound = true;
break; break;
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored)
{
// ignored because we're running a check after this block // ignored because we're running a check after this block
} }
} }
// fallback in case we didn't find any specified resolution // fallback in case we didn't find any specified resolution
if(!resFound) resolution = ProfileImage.parseResolution(512); if (!resFound) resolution = ProfileImage.parseResolution(512);
// check if someone is mentioned // check if someone is mentioned
Mentions mentions = event.getMessage().getMentions(); Mentions mentions = event.getMessage().getMentions();
if(mentions.getMentions().isEmpty()) if (mentions.getMentions().isEmpty())
{ {
user = event.getAuthor(); user = event.getAuthor();
} else } else
@@ -89,14 +98,14 @@ public class AvatarCommand implements MessageCommand
} }
// in case of issues, fallback to the sender // in case of issues, fallback to the sender
if(user == null) user = event.getAuthor(); if (user == null) user = event.getAuthor();
// send a response // send a response
MessageResponse response = ProfileImage.buildResponse(resolution, user, ProfileImage.ImageType.AVATAR); MessageResponse response = ProfileImage.buildResponse(resolution, user, ProfileImage.ImageType.AVATAR);
if(response.content() != null) if (response.content() != null)
{ {
event.getMessage().reply(response.content()).queue(); event.getMessage().reply(response.content()).queue();
} else if(response.embed() != null) } else if (response.embed() != null)
{ {
event.getMessage().replyEmbeds(response.embed()).queue(); event.getMessage().replyEmbeds(response.embed()).queue();
} }

View File

@@ -17,36 +17,42 @@ public class BanCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Collections.singletonList("ban")); return new LinkedList<>(Collections.singletonList("ban"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return new ArrayList<Permission>(Collections.singletonList(Permission.BAN_MEMBERS)); return new ArrayList<Permission>(Collections.singletonList(Permission.BAN_MEMBERS));
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.MODERATION; return CommandCategory.MODERATION;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Ban the mentioned user."; return "Ban the mentioned user.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "<mentioned user> [reason]"; return "<mentioned user> [reason]";
} }

View File

@@ -20,36 +20,42 @@ public class BannerCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Collections.singletonList("banner")); return new LinkedList<>(Collections.singletonList("banner"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return null; // anyone can use it return null; // anyone can use it
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Get someone's profile banner, or your own."; return "Get someone's profile banner, or your own.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "[mentioned user] [resolution]"; return "[mentioned user] [resolution]";
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.TOOLS; return CommandCategory.TOOLS;
} }
@@ -63,23 +69,26 @@ public class BannerCommand implements MessageCommand
// (mentions are handled differently by a specific method) // (mentions are handled differently by a specific method)
boolean resFound = false; boolean resFound = false;
for (String arg : args) { for (String arg : args)
try { {
try
{
int givenRes = Integer.parseInt(arg); int givenRes = Integer.parseInt(arg);
resolution = ProfileImage.parseResolution(givenRes); resolution = ProfileImage.parseResolution(givenRes);
resFound = true; resFound = true;
break; break;
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored)
{
// ignored because we're running a check after this block // ignored because we're running a check after this block
} }
} }
// fallback in case we didn't find any specified resolution // fallback in case we didn't find any specified resolution
if(!resFound) resolution = ProfileImage.parseResolution(512); if (!resFound) resolution = ProfileImage.parseResolution(512);
// check if someone is mentioned // check if someone is mentioned
Mentions mentions = event.getMessage().getMentions(); Mentions mentions = event.getMessage().getMentions();
if(mentions.getMentions().isEmpty()) if (mentions.getMentions().isEmpty())
{ {
user = event.getAuthor(); user = event.getAuthor();
} else } else
@@ -89,14 +98,14 @@ public class BannerCommand implements MessageCommand
} }
// in case of issues, fallback to the sender // in case of issues, fallback to the sender
if(user == null) user = event.getAuthor(); if (user == null) user = event.getAuthor();
// send a response // send a response
MessageResponse response = ProfileImage.buildResponse(resolution, user, ProfileImage.ImageType.BANNER); MessageResponse response = ProfileImage.buildResponse(resolution, user, ProfileImage.ImageType.BANNER);
if(response.content() != null) if (response.content() != null)
{ {
event.getMessage().reply(response.content()).queue(); event.getMessage().reply(response.content()).queue();
} else if(response.embed() != null) } else if (response.embed() != null)
{ {
event.getMessage().replyEmbeds(response.embed()).queue(); event.getMessage().replyEmbeds(response.embed()).queue();
} }

View File

@@ -18,46 +18,54 @@ public class BotInfoCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Arrays.asList("botinfo", "info")); return new LinkedList<>(Arrays.asList("botinfo", "info"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return null; // anyone can use it return null; // anyone can use it
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Get general info about the bot."; return "Get general info about the bot.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return null; return null;
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.TOOLS; return CommandCategory.TOOLS;
} }
@Override @Override
public void runCommand(MessageReceivedEvent event, String label, String[] args) { public void runCommand(MessageReceivedEvent event, String label, String[] args)
{
// get a list of message commands // get a list of message commands
LinkedList<MessageCommand> messageCommands = Cache.getMessageCommandListener().getRegisteredCommands(); LinkedList<MessageCommand> messageCommands = Cache.getMessageCommandListener().getRegisteredCommands();
LinkedList<String> commandNames = new LinkedList<>(); LinkedList<String> commandNames = new LinkedList<>();
for (MessageCommand command : messageCommands) { for (MessageCommand command : messageCommands)
{
commandNames.add(command.getCommandLabels().get(0)); commandNames.add(command.getCommandLabels().get(0));
} }

View File

@@ -19,33 +19,41 @@ public class ClearCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Collections.singletonList(ClearChat.getLabel())); return new LinkedList<>(Collections.singletonList(ClearChat.getLabel()));
} }
@Override @Override
public List<Permission> getPermissions() { return Collections.singletonList(ClearChat.getPermission()); } public List<Permission> getPermissions()
{
return Collections.singletonList(ClearChat.getPermission());
}
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.MODERATION; return CommandCategory.MODERATION;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Clear the current channel's chat history."; return "Clear the current channel's chat history.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "[amount]"; return "[amount]";
} }
@@ -54,7 +62,8 @@ public class ClearCommand implements MessageCommand
{ {
// 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)
{
event.getMessage().reply(error).queue(); event.getMessage().reply(error).queue();
return; return;
} }
@@ -64,7 +73,8 @@ public class ClearCommand implements MessageCommand
if (args.length == 0) toDeleteAmount = 1; if (args.length == 0) toDeleteAmount = 1;
else else
{ {
try { try
{
toDeleteAmount = Integer.parseInt(args[0]); toDeleteAmount = Integer.parseInt(args[0]);
} catch (NumberFormatException e) } catch (NumberFormatException e)
{ {
@@ -73,10 +83,11 @@ public class ClearCommand implements MessageCommand
} }
// cap the amount to avoid abuse. // cap the amount to avoid abuse.
if(toDeleteAmount > ClearChat.getMaxAmount()) toDeleteAmount = 0; if (toDeleteAmount > ClearChat.getMaxAmount()) toDeleteAmount = 0;
error = ClearChat.checkDeleteAmount(toDeleteAmount); error = ClearChat.checkDeleteAmount(toDeleteAmount);
if (error != null) { if (error != null)
{
event.getMessage().reply(error).queue(); event.getMessage().reply(error).queue();
return; return;
} }

View File

@@ -16,41 +16,48 @@ public class CoinFlipCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Arrays.asList("coinflip", "flip", "flipcoin")); return new LinkedList<>(Arrays.asList("coinflip", "flip", "flipcoin"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return null; // null because it can be used anywhere return null; // null because it can be used anywhere
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Flip a coin."; return "Flip a coin.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return null; return null;
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.FUN; return CommandCategory.FUN;
} }
@Override @Override
public void runCommand(MessageReceivedEvent event, String label, String[] args) { public void runCommand(MessageReceivedEvent event, String label, String[] args)
{
// perform coin flip // perform coin flip
event.getMessage().reply(CoinFlip.genRandom()) event.getMessage().reply(CoinFlip.genRandom())
@@ -59,6 +66,7 @@ public class CoinFlipCommand implements MessageCommand
{ {
// set the command as expiring and restrict it to the user who ran it // set the command as expiring and restrict it to the user who ran it
CoinFlip.trackAndRestrict(message, event.getAuthor()); CoinFlip.trackAndRestrict(message, event.getAuthor());
}, (error) -> {}); }, (error) -> {
});
} }
} }

View File

@@ -16,18 +16,21 @@ import java.util.List;
public class DiceRollCommand implements MessageCommand public class DiceRollCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Arrays.asList("diceroll", "droll", "roll")); return new LinkedList<>(Arrays.asList("diceroll", "droll", "roll"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return null; // anyone can use it return null; // anyone can use it
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@@ -47,13 +50,15 @@ public class DiceRollCommand implements MessageCommand
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "[dice size] [rolls]"; return "[dice size] [rolls]";
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.FUN; return CommandCategory.FUN;
} }
@@ -63,10 +68,10 @@ public class DiceRollCommand implements MessageCommand
MessageResponse response = DiceRoll.buildResponse(event.getAuthor(), args); MessageResponse response = DiceRoll.buildResponse(event.getAuthor(), args);
if(response.content() != null) if (response.content() != null)
{ {
event.getMessage().reply(response.content()).queue(); event.getMessage().reply(response.content()).queue();
} else if(response.embed() != null) } else if (response.embed() != null)
{ {
event.getMessage().replyEmbeds(response.embed()).queue(); event.getMessage().replyEmbeds(response.embed()).queue();
} }

View File

@@ -15,33 +15,41 @@ public class HelloCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Arrays.asList("hi", "hello", "heya")); return new LinkedList<>(Arrays.asList("hi", "hello", "heya"));
} }
@Override @Override
public List<Permission> getPermissions() { return null; } public List<Permission> getPermissions()
{
return null;
}
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Get pinged by the bot."; return "Get pinged by the bot.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return null; return null;
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.FUN; return CommandCategory.FUN;
} }

View File

@@ -18,34 +18,42 @@ public class HelpCommand implements MessageCommand
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Collections.singletonList("help")); return new LinkedList<>(Collections.singletonList("help"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { return null; } public List<Permission> getPermissions()
{
return null;
}
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Get general help on the bot. Specify a command if you want specific help about that command."; return "Get general help on the bot. Specify a command if you want specific help about that command.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "[command]"; return "[command]";
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.TOOLS; return CommandCategory.TOOLS;
} }
@@ -54,14 +62,14 @@ public class HelpCommand implements MessageCommand
{ {
LinkedHashMap<CommandCategory, LinkedList<MessageCommand>> commandCategories = new LinkedHashMap<>(); LinkedHashMap<CommandCategory, LinkedList<MessageCommand>> commandCategories = new LinkedHashMap<>();
if(args.length == 0) if (args.length == 0)
{ {
for(CommandCategory category : CommandCategory.values()) for (CommandCategory category : CommandCategory.values())
{ {
LinkedList<MessageCommand> commandsOfThisCategory = new LinkedList<>(); LinkedList<MessageCommand> commandsOfThisCategory = new LinkedList<>();
for (MessageCommand command : Cache.getMessageCommandListener().getRegisteredCommands()) for (MessageCommand command : Cache.getMessageCommandListener().getRegisteredCommands())
{ {
if(command.getCategory().equals(category)) if (command.getCategory().equals(category))
{ {
commandsOfThisCategory.add(command); commandsOfThisCategory.add(command);
} }
@@ -79,18 +87,18 @@ 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(Map.Entry<CommandCategory, LinkedList<MessageCommand>> entry : commandCategories.entrySet()) for (Map.Entry<CommandCategory, LinkedList<MessageCommand>> entry : commandCategories.entrySet())
{ {
StringBuilder commandsList = new StringBuilder(); StringBuilder commandsList = new StringBuilder();
CommandCategory category = entry.getKey(); CommandCategory category = entry.getKey();
LinkedList<MessageCommand> commandsOfThisCategory = entry.getValue(); LinkedList<MessageCommand> commandsOfThisCategory = entry.getValue();
for(int pos = 0; pos < commandsOfThisCategory.size(); pos++) for (int pos = 0; pos < commandsOfThisCategory.size(); pos++)
{ {
MessageCommand command = commandsOfThisCategory.get(pos); MessageCommand command = commandsOfThisCategory.get(pos);
commandsList.append("`").append(command.getCommandLabels().get(0)).append("`"); commandsList.append("`").append(command.getCommandLabels().get(0)).append("`");
if(pos + 1 != commandsOfThisCategory.size()) if (pos + 1 != commandsOfThisCategory.size())
commandsList.append(", "); // separate with comma except on last run commandsList.append(", "); // separate with comma except on last run
} }
@@ -102,11 +110,12 @@ public class HelpCommand implements MessageCommand
} }
event.getMessage().replyEmbeds(embedBuilder.build()).queue(); event.getMessage().replyEmbeds(embedBuilder.build()).queue();
} else { } else
{
String commandLabel = args[0].toLowerCase(); String commandLabel = args[0].toLowerCase();
MessageCommand command = Cache.getMessageCommandListener().getRegisteredCommand(commandLabel); MessageCommand command = Cache.getMessageCommandListener().getRegisteredCommand(commandLabel);
if(command == null) if (command == null)
{ {
event.getMessage().reply("Unrecognized command: `" + commandLabel + "`!").queue(); // todo prettier event.getMessage().reply("Unrecognized command: `" + commandLabel + "`!").queue(); // todo prettier
return; return;
@@ -115,23 +124,24 @@ public class HelpCommand implements MessageCommand
commandLabel = command.getCommandLabels().get(0); commandLabel = command.getCommandLabels().get(0);
String usage = "`" + Cache.getBotPrefix() + " " + commandLabel; String usage = "`" + Cache.getBotPrefix() + " " + commandLabel;
String internalUsage = command.getUsage(); String internalUsage = command.getUsage();
if(internalUsage != null) usage += " " + internalUsage; if (internalUsage != null) usage += " " + internalUsage;
usage += "`"; usage += "`";
String aliases = Alias.generateNiceAliases(command); String aliases = Alias.generateNiceAliases(command);
List<Permission> permissions = command.getPermissions(); List<Permission> permissions = command.getPermissions();
StringBuilder permissionsStringBuilder = new StringBuilder(); StringBuilder permissionsStringBuilder = new StringBuilder();
if(permissions == null) if (permissions == null)
{ {
permissionsStringBuilder = new StringBuilder("Available to everyone"); permissionsStringBuilder = new StringBuilder("Available to everyone");
} else { } else
for(int i = 0; i < permissions.size(); i++) {
for (int i = 0; i < permissions.size(); i++)
{ {
Permission permission = permissions.get(i); Permission permission = permissions.get(i);
permissionsStringBuilder.append("**").append(permission.getName()).append("**"); permissionsStringBuilder.append("**").append(permission.getName()).append("**");
if(i + 1 != permissions.size()) if (i + 1 != permissions.size())
permissionsStringBuilder.append(", "); // separate with comma expect on last iteration permissionsStringBuilder.append(", "); // separate with comma expect on last iteration
} }
} }

View File

@@ -19,36 +19,42 @@ public class InviteCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Collections.singletonList("invite")); return new LinkedList<>(Collections.singletonList("invite"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return null; return null;
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Get the bot's invite link."; return "Get the bot's invite link.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return null; return null;
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.MODERATION; return CommandCategory.MODERATION;
} }
@@ -61,7 +67,7 @@ public class InviteCommand implements MessageCommand
Button inviteButton = Invite.getInviteButton(); Button inviteButton = Invite.getInviteButton();
// if this is a guild, don't spam the invite in public but DM it // if this is a guild, don't spam the invite in public but DM it
if(event.getChannelType().isGuild()) if (event.getChannelType().isGuild())
{ {
event.getAuthor().openPrivateChannel().queue(privateChannel -> event.getAuthor().openPrivateChannel().queue(privateChannel ->
{ {
@@ -70,7 +76,8 @@ public class InviteCommand implements MessageCommand
.queue(); .queue();
event.getMessage().addReaction(Emoji.fromUnicode("")).queue(); event.getMessage().addReaction(Emoji.fromUnicode("")).queue();
}, error -> event.getMessage().addReaction(Emoji.fromUnicode("")).queue()); }, error -> event.getMessage().addReaction(Emoji.fromUnicode("")).queue());
} else { } else
{
event.getMessage() event.getMessage()
.replyEmbeds(inviteEmbed) .replyEmbeds(inviteEmbed)
.addActionRow(inviteButton) .addActionRow(inviteButton)

View File

@@ -17,36 +17,42 @@ public class KickCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Collections.singletonList("kick")); return new LinkedList<>(Collections.singletonList("kick"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return new ArrayList<Permission>(Collections.singletonList(Permission.KICK_MEMBERS)); return new ArrayList<Permission>(Collections.singletonList(Permission.KICK_MEMBERS));
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.MODERATION; return CommandCategory.MODERATION;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Kick the mentioned user from the guild."; return "Kick the mentioned user from the guild.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "<mentioned user> [reason]"; return "<mentioned user> [reason]";
} }

View File

@@ -29,30 +29,35 @@ public class LoveCalculatorCommand implements MessageCommand
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return null; //anyone can use it return null; //anyone can use it
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Calculate how much two people love each other. You can mention two people or just one."; return "Calculate how much two people love each other. You can mention two people or just one.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "<person 1> [person 2]"; return "<person 1> [person 2]";
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.FUN; return CommandCategory.FUN;
} }
@@ -64,7 +69,7 @@ public class LoveCalculatorCommand implements MessageCommand
List<IMentionable> mentions = mentionsObj.getMentions(); List<IMentionable> mentions = mentionsObj.getMentions();
if(args.length == 0 || mentions.isEmpty()) if (args.length == 0 || mentions.isEmpty())
{ {
event.getMessage() event.getMessage()
.reply("\uD83D\uDE22 I need to know who to check! Please mention them.") .reply("\uD83D\uDE22 I need to know who to check! Please mention them.")
@@ -77,10 +82,11 @@ public class LoveCalculatorCommand implements MessageCommand
String mentionedUserId = mentions.get(0).getId(); String mentionedUserId = mentions.get(0).getId();
user1 = HidekoBot.getAPI().retrieveUserById(mentionedUserId).complete(); user1 = HidekoBot.getAPI().retrieveUserById(mentionedUserId).complete();
if(mentions.size() == 1) if (mentions.size() == 1)
{ {
user2 = event.getAuthor(); user2 = event.getAuthor();
} else { } else
{
mentionedUserId = mentions.get(1).getId(); mentionedUserId = mentions.get(1).getId();
user2 = HidekoBot.getAPI().retrieveUserById(mentionedUserId).complete(); user2 = HidekoBot.getAPI().retrieveUserById(mentionedUserId).complete();
} }

View File

@@ -15,54 +15,60 @@ public class MagicBallCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return MagicBall.getLabels(); return MagicBall.getLabels();
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return null; // anyone can use it return null; // anyone can use it
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Ask a question to the Magic Ball."; return "Ask a question to the Magic Ball.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "<question>"; return "<question>";
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.FUN; return CommandCategory.FUN;
} }
@Override @Override
public void runCommand(MessageReceivedEvent event, String label, String[] args) public void runCommand(MessageReceivedEvent event, String label, String[] args)
{ {
if(args.length == 0) if (args.length == 0)
{ {
event.getMessage().reply("You need to specify a question!").queue(); event.getMessage().reply("You need to specify a question!").queue();
return; return;
} }
StringBuilder questionBuilder = new StringBuilder(); StringBuilder questionBuilder = new StringBuilder();
for(int i = 0; i < args.length; i++) for (int i = 0; i < args.length; i++)
{ {
String arg = args[i]; String arg = args[i];
questionBuilder.append(arg); questionBuilder.append(arg);
if(i + 1 != args.length) // don't add a separator on the last iteration if (i + 1 != args.length) // don't add a separator on the last iteration
questionBuilder.append(" "); questionBuilder.append(" ");
} }

View File

@@ -18,34 +18,42 @@ public class SayCommand implements MessageCommand
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Collections.singletonList("say")); return new LinkedList<>(Collections.singletonList("say"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { return Collections.singletonList(Say.getPermission()); } public List<Permission> getPermissions()
{
return Collections.singletonList(Say.getPermission());
}
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return true; return true;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Make the bot say something for you."; return "Make the bot say something for you.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "<text>"; return "<text>";
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.TOOLS; return CommandCategory.TOOLS;
} }

View File

@@ -17,36 +17,42 @@ public class TimeoutCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Collections.singletonList("timeout")); return new LinkedList<>(Collections.singletonList("timeout"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return new ArrayList<Permission>(Collections.singletonList(Permission.MODERATE_MEMBERS)); return new ArrayList<Permission>(Collections.singletonList(Permission.MODERATE_MEMBERS));
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.MODERATION; return CommandCategory.MODERATION;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Timeout the mentioned user."; return "Timeout the mentioned user.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "<mentioned user> <duration> [reason]"; return "<mentioned user> <duration> [reason]";
} }

View File

@@ -23,36 +23,42 @@ public class TriviaCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return new LinkedList<>(Collections.singletonList("trivia")); return new LinkedList<>(Collections.singletonList("trivia"));
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return null; return null;
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.FUN; return CommandCategory.FUN;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Start a Trivia session and play with others!"; return "Start a Trivia session and play with others!";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return null; return null;
} }
@@ -61,13 +67,13 @@ public class TriviaCommand implements MessageCommand
{ {
MessageChannel channel = event.getChannel(); MessageChannel channel = event.getChannel();
if(!(channel instanceof TextChannel)) if (!(channel instanceof TextChannel))
{ {
channel.sendMessage(Trivia.getNoDMsError()).queue(); channel.sendMessage(Trivia.getNoDMsError()).queue();
return; return;
} }
if(Trivia.channelsRunningTrivia.contains(channel.getId())) if (Trivia.channelsRunningTrivia.contains(channel.getId()))
{ {
// todo: also what if the bot stops (database...?) // todo: also what if the bot stops (database...?)
// todo: also what if the message is already deleted // todo: also what if the message is already deleted
@@ -80,11 +86,12 @@ public class TriviaCommand implements MessageCommand
Message recvMessage = event.getMessage(); Message recvMessage = event.getMessage();
MessageCreateAction responseAction = null; MessageCreateAction responseAction = null;
if(response.content() != null) responseAction = recvMessage.reply(response.content()); if (response.content() != null) responseAction = recvMessage.reply(response.content());
else if(response.embed() != null) responseAction = recvMessage.replyEmbeds(response.embed()); else if (response.embed() != null) responseAction = recvMessage.replyEmbeds(response.embed());
if(responseAction != null) { if (responseAction != null)
if(response.components() != null) responseAction = responseAction.addActionRow(response.components()); {
if (response.components() != null) responseAction = responseAction.addActionRow(response.components());
responseAction.queue(message -> { responseAction.queue(message -> {
Cache.getDatabaseSource().trackRanCommandReply(message, event.getAuthor()); Cache.getDatabaseSource().trackRanCommandReply(message, event.getAuthor());

View File

@@ -21,36 +21,42 @@ public class UrbanDictionaryCommand implements MessageCommand
{ {
@Override @Override
public LinkedList<String> getCommandLabels() { public LinkedList<String> getCommandLabels()
{
return UrbanDictionary.getCommandLabels(); return UrbanDictionary.getCommandLabels();
} }
@Nullable @Nullable
@Override @Override
public List<Permission> getPermissions() { public List<Permission> getPermissions()
{
return null; //anyone can use it return null; //anyone can use it
} }
@Override @Override
public boolean passRawArgs() { public boolean passRawArgs()
{
return false; return false;
} }
@NotNull @NotNull
@Override @Override
public String getDescription() { public String getDescription()
{
return "Look something up in the Urban Dictionary."; return "Look something up in the Urban Dictionary.";
} }
@Nullable @Nullable
@Override @Override
public String getUsage() { public String getUsage()
{
return "<query>"; return "<query>";
} }
@NotNull @NotNull
@Override @Override
public CommandCategory getCategory() { public CommandCategory getCategory()
{
return CommandCategory.FUN; return CommandCategory.FUN;
} }
@@ -58,7 +64,7 @@ public class UrbanDictionaryCommand implements MessageCommand
@Override @Override
public void runCommand(MessageReceivedEvent event, String label, String[] args) public void runCommand(MessageReceivedEvent event, String label, String[] args)
{ {
if(args.length == 0) if (args.length == 0)
{ {
event.getMessage().reply(UrbanDictionary.getNoArgsError()).queue(); event.getMessage().reply(UrbanDictionary.getNoArgsError()).queue();
return; return;
@@ -66,11 +72,12 @@ public class UrbanDictionaryCommand implements MessageCommand
// sanitize args by only keeping letters and numbers, and adding "+" instead of spaces for HTML parsing // sanitize args by only keeping letters and numbers, and adding "+" instead of spaces for HTML parsing
StringBuilder termBuilder = new StringBuilder(); StringBuilder termBuilder = new StringBuilder();
for (int i = 0; i < args.length; i++) { for (int i = 0; i < args.length; i++)
{
String arg = args[i]; String arg = args[i];
termBuilder.append(arg); termBuilder.append(arg);
if(i + 1 != args.length) // add spaces between args, but not on the last run if (i + 1 != args.length) // add spaces between args, but not on the last run
termBuilder.append(" "); termBuilder.append(" ");
} }
@@ -79,9 +86,11 @@ public class UrbanDictionaryCommand implements MessageCommand
Document doc; Document doc;
try { try
{
doc = Jsoup.connect(url).get(); doc = Jsoup.connect(url).get();
} catch (IOException e) { } catch (IOException e)
{
event.getMessage().reply(UrbanDictionary.getTermNotFoundError()).queue(); event.getMessage().reply(UrbanDictionary.getTermNotFoundError()).queue();
return; return;
} }
@@ -92,7 +101,7 @@ public class UrbanDictionaryCommand implements MessageCommand
// disable next page if we only have one result // disable next page if we only have one result
Button nextPageBtnLocal = UrbanDictionary.getNextPageButton(); Button nextPageBtnLocal = UrbanDictionary.getNextPageButton();
if(search.getPages() == 1) nextPageBtnLocal = nextPageBtnLocal.asDisabled(); if (search.getPages() == 1) nextPageBtnLocal = nextPageBtnLocal.asDisabled();
event.getChannel() event.getChannel()
.sendMessageEmbeds(embed) .sendMessageEmbeds(embed)

View File

@@ -14,7 +14,8 @@ import wtf.beatrice.hidekobot.objects.commands.SlashCommandImpl;
public class AvatarCommand extends SlashCommandImpl public class AvatarCommand extends SlashCommandImpl
{ {
@Override @Override
public CommandData getSlashCommandData() { public CommandData getSlashCommandData()
{
return Commands.slash("avatar", "Get someone's profile picture.") return Commands.slash("avatar", "Get someone's profile picture.")
.addOption(OptionType.USER, "user", "User you want to grab the avatar of.") .addOption(OptionType.USER, "user", "User you want to grab the avatar of.")
.addOption(OptionType.INTEGER, "size", "The size of the returned image.", .addOption(OptionType.INTEGER, "size", "The size of the returned image.",
@@ -32,26 +33,28 @@ public class AvatarCommand extends SlashCommandImpl
int resolution; int resolution;
OptionMapping userArg = event.getOption("user"); OptionMapping userArg = event.getOption("user");
if(userArg != null) if (userArg != null)
{ {
user = userArg.getAsUser(); user = userArg.getAsUser();
} else { } else
{
user = event.getUser(); user = event.getUser();
} }
OptionMapping sizeArg = event.getOption("size"); OptionMapping sizeArg = event.getOption("size");
if(sizeArg != null) if (sizeArg != null)
{ {
resolution = ProfileImage.parseResolution(sizeArg.getAsInt()); resolution = ProfileImage.parseResolution(sizeArg.getAsInt());
} else { } else
{
resolution = ProfileImage.parseResolution(512); resolution = ProfileImage.parseResolution(512);
} }
MessageResponse response = ProfileImage.buildResponse(resolution, user, ProfileImage.ImageType.AVATAR); MessageResponse response = ProfileImage.buildResponse(resolution, user, ProfileImage.ImageType.AVATAR);
if(response.content() != null) if (response.content() != null)
{ {
event.getHook().editOriginal(response.content()).queue(); event.getHook().editOriginal(response.content()).queue();
} else if(response.embed() != null) } else if (response.embed() != null)
{ {
event.getHook().editOriginalEmbeds(response.embed()).queue(); event.getHook().editOriginalEmbeds(response.embed()).queue();
} }

View File

@@ -14,7 +14,8 @@ import wtf.beatrice.hidekobot.objects.commands.SlashCommandImpl;
public class BannerCommand extends SlashCommandImpl public class BannerCommand extends SlashCommandImpl
{ {
@Override @Override
public CommandData getSlashCommandData() { public CommandData getSlashCommandData()
{
return Commands.slash("banner", "Get someone's profile banner.") return Commands.slash("banner", "Get someone's profile banner.")
.addOption(OptionType.USER, "user", "User you want to grab the banner of.") .addOption(OptionType.USER, "user", "User you want to grab the banner of.")
.addOption(OptionType.INTEGER, "size", "The size of the returned image.", .addOption(OptionType.INTEGER, "size", "The size of the returned image.",
@@ -32,26 +33,28 @@ public class BannerCommand extends SlashCommandImpl
int resolution; int resolution;
OptionMapping userArg = event.getOption("user"); OptionMapping userArg = event.getOption("user");
if(userArg != null) if (userArg != null)
{ {
user = userArg.getAsUser(); user = userArg.getAsUser();
} else { } else
{
user = event.getUser(); user = event.getUser();
} }
OptionMapping sizeArg = event.getOption("size"); OptionMapping sizeArg = event.getOption("size");
if(sizeArg != null) if (sizeArg != null)
{ {
resolution = ProfileImage.parseResolution(sizeArg.getAsInt()); resolution = ProfileImage.parseResolution(sizeArg.getAsInt());
} else { } else
{
resolution = ProfileImage.parseResolution(512); resolution = ProfileImage.parseResolution(512);
} }
MessageResponse response = ProfileImage.buildResponse(resolution, user, ProfileImage.ImageType.BANNER); MessageResponse response = ProfileImage.buildResponse(resolution, user, ProfileImage.ImageType.BANNER);
if(response.content() != null) if (response.content() != null)
{ {
event.getHook().editOriginal(response.content()).queue(); event.getHook().editOriginal(response.content()).queue();
} else if(response.embed() != null) } else if (response.embed() != null)
{ {
event.getHook().editOriginalEmbeds(response.embed()).queue(); event.getHook().editOriginalEmbeds(response.embed()).queue();
} }

View File

@@ -16,7 +16,8 @@ import java.util.List;
public class BotInfoCommand extends SlashCommandImpl public class BotInfoCommand extends SlashCommandImpl
{ {
@Override @Override
public CommandData getSlashCommandData() { public CommandData getSlashCommandData()
{
return Commands.slash("botinfo", "Get info about the bot."); return Commands.slash("botinfo", "Get info about the bot.");
} }
@@ -29,7 +30,7 @@ public class BotInfoCommand extends SlashCommandImpl
// get a list of slash commands // get a list of slash commands
List<SlashCommand> registeredCommands = Cache.getSlashCommandListener().getRegisteredCommands(); List<SlashCommand> registeredCommands = Cache.getSlashCommandListener().getRegisteredCommands();
LinkedList<String> registeredCommandNames = new LinkedList<>(); LinkedList<String> registeredCommandNames = new LinkedList<>();
for(SlashCommand command : registeredCommands) for (SlashCommand command : registeredCommands)
{ {
// node: adding slash so people realize that this is specific about slash commands. // node: adding slash so people realize that this is specific about slash commands.
registeredCommandNames.add("/" + command.getCommandName()); registeredCommandNames.add("/" + command.getCommandName());

View File

@@ -17,7 +17,8 @@ public class ClearCommand extends SlashCommandImpl
{ {
@Override @Override
public CommandData getSlashCommandData() { public CommandData getSlashCommandData()
{
return Commands.slash(ClearChat.getLabel(), return Commands.slash(ClearChat.getLabel(),
ClearChat.getDescription()) ClearChat.getDescription())
.addOption(OptionType.INTEGER, "amount", "The amount of messages to delete.") .addOption(OptionType.INTEGER, "amount", "The amount of messages to delete.")
@@ -32,7 +33,7 @@ public class ClearCommand extends SlashCommandImpl
// 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)
{ {
event.getHook().editOriginal(error).queue(); event.getHook().editOriginal(error).queue();
return; return;
@@ -45,10 +46,10 @@ public class ClearCommand extends SlashCommandImpl
int toDeleteAmount = amountOption == null ? 1 : amountOption.getAsInt(); int toDeleteAmount = amountOption == null ? 1 : amountOption.getAsInt();
// cap the amount to avoid abuse. // cap the amount to avoid abuse.
if(toDeleteAmount > ClearChat.getMaxAmount()) toDeleteAmount = 0; if (toDeleteAmount > ClearChat.getMaxAmount()) toDeleteAmount = 0;
error = ClearChat.checkDeleteAmount(toDeleteAmount); error = ClearChat.checkDeleteAmount(toDeleteAmount);
if(error != null) if (error != null)
{ {
event.getHook().editOriginal(error).queue(); event.getHook().editOriginal(error).queue();
return; return;

View File

@@ -29,12 +29,11 @@ public class CoinFlipCommand extends SlashCommandImpl
interaction.retrieveOriginal().queue((message) -> interaction.retrieveOriginal().queue((message) ->
{ {
CoinFlip.trackAndRestrict(message, event.getUser()); CoinFlip.trackAndRestrict(message, event.getUser());
}, (error) -> {}); }, (error) -> {
}, (error) -> {}); });
}, (error) -> {
});
} }
} }

View File

@@ -30,7 +30,7 @@ public class DiceRollCommand extends SlashCommandImpl
OptionMapping textOption = event.getOption("query"); OptionMapping textOption = event.getOption("query");
String messageContent = ""; String messageContent = "";
if(textOption != null) if (textOption != null)
{ {
messageContent = textOption.getAsString(); messageContent = textOption.getAsString();
} }
@@ -39,10 +39,10 @@ public class DiceRollCommand extends SlashCommandImpl
MessageResponse response = DiceRoll.buildResponse(event.getUser(), args); MessageResponse response = DiceRoll.buildResponse(event.getUser(), args);
if(response.content() != null) if (response.content() != null)
{ {
event.getHook().editOriginal(response.content()).queue(); event.getHook().editOriginal(response.content()).queue();
} else if(response.embed() != null) } else if (response.embed() != null)
{ {
event.getHook().editOriginalEmbeds(response.embed()).queue(); event.getHook().editOriginalEmbeds(response.embed()).queue();
} }

View File

@@ -16,7 +16,8 @@ import java.util.concurrent.TimeUnit;
public class DieCommand extends SlashCommandImpl public class DieCommand extends SlashCommandImpl
{ {
@Override @Override
public CommandData getSlashCommandData() { public CommandData getSlashCommandData()
{
return Commands.slash("die", "Stop the bot's process.") return Commands.slash("die", "Stop the bot's process.")
.setDefaultPermissions(DefaultMemberPermissions.DISABLED); .setDefaultPermissions(DefaultMemberPermissions.DISABLED);
} }
@@ -24,12 +25,14 @@ public class DieCommand extends SlashCommandImpl
@Override @Override
public void runSlashCommand(@NotNull SlashCommandInteractionEvent event) public void runSlashCommand(@NotNull SlashCommandInteractionEvent event)
{ {
if(Cache.getBotOwnerId() != event.getUser().getIdLong()) if (Cache.getBotOwnerId() != event.getUser().getIdLong())
{ {
event.reply("Sorry, only the bot owner can run this command!").setEphemeral(true).queue(); event.reply("Sorry, only the bot owner can run this command!").setEphemeral(true).queue();
} else { } else
{
event.reply("Going to sleep! Cya ✨").queue(); event.reply("Going to sleep! Cya ✨").queue();
try (ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor()) { try (ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor())
{
executor.schedule(HidekoBot::shutdown, 3, TimeUnit.SECONDS); executor.schedule(HidekoBot::shutdown, 3, TimeUnit.SECONDS);
} }
} }

View File

@@ -30,7 +30,7 @@ public class InviteCommand extends SlashCommandImpl
ReplyCallbackAction replyCallbackAction = event.deferReply(); ReplyCallbackAction replyCallbackAction = event.deferReply();
// only make message permanent in DMs // only make message permanent in DMs
if(event.getChannelType() != ChannelType.PRIVATE) if (event.getChannelType() != ChannelType.PRIVATE)
{ {
replyCallbackAction = replyCallbackAction.setEphemeral(true); replyCallbackAction = replyCallbackAction.setEphemeral(true);
} }

View File

@@ -37,10 +37,11 @@ public class LoveCalculatorCommand extends SlashCommandImpl
User firstUser, secondUser; User firstUser, secondUser;
OptionMapping firsUserArg = event.getOption("first"); OptionMapping firsUserArg = event.getOption("first");
if(firsUserArg != null) if (firsUserArg != null)
{ {
firstUser = firsUserArg.getAsUser(); //todo null check? firstUser = firsUserArg.getAsUser(); //todo null check?
} else { } else
{
event.reply("\uD83D\uDE22 I need to know who to check! Please mention them.") event.reply("\uD83D\uDE22 I need to know who to check! Please mention them.")
.setEphemeral(true) .setEphemeral(true)
.queue(); .queue();
@@ -48,10 +49,11 @@ public class LoveCalculatorCommand extends SlashCommandImpl
} }
OptionMapping secondUserArg = event.getOption("second"); OptionMapping secondUserArg = event.getOption("second");
if(secondUserArg != null) if (secondUserArg != null)
{ {
secondUser = secondUserArg.getAsUser(); //todo null check? secondUser = secondUserArg.getAsUser(); //todo null check?
} else { } else
{
secondUser = event.getUser(); secondUser = event.getUser();
} }

View File

@@ -30,12 +30,12 @@ public class MagicBallCommand extends SlashCommandImpl
// get the asked question // get the asked question
OptionMapping textOption = event.getOption("question"); OptionMapping textOption = event.getOption("question");
String question = ""; String question = "";
if(textOption != null) if (textOption != null)
{ {
question = textOption.getAsString(); question = textOption.getAsString();
} }
if(textOption == null || question.isEmpty()) if (textOption == null || question.isEmpty())
{ {
event.reply("\uD83D\uDE20 Hey, you have to ask me a question!") event.reply("\uD83D\uDE20 Hey, you have to ask me a question!")
.setEphemeral(true) .setEphemeral(true)

View File

@@ -33,12 +33,12 @@ public class SayCommand extends SlashCommandImpl
// get the text to send // get the text to send
OptionMapping textOption = event.getOption("text"); OptionMapping textOption = event.getOption("text");
String messageContent = ""; String messageContent = "";
if(textOption != null) if (textOption != null)
{ {
messageContent = textOption.getAsString(); messageContent = textOption.getAsString();
} }
if(textOption == null || messageContent.isEmpty()) if (textOption == null || messageContent.isEmpty())
{ {
event.reply("\uD83D\uDE20 Hey, you have to tell me what to say!") event.reply("\uD83D\uDE20 Hey, you have to tell me what to say!")
.setEphemeral(true) .setEphemeral(true)

View File

@@ -26,13 +26,13 @@ public class TriviaCommand extends SlashCommandImpl
{ {
MessageChannel channel = event.getChannel(); MessageChannel channel = event.getChannel();
if(!(channel instanceof TextChannel)) if (!(channel instanceof TextChannel))
{ {
event.reply(Trivia.getNoDMsError()).queue(); event.reply(Trivia.getNoDMsError()).queue();
return; return;
} }
if(Trivia.channelsRunningTrivia.contains(channel.getId())) if (Trivia.channelsRunningTrivia.contains(channel.getId()))
{ {
event.reply(Trivia.getTriviaAlreadyRunningError()).setEphemeral(true).queue(); event.reply(Trivia.getTriviaAlreadyRunningError()).setEphemeral(true).queue();
return; return;

View File

@@ -36,12 +36,12 @@ public class UrbanDictionaryCommand extends SlashCommandImpl
// get the term to look up // get the term to look up
OptionMapping textOption = event.getOption("term"); OptionMapping textOption = event.getOption("term");
String term = ""; String term = "";
if(textOption != null) if (textOption != null)
{ {
term = textOption.getAsString(); term = textOption.getAsString();
} }
if(textOption == null || term.isEmpty()) if (textOption == null || term.isEmpty())
{ {
event.reply(UrbanDictionary.getNoArgsError()) event.reply(UrbanDictionary.getNoArgsError())
.setEphemeral(true) .setEphemeral(true)
@@ -54,9 +54,11 @@ public class UrbanDictionaryCommand extends SlashCommandImpl
Document doc; Document doc;
try { try
{
doc = Jsoup.connect(url).get(); doc = Jsoup.connect(url).get();
} catch (IOException e) { } catch (IOException e)
{
event.reply(UrbanDictionary.getTermNotFoundError()) event.reply(UrbanDictionary.getTermNotFoundError())
.setEphemeral(true) .setEphemeral(true)
.queue(); .queue();
@@ -69,7 +71,7 @@ public class UrbanDictionaryCommand extends SlashCommandImpl
// disable next page if we only have one result // disable next page if we only have one result
Button nextPageBtnLocal = UrbanDictionary.getNextPageButton(); Button nextPageBtnLocal = UrbanDictionary.getNextPageButton();
if(search.getPages() == 1) nextPageBtnLocal = nextPageBtnLocal.asDisabled(); if (search.getPages() == 1) nextPageBtnLocal = nextPageBtnLocal.asDisabled();
ActionRow actionRow = ActionRow.of(UrbanDictionary.getPreviousPageButton().asDisabled(), ActionRow actionRow = ActionRow.of(UrbanDictionary.getPreviousPageButton().asDisabled(),
//disabled by default because we're on page 0 //disabled by default because we're on page 0

View File

@@ -14,12 +14,20 @@ public enum ConfigurationEntry
private String path; private String path;
private Object defaultValue; private Object defaultValue;
ConfigurationEntry(String path, Object defaultValue) ConfigurationEntry(String path, Object defaultValue)
{ {
this.path = path; this.path = path;
this.defaultValue = defaultValue; this.defaultValue = defaultValue;
} }
public String getPath() { return path; } public String getPath()
public Object getDefaultValue() { return defaultValue; } {
return path;
}
public Object getDefaultValue()
{
return defaultValue;
}
} }

View File

@@ -32,12 +32,12 @@ public class ConfigurationSource
* we used to have a config.yml file in the "resources" folder, but that is no longer necessary. * we used to have a config.yml file in the "resources" folder, but that is no longer necessary.
*/ */
LinkedHashMap<String, Object> internalConfigContents = new LinkedHashMap<>(); // map holding all file entries LinkedHashMap<String, Object> internalConfigContents = new LinkedHashMap<>(); // map holding all file entries
for(ConfigurationEntry entry : ConfigurationEntry.values()) for (ConfigurationEntry entry : ConfigurationEntry.values())
{ {
internalConfigContents.put(entry.getPath(), entry.getDefaultValue()); internalConfigContents.put(entry.getPath(), entry.getDefaultValue());
} }
if(internalConfigContents.isEmpty()) if (internalConfigContents.isEmpty())
{ {
LOGGER.error("Error reading internal configuration!"); LOGGER.error("Error reading internal configuration!");
HidekoBot.shutdown(); HidekoBot.shutdown();
@@ -46,18 +46,19 @@ public class ConfigurationSource
// check if config files exists in filesystem // check if config files exists in filesystem
File fsConfigFile = new File(configFilePath); File fsConfigFile = new File(configFilePath);
if(!fsConfigFile.exists()) if (!fsConfigFile.exists())
{ {
// try to create config file // try to create config file
try { try
if(!fsConfigFile.createNewFile()) {
if (!fsConfigFile.createNewFile())
{ {
LOGGER.error("We tried creating a file that already exists!"); LOGGER.error("We tried creating a file that already exists!");
HidekoBot.shutdown(); HidekoBot.shutdown();
return; return;
} }
} } catch (IOException e)
catch (IOException e) { {
LOGGER.error("Error creating configuration file!", e); LOGGER.error("Error creating configuration file!", e);
HidekoBot.shutdown(); HidekoBot.shutdown();
return; return;
@@ -68,11 +69,15 @@ public class ConfigurationSource
Yaml fsConfigYaml = new Yaml(new SafeConstructor(options)); Yaml fsConfigYaml = new Yaml(new SafeConstructor(options));
LinkedHashMap<String, Object> fsConfigContents = null; // map holding all file entries LinkedHashMap<String, Object> fsConfigContents = null; // map holding all file entries
try (InputStream fsConfigStream = new FileInputStream(fsConfigFile)) try (InputStream fsConfigStream = new FileInputStream(fsConfigFile))
{ fsConfigContents = fsConfigYaml.load(fsConfigStream); } {
catch (IOException e) { LOGGER.error(e.getMessage()); } fsConfigContents = fsConfigYaml.load(fsConfigStream);
} catch (IOException e)
{
LOGGER.error(e.getMessage());
}
if(fsConfigContents == null) // if file contents are empty or corrupted... if (fsConfigContents == null) // if file contents are empty or corrupted...
{ {
// "clean" them (this effectively forces a config file reset) // "clean" them (this effectively forces a config file reset)
fsConfigContents = new LinkedHashMap<>(); fsConfigContents = new LinkedHashMap<>();
@@ -80,10 +85,10 @@ public class ConfigurationSource
// check for missing keys // check for missing keys
boolean missingKeys = false; boolean missingKeys = false;
for(String key : internalConfigContents.keySet()) for (String key : internalConfigContents.keySet())
{ {
// if key is missing // if key is missing
if(!fsConfigContents.containsKey(key)) if (!fsConfigContents.containsKey(key))
{ {
// quit and flag it, as we need to complete the file with the missing ones // quit and flag it, as we need to complete the file with the missing ones
missingKeys = true; missingKeys = true;
@@ -92,27 +97,29 @@ public class ConfigurationSource
} }
// if keys are missing // if keys are missing
if(missingKeys) if (missingKeys)
{ {
// 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(Map.Entry<String, Object> entry : internalConfigContents.entrySet()) for (Map.Entry<String, Object> entry : internalConfigContents.entrySet())
{ {
String key = entry.getKey(); 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, entry.getValue()); filledEntries.put(key, entry.getValue());
} }
} }
try { try
{
// new writer to actually write the contents to the file // new writer to actually write the contents to the file
PrintWriter missingKeysWriter = new PrintWriter(fsConfigFile); PrintWriter missingKeysWriter = new PrintWriter(fsConfigFile);
@@ -125,7 +132,8 @@ public class ConfigurationSource
// create the yaml object and dump the values to filesystem // create the yaml object and dump the values to filesystem
Yaml yaml = new Yaml(dumperOptions); Yaml yaml = new Yaml(dumperOptions);
yaml.dump(filledEntries, missingKeysWriter); yaml.dump(filledEntries, missingKeysWriter);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e)
{
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
HidekoBot.shutdown(); HidekoBot.shutdown();
return; return;
@@ -133,7 +141,8 @@ public class ConfigurationSource
// finally, dump all entries to cache. // finally, dump all entries to cache.
loadConfig(filledEntries); loadConfig(filledEntries);
} else { } else
{
// if no key is missing, just cache all entries and values from filesystem. // if no key is missing, just cache all entries and values from filesystem.
loadConfig(fsConfigContents); loadConfig(fsConfigContents);
} }
@@ -144,6 +153,7 @@ public class ConfigurationSource
{ {
this.configurationEntries.putAll(configurationEntries); this.configurationEntries.putAll(configurationEntries);
} }
public Object getConfigValue(ConfigurationEntry key) public Object getConfigValue(ConfigurationEntry key)
{ {
return configurationEntries.get(key.getPath()); return configurationEntries.get(key.getPath());

View File

@@ -12,31 +12,37 @@ import java.time.format.DateTimeFormatter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class DatabaseSource { public class DatabaseSource
{
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(DatabaseSource.class); private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(DatabaseSource.class);
private static final String JDBC_URL = "jdbc:sqlite:%path%"; private static final String JDBC_URL = "jdbc:sqlite:%path%";
private Connection dbConnection = null; private Connection dbConnection = null;
private final String dbPath; private final String dbPath;
public DatabaseSource(String dbPath) { public DatabaseSource(String dbPath)
{
this.dbPath = dbPath; this.dbPath = dbPath;
} }
private void logException(SQLException e) { private void logException(SQLException e)
{
LOGGER.error("Database Exception", e); LOGGER.error("Database Exception", e);
} }
public boolean connect() { public boolean connect()
{
String url = JDBC_URL.replace("%path%", dbPath); String url = JDBC_URL.replace("%path%", dbPath);
if (!close()) return false; if (!close()) return false;
try { try
{
dbConnection = DriverManager.getConnection(url); dbConnection = DriverManager.getConnection(url);
LOGGER.info("Database connection established!"); LOGGER.info("Database connection established!");
return true; return true;
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
return false; return false;
} }
@@ -44,13 +50,18 @@ public class DatabaseSource {
} }
public boolean close() { public boolean close()
if (dbConnection != null) { {
try { if (dbConnection != null)
if (!dbConnection.isClosed()) { {
try
{
if (!dbConnection.isClosed())
{
dbConnection.close(); dbConnection.close();
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
return false; return false;
} }
@@ -87,7 +98,8 @@ public class DatabaseSource {
*/ */
//todo: javadocs //todo: javadocs
public boolean initDb() { public boolean initDb()
{
List<String> newTables = new ArrayList<>(); List<String> newTables = new ArrayList<>();
newTables.add(""" newTables.add("""
@@ -119,11 +131,14 @@ public class DatabaseSource {
); );
"""); """);
for (String sql : newTables) { for (String sql : newTables)
try (Statement stmt = dbConnection.createStatement()) { {
try (Statement stmt = dbConnection.createStatement())
{
// execute the statement // execute the statement
stmt.execute(sql); stmt.execute(sql);
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
return false; return false;
} }
@@ -132,14 +147,17 @@ public class DatabaseSource {
return true; return true;
} }
public boolean trackRanCommandReply(Message message, User user) { public boolean trackRanCommandReply(Message message, User user)
{
String userId = user.getId(); String userId = user.getId();
String guildId; String guildId;
ChannelType channelType = message.getChannelType(); ChannelType channelType = message.getChannelType();
if (!(channelType.isGuild())) { if (!(channelType.isGuild()))
{
guildId = userId; guildId = userId;
} else { } else
{
guildId = message.getGuild().getId(); guildId = message.getGuild().getId();
} }
@@ -153,7 +171,8 @@ public class DatabaseSource {
(?, ?, ?, ?, ?); (?, ?, ?, ?, ?);
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, guildId); preparedStatement.setString(1, guildId);
preparedStatement.setString(2, channelId); preparedStatement.setString(2, channelId);
preparedStatement.setString(3, messageId); preparedStatement.setString(3, messageId);
@@ -163,36 +182,42 @@ public class DatabaseSource {
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
return true; return true;
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return false; return false;
} }
public boolean isUserTrackedFor(String userId, String messageId) { public boolean isUserTrackedFor(String userId, String messageId)
{
String trackedUserId = getTrackedReplyUserId(messageId); String trackedUserId = getTrackedReplyUserId(messageId);
if (trackedUserId == null) return false; if (trackedUserId == null) return false;
return userId.equals(trackedUserId); return userId.equals(trackedUserId);
} }
public ChannelType getTrackedMessageChannelType(String messageId) { public ChannelType getTrackedMessageChannelType(String messageId)
{
String query = """ String query = """
SELECT channel_type SELECT channel_type
FROM command_runners FROM command_runners
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.isClosed()) return null; if (resultSet.isClosed()) return null;
while (resultSet.next()) { while (resultSet.next())
{
String channelTypeName = resultSet.getString("channel_type"); String channelTypeName = resultSet.getString("channel_type");
return ChannelType.valueOf(channelTypeName); return ChannelType.valueOf(channelTypeName);
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
@@ -200,37 +225,44 @@ public class DatabaseSource {
} }
public String getTrackedReplyUserId(String messageId) { public String getTrackedReplyUserId(String messageId)
{
String query = """ String query = """
SELECT user_id SELECT user_id
FROM command_runners FROM command_runners
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.isClosed()) return null; if (resultSet.isClosed()) return null;
while (resultSet.next()) { while (resultSet.next())
{
return resultSet.getString("user_id"); return resultSet.getString("user_id");
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return null; return null;
} }
public boolean queueDisabling(Message message) { public boolean queueDisabling(Message message)
{
String messageId = message.getId(); String messageId = message.getId();
String channelId = message.getChannel().getId(); String channelId = message.getChannel().getId();
String guildId; String guildId;
ChannelType channelType = message.getChannelType(); ChannelType channelType = message.getChannelType();
if (!(channelType.isGuild())) { if (!(channelType.isGuild()))
{
guildId = "PRIVATE"; guildId = "PRIVATE";
} else { } else
{
guildId = message.getGuild().getId(); guildId = message.getGuild().getId();
} }
@@ -245,7 +277,8 @@ public class DatabaseSource {
(?, ?, ?, ?); (?, ?, ?, ?);
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, guildId); preparedStatement.setString(1, guildId);
preparedStatement.setString(2, channelId); preparedStatement.setString(2, channelId);
preparedStatement.setString(3, messageId); preparedStatement.setString(3, messageId);
@@ -254,14 +287,16 @@ public class DatabaseSource {
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
return true; return true;
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return false; return false;
} }
public List<String> getQueuedExpiringMessages() { public List<String> getQueuedExpiringMessages()
{
List<String> messages = new ArrayList<>(); List<String> messages = new ArrayList<>();
String query = """ String query = """
@@ -269,44 +304,54 @@ public class DatabaseSource {
FROM pending_disabled_messages; FROM pending_disabled_messages;
"""; """;
try (Statement statement = dbConnection.createStatement()) { try (Statement statement = dbConnection.createStatement())
{
ResultSet resultSet = statement.executeQuery(query); ResultSet resultSet = statement.executeQuery(query);
if (resultSet.isClosed()) return messages; if (resultSet.isClosed()) return messages;
while (resultSet.next()) { while (resultSet.next())
{
messages.add(resultSet.getString("message_id")); messages.add(resultSet.getString("message_id"));
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return messages; return messages;
} }
public boolean untrackExpiredMessage(String messageId) { public boolean untrackExpiredMessage(String messageId)
{
String query = "DELETE FROM pending_disabled_messages WHERE message_id = ?;"; String query = "DELETE FROM pending_disabled_messages WHERE message_id = ?;";
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
preparedStatement.execute(); preparedStatement.execute();
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
return false; return false;
} }
query = "DELETE FROM command_runners WHERE message_id = ?;"; query = "DELETE FROM command_runners WHERE message_id = ?;";
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
preparedStatement.execute(); preparedStatement.execute();
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
return false; return false;
} }
query = "DELETE FROM urban_dictionary WHERE message_id = ?;"; query = "DELETE FROM urban_dictionary WHERE message_id = ?;";
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
preparedStatement.execute(); preparedStatement.execute();
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
return false; return false;
} }
@@ -314,66 +359,78 @@ public class DatabaseSource {
return true; return true;
} }
public String getQueuedExpiringMessageExpiryDate(String messageId) { public String getQueuedExpiringMessageExpiryDate(String messageId)
{
String query = """ String query = """
SELECT expiry_timestamp SELECT expiry_timestamp
FROM pending_disabled_messages FROM pending_disabled_messages
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.isClosed()) return null; if (resultSet.isClosed()) return null;
while (resultSet.next()) { while (resultSet.next())
{
return resultSet.getString("expiry_timestamp"); return resultSet.getString("expiry_timestamp");
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return null; return null;
} }
public String getQueuedExpiringMessageChannel(String messageId) { public String getQueuedExpiringMessageChannel(String messageId)
{
String query = """ String query = """
SELECT channel_id SELECT channel_id
FROM pending_disabled_messages FROM pending_disabled_messages
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.isClosed()) return null; if (resultSet.isClosed()) return null;
while (resultSet.next()) { while (resultSet.next())
{
return resultSet.getString("channel_id"); return resultSet.getString("channel_id");
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return null; return null;
} }
public String getQueuedExpiringMessageGuild(String messageId) { public String getQueuedExpiringMessageGuild(String messageId)
{
String query = """ String query = """
SELECT guild_id SELECT guild_id
FROM pending_disabled_messages FROM pending_disabled_messages
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.isClosed()) return null; if (resultSet.isClosed()) return null;
while (resultSet.next()) { while (resultSet.next())
{
return resultSet.getString("guild_id"); return resultSet.getString("guild_id");
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
@@ -382,7 +439,8 @@ public class DatabaseSource {
public boolean trackUrban(String meanings, String examples, public boolean trackUrban(String meanings, String examples,
String contributors, String dates, String contributors, String dates,
Message message, String term) { Message message, String term)
{
String query = """ String query = """
INSERT INTO urban_dictionary INSERT INTO urban_dictionary
@@ -390,7 +448,8 @@ public class DatabaseSource {
(?, ?, ?, ?, ?, ?, ?); (?, ?, ?, ?, ?, ?, ?);
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, message.getId()); preparedStatement.setString(1, message.getId());
preparedStatement.setInt(2, 0); preparedStatement.setInt(2, 0);
preparedStatement.setString(3, meanings); preparedStatement.setString(3, meanings);
@@ -402,167 +461,196 @@ public class DatabaseSource {
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
return true; return true;
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return false; return false;
} }
public int getUrbanPage(String messageId) { public int getUrbanPage(String messageId)
{
String query = """ String query = """
SELECT page SELECT page
FROM urban_dictionary FROM urban_dictionary
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.isClosed()) return 0; if (resultSet.isClosed()) return 0;
while (resultSet.next()) { while (resultSet.next())
{
return resultSet.getInt("page"); return resultSet.getInt("page");
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return 0; return 0;
} }
public String getUrbanMeanings(String messageId) { public String getUrbanMeanings(String messageId)
{
String query = """ String query = """
SELECT meanings SELECT meanings
FROM urban_dictionary FROM urban_dictionary
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.isClosed()) return null; if (resultSet.isClosed()) return null;
while (resultSet.next()) { while (resultSet.next())
{
return resultSet.getString("meanings"); return resultSet.getString("meanings");
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return null; return null;
} }
public String getUrbanExamples(String messageId) { public String getUrbanExamples(String messageId)
{
String query = """ String query = """
SELECT examples SELECT examples
FROM urban_dictionary FROM urban_dictionary
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.isClosed()) return null; if (resultSet.isClosed()) return null;
while (resultSet.next()) { while (resultSet.next())
{
return resultSet.getString("examples"); return resultSet.getString("examples");
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return null; return null;
} }
public String getUrbanContributors(String messageId) { public String getUrbanContributors(String messageId)
{
String query = """ String query = """
SELECT contributors SELECT contributors
FROM urban_dictionary FROM urban_dictionary
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.isClosed()) return null; if (resultSet.isClosed()) return null;
while (resultSet.next()) { while (resultSet.next())
{
return resultSet.getString("contributors"); return resultSet.getString("contributors");
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return null; return null;
} }
public String getUrbanDates(String messageId) { public String getUrbanDates(String messageId)
{
String query = """ String query = """
SELECT dates SELECT dates
FROM urban_dictionary FROM urban_dictionary
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.isClosed()) return null; if (resultSet.isClosed()) return null;
while (resultSet.next()) { while (resultSet.next())
{
return resultSet.getString("dates"); return resultSet.getString("dates");
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return null; return null;
} }
public String getUrbanTerm(String messageId) { public String getUrbanTerm(String messageId)
{
String query = """ String query = """
SELECT term SELECT term
FROM urban_dictionary FROM urban_dictionary
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, messageId); preparedStatement.setString(1, messageId);
ResultSet resultSet = preparedStatement.executeQuery(); ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.isClosed()) return null; if (resultSet.isClosed()) return null;
while (resultSet.next()) { while (resultSet.next())
{
return resultSet.getString("term"); return resultSet.getString("term");
} }
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return null; return null;
} }
public boolean setUrbanPage(String messageId, int page) { public boolean setUrbanPage(String messageId, int page)
{
String query = """ String query = """
UPDATE urban_dictionary UPDATE urban_dictionary
SET page = ? SET page = ?
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setInt(1, page); preparedStatement.setInt(1, page);
preparedStatement.setString(2, messageId); preparedStatement.setString(2, messageId);
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
return true; return true;
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }
return false; return false;
} }
public boolean resetExpiryTimestamp(String messageId) { public boolean resetExpiryTimestamp(String messageId)
{
LocalDateTime expiryTime = LocalDateTime.now().plusSeconds(Cache.getExpiryTimeSeconds()); LocalDateTime expiryTime = LocalDateTime.now().plusSeconds(Cache.getExpiryTimeSeconds());
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(Cache.getExpiryTimestampFormat()); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(Cache.getExpiryTimestampFormat());
@@ -574,14 +662,16 @@ public class DatabaseSource {
WHERE message_id = ?; WHERE message_id = ?;
"""; """;
try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { try (PreparedStatement preparedStatement = dbConnection.prepareStatement(query))
{
preparedStatement.setString(1, expiryTimeFormatted); preparedStatement.setString(1, expiryTimeFormatted);
preparedStatement.setString(2, messageId); preparedStatement.setString(2, messageId);
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
return true; return true;
} catch (SQLException e) { } catch (SQLException e)
{
logException(e); logException(e);
} }

View File

@@ -25,8 +25,8 @@ public class PropertiesSource
{ {
properties.load(internalPropertiesStream); properties.load(internalPropertiesStream);
} } catch (IOException e)
catch (IOException e) { {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
HidekoBot.shutdown(); HidekoBot.shutdown();
return; return;
@@ -34,5 +34,7 @@ public class PropertiesSource
} }
public String getProperty(String property) public String getProperty(String property)
{ return properties == null ? "" : properties.getProperty(property); } {
return properties == null ? "" : properties.getProperty(property);
}
} }

View File

@@ -18,7 +18,8 @@ public class ButtonInteractionListener extends ListenerAdapter
public void onButtonInteraction(ButtonInteractionEvent event) public void onButtonInteraction(ButtonInteractionEvent event)
{ {
switch (event.getComponentId().toLowerCase()) { switch (event.getComponentId().toLowerCase())
{
// coinflip // coinflip
case "coinflip_reflip" -> CoinFlip.buttonReFlip(event); case "coinflip_reflip" -> CoinFlip.buttonReFlip(event);

View File

@@ -38,14 +38,16 @@ public class MessageCommandListener extends ListenerAdapter
public MessageCommand getRegisteredCommand(String label) public MessageCommand getRegisteredCommand(String label)
{ {
for(Map.Entry<LinkedList<String>, MessageCommand> entry : registeredCommands.entrySet()) for (Map.Entry<LinkedList<String>, MessageCommand> entry : registeredCommands.entrySet())
{ {
LinkedList<String> aliases = entry.getKey(); LinkedList<String> aliases = entry.getKey();
for(String currentAlias : aliases) for (String currentAlias : aliases)
{ {
if(label.equals(currentAlias)) if (label.equals(currentAlias))
{ return entry.getValue(); } {
return entry.getValue();
}
} }
} }
@@ -53,19 +55,21 @@ public class MessageCommandListener extends ListenerAdapter
} }
public LinkedList<MessageCommand> getRegisteredCommands() public LinkedList<MessageCommand> getRegisteredCommands()
{ return new LinkedList<>(registeredCommands.values()); } {
return new LinkedList<>(registeredCommands.values());
}
@Override @Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) public void onMessageReceived(@NotNull MessageReceivedEvent event)
{ {
// check if a bot is sending this message, and ignore it // check if a bot is sending this message, and ignore it
if(event.getAuthor().isBot()) return; if (event.getAuthor().isBot()) return;
// warning: we are getting the RAW value of the message content, not the DISPLAY value! // warning: we are getting the RAW value of the message content, not the DISPLAY value!
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)" + COMMAND_REGEX + ".*")) if (!eventMessage.toLowerCase().matches("(?s)" + COMMAND_REGEX + ".*"))
return; return;
// generate args from the string // generate args from the string
@@ -77,7 +81,7 @@ public class MessageCommandListener extends ListenerAdapter
// and that element is the whole string passed as a single argument, which would be empty in this case // and that element is the whole string passed as a single argument, which would be empty in this case
// (or contain text in other cases like "string split ," if the passed text doesn't contain any comma -> // (or contain text in other cases like "string split ," if the passed text doesn't contain any comma ->
// it will be the whole text as a single element. // it will be the whole text as a single element.
if(argsString.isEmpty()) if (argsString.isEmpty())
{ {
event.getMessage() event.getMessage()
.reply("Hello there! ✨ Type `" + Cache.getBotPrefix() + " help` to get started!") .reply("Hello there! ✨ Type `" + Cache.getBotPrefix() + " help` to get started!")
@@ -92,7 +96,7 @@ public class MessageCommandListener extends ListenerAdapter
String commandLabel = argsRaw[0]; String commandLabel = argsRaw[0];
MessageCommand commandObject = getRegisteredCommand(commandLabel); MessageCommand commandObject = getRegisteredCommand(commandLabel);
if(commandObject == null) if (commandObject == null)
{ {
/* temporarily disabled because when people talk about the bot, it replies with this spammy message. /* temporarily disabled because when people talk about the bot, it replies with this spammy message.
@@ -107,13 +111,13 @@ public class MessageCommandListener extends ListenerAdapter
// permissions check // permissions check
List<Permission> requiredPermissions = commandObject.getPermissions(); List<Permission> requiredPermissions = commandObject.getPermissions();
if(requiredPermissions != null && !requiredPermissions.isEmpty()) if (requiredPermissions != null && !requiredPermissions.isEmpty())
{ {
if(channelType.isGuild()) //todo: what about forum post if (channelType.isGuild()) //todo: what about forum post
{ {
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 && !member.hasPermission(channel, requiredPermissions)) if (member != null && !member.hasPermission(channel, requiredPermissions))
{ {
event.getMessage() event.getMessage()
.reply("You do not have permissions to run this command!") .reply("You do not have permissions to run this command!")
@@ -126,15 +130,14 @@ public class MessageCommandListener extends ListenerAdapter
} }
String[] commandArgs; String[] commandArgs;
if(commandObject.passRawArgs()) if (commandObject.passRawArgs())
{ {
// remove first argument, which is the command label // remove first argument, which is the command label
argsString = argsString.replaceAll("^[\\S]+\\s*", ""); argsString = argsString.replaceAll("^[\\S]+\\s*", "");
// pass all other arguments as a single argument as the first array element // pass all other arguments as a single argument as the first array element
commandArgs = new String[]{argsString}; commandArgs = new String[]{argsString};
} } else
else
{ {
// copy all split arguments to the array, except from the command label // copy all split arguments to the array, except from the command label
commandArgs = Arrays.copyOfRange(argsRaw, 1, argsRaw.length); commandArgs = Arrays.copyOfRange(argsRaw, 1, argsRaw.length);

View File

@@ -25,7 +25,7 @@ public class MessageLogger extends ListenerAdapter
String userName = event.getAuthor().getAsTag(); String userName = event.getAuthor().getAsTag();
String message = event.getMessage().getContentDisplay(); String message = event.getMessage().getContentDisplay();
if(event.getChannel() instanceof TextChannel channel) if (event.getChannel() instanceof TextChannel channel)
{ {
String guildName = channel.getGuild().getName(); String guildName = channel.getGuild().getName();
String channelName = event.getChannel().getName(); String channelName = event.getChannel().getName();
@@ -33,8 +33,7 @@ public class MessageLogger extends ListenerAdapter
toLog = GUILD_MESSAGE_LOG_FORMAT toLog = GUILD_MESSAGE_LOG_FORMAT
.replace("%guild%", guildName) .replace("%guild%", guildName)
.replace("%channel%", channelName); .replace("%channel%", channelName);
} } else if (event.getChannel() instanceof PrivateChannel)
else if(event.getChannel() instanceof PrivateChannel)
{ {
toLog = DIRECT_MESSAGE_LOG_FORMAT; toLog = DIRECT_MESSAGE_LOG_FORMAT;
} }
@@ -45,9 +44,9 @@ public class MessageLogger extends ListenerAdapter
LOGGER.info(toLog); LOGGER.info(toLog);
if(!event.getMessage().getAttachments().isEmpty()) if (!event.getMessage().getAttachments().isEmpty())
{ {
for(Message.Attachment atch : event.getMessage().getAttachments()) for (Message.Attachment atch : event.getMessage().getAttachments())
{ {
LOGGER.info(atch.getUrl()); LOGGER.info(atch.getUrl());
} }

View File

@@ -14,7 +14,8 @@ public class SelectMenuInteractionListener extends ListenerAdapter
@Override @Override
public void onStringSelectInteraction(StringSelectInteractionEvent event) public void onStringSelectInteraction(StringSelectInteractionEvent event)
{ {
switch (event.getComponentId().toLowerCase()) { switch (event.getComponentId().toLowerCase())
{
// trivia // trivia
case "trivia_categories" -> Trivia.handleMenuSelection(event); case "trivia_categories" -> Trivia.handleMenuSelection(event);

View File

@@ -21,16 +21,21 @@ public class SlashCommandCompletionListener extends ListenerAdapter
} }
public SlashArgumentsCompleter getRegisteredCompleter(String label) public SlashArgumentsCompleter getRegisteredCompleter(String label)
{ return registeredCompleters.get(label); } {
return registeredCompleters.get(label);
}
public LinkedList<SlashArgumentsCompleter> getRegisteredCompleters() public LinkedList<SlashArgumentsCompleter> getRegisteredCompleters()
{ return new LinkedList<>(registeredCompleters.values()); } {
return new LinkedList<>(registeredCompleters.values());
}
@Override @Override
public void onCommandAutoCompleteInteraction(CommandAutoCompleteInteractionEvent event) public void onCommandAutoCompleteInteraction(CommandAutoCompleteInteractionEvent event)
{ {
String commandName = event.getName().toLowerCase(); String commandName = event.getName().toLowerCase();
SlashArgumentsCompleter completer = registeredCompleters.get(commandName); SlashArgumentsCompleter completer = registeredCompleters.get(commandName);
if(completer == null) return; if (completer == null) return;
// not running in a thread because nothing heavy should be done here... // not running in a thread because nothing heavy should be done here...
completer.runCompletion(event); completer.runCompletion(event);

View File

@@ -21,17 +21,21 @@ public class SlashCommandListener extends ListenerAdapter
} }
public SlashCommand getRegisteredCommand(String label) public SlashCommand getRegisteredCommand(String label)
{ return registeredCommands.get(label); } {
return registeredCommands.get(label);
}
public LinkedList<SlashCommand> getRegisteredCommands() public LinkedList<SlashCommand> getRegisteredCommands()
{ return new LinkedList<>(registeredCommands.values()); } {
return new LinkedList<>(registeredCommands.values());
}
@Override @Override
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event)
{ {
String commandName = event.getName().toLowerCase(); String commandName = event.getName().toLowerCase();
SlashCommand command = registeredCommands.get(commandName); SlashCommand command = registeredCommands.get(commandName);
if(command == null) return; if (command == null) return;
// finally run the command, in a new thread to avoid locking the main one. // finally run the command, in a new thread to avoid locking the main one.

View File

@@ -9,10 +9,12 @@ import java.util.Objects;
public record MessageResponse(@Nullable String content, public record MessageResponse(@Nullable String content,
@Nullable MessageEmbed embed, @Nullable MessageEmbed embed,
@Nullable ItemComponent... components) { @Nullable ItemComponent... components)
{
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o)
{
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
MessageResponse response = (MessageResponse) o; MessageResponse response = (MessageResponse) o;
@@ -22,14 +24,16 @@ public record MessageResponse(@Nullable String content,
} }
@Override @Override
public int hashCode() { public int hashCode()
{
int result = Objects.hash(content, embed); int result = Objects.hash(content, embed);
result = 31 * result + Arrays.hashCode(components); result = 31 * result + Arrays.hashCode(components);
return result; return result;
} }
@Override @Override
public String toString() { public String toString()
{
return "MessageResponse{" + return "MessageResponse{" +
"content=" + content + "content=" + content +
", embed=" + embed + ", embed=" + embed +

View File

@@ -9,10 +9,14 @@ public enum CommandCategory
; ;
private String emoji; private String emoji;
CommandCategory(String emoji) CommandCategory(String emoji)
{ {
this.emoji = emoji; this.emoji = emoji;
} }
public String getEmoji() { return emoji; } public String getEmoji()
{
return emoji;
}
} }

View File

@@ -70,9 +70,7 @@ public interface MessageCommand
* *
* @param event the received message event. It should not be used for parsing message contents data as * @param event the received message event. It should not be used for parsing message contents data as
* the arguments already account for it in a better way. * the arguments already account for it in a better way.
*
* @param label the command label that was used, taken from all available command aliases. * @param label the command label that was used, taken from all available command aliases.
*
* @param args a pre-formatted list of arguments, excluding the bot prefix and the command name. * @param args a pre-formatted list of arguments, excluding the bot prefix and the command name.
* This is useful because command logic won't have to change in case the bot prefix is changed, * This is useful because command logic won't have to change in case the bot prefix is changed,
* removed, or we switch to another method of triggering commands (ping, trigger words, ...). * removed, or we switch to another method of triggering commands (ping, trigger words, ...).

View File

@@ -12,6 +12,7 @@ public interface SlashArgumentsCompleter
* @return the command object. * @return the command object.
*/ */
SlashCommand getCommand(); SlashCommand getCommand();
/** /**
* Run the argument-completion logic by parsing the event and replying accordingly. * Run the argument-completion logic by parsing the event and replying accordingly.
* *

View File

@@ -6,13 +6,16 @@ import org.jetbrains.annotations.NotNull;
public class SlashArgumentsCompleterImpl implements SlashArgumentsCompleter public class SlashArgumentsCompleterImpl implements SlashArgumentsCompleter
{ {
private final SlashCommand parentCommand; private final SlashCommand parentCommand;
public SlashArgumentsCompleterImpl(SlashCommand parentCommand) public SlashArgumentsCompleterImpl(SlashCommand parentCommand)
{ {
this.parentCommand = parentCommand; this.parentCommand = parentCommand;
} }
public SlashCommand getCommand() public SlashCommand getCommand()
{ return parentCommand; } {
return parentCommand;
}
public void runCompletion(@NotNull CommandAutoCompleteInteractionEvent event) public void runCompletion(@NotNull CommandAutoCompleteInteractionEvent event)
{ {

View File

@@ -21,6 +21,7 @@ public interface SlashCommand
* @return the command data object. * @return the command data object.
*/ */
CommandData getSlashCommandData(); CommandData getSlashCommandData();
/** /**
* Run the command logic by parsing the event and replying accordingly. * Run the command logic by parsing the event and replying accordingly.
* *

View File

@@ -8,17 +8,20 @@ public class SlashCommandImpl implements SlashCommand
{ {
@Override @Override
public String getCommandName() { public String getCommandName()
{
return getSlashCommandData().getName(); return getSlashCommandData().getName();
} }
@Override @Override
public CommandData getSlashCommandData() { public CommandData getSlashCommandData()
{
return null; return null;
} }
@Override @Override
public void runSlashCommand(@NotNull SlashCommandInteractionEvent event) { public void runSlashCommand(@NotNull SlashCommandInteractionEvent event)
{
event.reply("Base command implementation").queue(); event.reply("Base command implementation").queue();
} }
} }

View File

@@ -6,13 +6,15 @@ import java.util.LinkedList;
/** /**
* This class gets two linked lists, and compares their first value alphabetically. * This class gets two linked lists, and compares their first value alphabetically.
*/ */
public class MessageCommandAliasesComparator implements Comparator<LinkedList<String>> { public class MessageCommandAliasesComparator implements Comparator<LinkedList<String>>
{
@Override @Override
public int compare(LinkedList<String> linkedList, LinkedList<String> t1) { public int compare(LinkedList<String> linkedList, LinkedList<String> t1)
{
if(linkedList.isEmpty()) return 0; if (linkedList.isEmpty()) return 0;
if(t1.isEmpty()) return 0; if (t1.isEmpty()) return 0;
return linkedList.get(0).compareTo(t1.get(0)); return linkedList.get(0).compareTo(t1.get(0));
} }

View File

@@ -7,10 +7,12 @@ import java.util.Comparator;
/** /**
* This class gets two trivia categories, and compares them by their name. * This class gets two trivia categories, and compares them by their name.
*/ */
public class TriviaCategoryComparator implements Comparator<TriviaCategory> { public class TriviaCategoryComparator implements Comparator<TriviaCategory>
{
@Override @Override
public int compare(TriviaCategory o1, TriviaCategory o2) { public int compare(TriviaCategory o1, TriviaCategory o2)
{
return CharSequence.compare(o1.categoryName(), o2.categoryName()); return CharSequence.compare(o1.categoryName(), o2.categoryName());
} }
} }

View File

@@ -7,10 +7,12 @@ import java.util.Comparator;
/** /**
* This class gets two trivia scores, and compares their score. * This class gets two trivia scores, and compares their score.
*/ */
public class TriviaScoreComparator implements Comparator<TriviaScore> { public class TriviaScoreComparator implements Comparator<TriviaScore>
{
@Override @Override
public int compare(TriviaScore o1, TriviaScore o2) { public int compare(TriviaScore o1, TriviaScore o2)
{
return Integer.compare(o2.getScore(), o1.getScore()); // inverted, because higher number should come first return Integer.compare(o2.getScore(), o1.getScore()); // inverted, because higher number should come first
} }
} }

View File

@@ -1,5 +1,6 @@
package wtf.beatrice.hidekobot.objects.fun; package wtf.beatrice.hidekobot.objects.fun;
public record TriviaCategory(String categoryName, int categoryId) { public record TriviaCategory(String categoryName, int categoryId)
{
} }

View File

@@ -3,6 +3,7 @@ package wtf.beatrice.hidekobot.objects.fun;
import java.util.List; import java.util.List;
public record TriviaQuestion(String question, String correctAnswer, public record TriviaQuestion(String question, String correctAnswer,
List<String> wrongAnswers) { List<String> wrongAnswers)
{
} }

View File

@@ -18,9 +18,15 @@ public class TriviaScore
score += add; score += add;
} }
public int getScore() { return score; } public int getScore()
{
return score;
}
public User getUser() { return user; } public User getUser()
{
return user;
}
@Override @Override
public String toString() public String toString()

View File

@@ -10,7 +10,8 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.List; import java.util.List;
public class ExpiredMessageTask implements Runnable { public class ExpiredMessageTask implements Runnable
{
private final DateTimeFormatter formatter; private final DateTimeFormatter formatter;
private static final Logger LOGGER = LoggerFactory.getLogger(ExpiredMessageTask.class); private static final Logger LOGGER = LoggerFactory.getLogger(ExpiredMessageTask.class);
@@ -26,23 +27,24 @@ public class ExpiredMessageTask implements Runnable {
@Override @Override
public void run() { public void run()
{
databaseSource = Cache.getDatabaseSource(); databaseSource = Cache.getDatabaseSource();
if(databaseSource == null) return; if (databaseSource == null) return;
List<String> expiringMessages = Cache.getDatabaseSource().getQueuedExpiringMessages(); List<String> expiringMessages = Cache.getDatabaseSource().getQueuedExpiringMessages();
if(expiringMessages == null || expiringMessages.isEmpty()) return; if (expiringMessages == null || expiringMessages.isEmpty()) return;
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
for(String messageId : expiringMessages) for (String messageId : expiringMessages)
{ {
if(Cache.isVerbose()) LOGGER.info("expired check: {}", messageId); if (Cache.isVerbose()) LOGGER.info("expired check: {}", messageId);
String expiryTimestamp = databaseSource.getQueuedExpiringMessageExpiryDate(messageId); String expiryTimestamp = databaseSource.getQueuedExpiringMessageExpiryDate(messageId);
if(expiryTimestamp == null || expiryTimestamp.isEmpty()) // if missing timestamp if (expiryTimestamp == null || expiryTimestamp.isEmpty()) // if missing timestamp
{ {
// count it as already expired // count it as already expired
databaseSource.untrackExpiredMessage(messageId); databaseSource.untrackExpiredMessage(messageId);
@@ -52,9 +54,9 @@ public class ExpiredMessageTask implements Runnable {
LocalDateTime expiryDate = LocalDateTime.parse(expiryTimestamp, formatter); LocalDateTime expiryDate = LocalDateTime.parse(expiryTimestamp, formatter);
if(now.isAfter(expiryDate)) if (now.isAfter(expiryDate))
{ {
if(Cache.isVerbose()) LOGGER.info("expired: {}", messageId); if (Cache.isVerbose()) LOGGER.info("expired: {}", messageId);
CommandUtil.disableExpired(messageId); CommandUtil.disableExpired(messageId);
} }
} }

View File

@@ -16,9 +16,10 @@ public class HeartBeatTask implements Runnable
public void run() public void run()
{ {
String urlString = Cache.getFullHeartBeatLink(); String urlString = Cache.getFullHeartBeatLink();
if(urlString == null || urlString.isEmpty()) return; if (urlString == null || urlString.isEmpty()) return;
try { try
{
URL heartbeatUrl = new URL(urlString); URL heartbeatUrl = new URL(urlString);
@@ -28,17 +29,17 @@ public class HeartBeatTask implements Runnable
connection.setReadTimeout(5000); connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode(); int responseCode = connection.getResponseCode();
if(200 <= responseCode && responseCode < 300) if (200 <= responseCode && responseCode < 300)
{ {
// only log ok response codes when verbosity is enabled // only log ok response codes when verbosity is enabled
if(Cache.isVerbose()) LOGGER.info("Heartbeat response code: {}", responseCode); if (Cache.isVerbose()) LOGGER.info("Heartbeat response code: {}", responseCode);
} } else
else
{ {
LOGGER.error("Heartbeat returned problematic response code: {}", responseCode); LOGGER.error("Heartbeat returned problematic response code: {}", responseCode);
} }
} catch (IOException e) { } catch (IOException e)
{
LOGGER.error("Error while trying to push heartbeat", e); LOGGER.error("Error while trying to push heartbeat", e);
} }

View File

@@ -20,11 +20,11 @@ public class RandomOrgSeedTask implements Runnable
@Override @Override
public void run() public void run()
{ {
if(RandomUtil.isRandomOrgKeyValid()) if (RandomUtil.isRandomOrgKeyValid())
{ {
if(Cache.isVerbose()) LOGGER.info("Updating Random seed from random.org..."); if (Cache.isVerbose()) LOGGER.info("Updating Random seed from random.org...");
RandomUtil.initRandomOrg(); RandomUtil.initRandomOrg();
if(Cache.isVerbose()) LOGGER.info("Random.org seed updated!"); if (Cache.isVerbose()) LOGGER.info("Random.org seed updated!");
} }
} }
} }

View File

@@ -22,7 +22,8 @@ public class StatusUpdateTask implements Runnable
); );
@Override @Override
public void run() { public void run()
{
int randomPos = RandomUtil.getRandomNumber(0, statuses.size() - 1); int randomPos = RandomUtil.getRandomNumber(0, statuses.size() - 1);
String status = statuses.get(randomPos) + " | " + Cache.getBotPrefix() + " help"; String status = statuses.get(randomPos) + " | " + Cache.getBotPrefix() + " help";
HidekoBot.getAPI().getPresence().setActivity(Activity.playing(status)); HidekoBot.getAPI().getPresence().setActivity(Activity.playing(status));

View File

@@ -52,12 +52,12 @@ public class TriviaTask implements Runnable
public void run() public void run()
{ {
if(previousMessage != null) if (previousMessage != null)
{ {
// todo: we shouldn't use this method, since it messes with the database... look at coin reflip // todo: we shouldn't use this method, since it messes with the database... look at coin reflip
CommandUtil.disableExpired(previousMessage.getId()); CommandUtil.disableExpired(previousMessage.getId());
String previousCorrectAnswer = questions.get(iteration-1).correctAnswer(); String previousCorrectAnswer = questions.get(iteration - 1).correctAnswer();
// we need this to be thread-locking to avoid getting out of sync with the rest of the trivia features // we need this to be thread-locking to avoid getting out of sync with the rest of the trivia features
previousMessage.reply("The correct answer was: **" + previousCorrectAnswer + "**!").complete(); previousMessage.reply("The correct answer was: **" + previousCorrectAnswer + "**!").complete();
@@ -67,7 +67,7 @@ public class TriviaTask implements Runnable
Trivia.channelAndWhoResponded.put(previousMessage.getChannel().getId(), new ArrayList<>()); Trivia.channelAndWhoResponded.put(previousMessage.getChannel().getId(), new ArrayList<>());
} }
if(iteration >= questions.size()) if (iteration >= questions.size())
{ {
String scoreboardText = "\uD83D\uDC23 Trivia session is over!"; String scoreboardText = "\uD83D\uDC23 Trivia session is over!";
@@ -77,28 +77,30 @@ public class TriviaTask implements Runnable
StringBuilder othersBuilder = new StringBuilder(); StringBuilder othersBuilder = new StringBuilder();
LinkedList<TriviaScore> triviaScores = Trivia.channelAndScores.get(channel.getId()); LinkedList<TriviaScore> triviaScores = Trivia.channelAndScores.get(channel.getId());
if(triviaScores == null) triviaScores = new LinkedList<>(); if (triviaScores == null) triviaScores = new LinkedList<>();
else triviaScores.sort(new TriviaScoreComparator()); else triviaScores.sort(new TriviaScoreComparator());
int pos = 0; int pos = 0;
Integer previousScore = null; Integer previousScore = null;
for(TriviaScore triviaScore : triviaScores) for (TriviaScore triviaScore : triviaScores)
{ {
if(pos > 10) break; // cap at top 10 if (pos > 10) break; // cap at top 10
String user = triviaScore.getUser().getAsMention(); String user = triviaScore.getUser().getAsMention();
int score = triviaScore.getScore(); int score = triviaScore.getScore();
if(previousScore == null) if (previousScore == null)
{ {
previousScore = score; previousScore = score;
topScore = score; topScore = score;
pos = 1; pos = 1;
} else { } else
if(score != previousScore) pos++; {
if (score != previousScore) pos++;
} }
if(pos == 1) winners.add(user); if (pos == 1) winners.add(user);
else { else
{
othersBuilder.append("\n").append(pos) othersBuilder.append("\n").append(pos)
.append(" | ").append(user) .append(" | ").append(user)
.append(": ").append(score).append(" points"); .append(": ").append(score).append(" points");
@@ -106,14 +108,15 @@ public class TriviaTask implements Runnable
} }
StringBuilder winnersBuilder = new StringBuilder(); StringBuilder winnersBuilder = new StringBuilder();
for(int i = 0; i < winners.size(); i++) for (int i = 0; i < winners.size(); i++)
{ {
String winner = winners.get(i); String winner = winners.get(i);
winnersBuilder.append(winner); winnersBuilder.append(winner);
if(i + 1 != winners.size()) if (i + 1 != winners.size())
{ {
winnersBuilder.append(", "); // separate with comma except on last run winnersBuilder.append(", "); // separate with comma except on last run
} else { } else
{
winnersBuilder.append(": ").append(topScore).append(" points \uD83C\uDF89"); winnersBuilder.append(": ").append(topScore).append(" points \uD83C\uDF89");
} }
} }
@@ -127,10 +130,10 @@ public class TriviaTask implements Runnable
EmbedBuilder scoreboardBuilder = new EmbedBuilder(); EmbedBuilder scoreboardBuilder = new EmbedBuilder();
scoreboardBuilder.setColor(Cache.getBotColor()); scoreboardBuilder.setColor(Cache.getBotColor());
scoreboardBuilder.setTitle("\uD83C\uDF1F Trivia Scoreboard"); scoreboardBuilder.setTitle("\uD83C\uDF1F Trivia Scoreboard");
if(!winnersString.isEmpty()) scoreboardBuilder.addField(winnersTitle, winnersString, false); if (!winnersString.isEmpty()) scoreboardBuilder.addField(winnersTitle, winnersString, false);
else scoreboardBuilder.addField("\uD83D\uDE22 Sad Trivia", else scoreboardBuilder.addField("\uD83D\uDE22 Sad Trivia",
"No one played \uD83D\uDE2D", false); "No one played \uD83D\uDE2D", false);
if(!othersString.isEmpty()) scoreboardBuilder.addField("☁️ Others", othersString, false); if (!othersString.isEmpty()) scoreboardBuilder.addField("☁️ Others", othersString, false);
channel.sendMessage(scoreboardText).addEmbeds(scoreboardBuilder.build()).queue(); channel.sendMessage(scoreboardText).addEmbeds(scoreboardBuilder.build()).queue();
@@ -153,7 +156,7 @@ public class TriviaTask implements Runnable
answerButtons.add(correctAnswerButton); answerButtons.add(correctAnswerButton);
int i = 0; // we need to add a number because buttons can't have the same id int i = 0; // we need to add a number because buttons can't have the same id
for(String wrongAnswer : currentTriviaQuestion.wrongAnswers()) for (String wrongAnswer : currentTriviaQuestion.wrongAnswers())
{ {
i++; i++;
Button wrongAnswerButton = Button.primary("trivia_wrong_" + i, wrongAnswer); Button wrongAnswerButton = Button.primary("trivia_wrong_" + i, wrongAnswer);
@@ -166,9 +169,9 @@ public class TriviaTask implements Runnable
"\uD83D\uDFE2", "\uD83D\uDFE1", "\uD83D\uDFE4", "\uD83D\uDFE3", "\uD83D\uDFE0"); "\uD83D\uDFE2", "\uD83D\uDFE1", "\uD83D\uDFE4", "\uD83D\uDFE3", "\uD83D\uDFE0");
// add emojis to buttons // add emojis to buttons
for(int emojiPos = 0; emojiPos < buttonEmojis.size(); emojiPos++) for (int emojiPos = 0; emojiPos < buttonEmojis.size(); emojiPos++)
{ {
if(emojiPos == answerButtons.size()) break; if (emojiPos == answerButtons.size()) break;
String emoji = buttonEmojis.get(emojiPos); String emoji = buttonEmojis.get(emojiPos);
Button button = answerButtons.get(emojiPos); Button button = answerButtons.get(emojiPos);
@@ -180,7 +183,7 @@ public class TriviaTask implements Runnable
embedBuilder.setColor(Cache.getBotColor()); embedBuilder.setColor(Cache.getBotColor());
embedBuilder.setTitle("\uD83C\uDFB2 Trivia - " + category.categoryName() + embedBuilder.setTitle("\uD83C\uDFB2 Trivia - " + category.categoryName() +
" (" + (iteration+1) + "/" + questions.size() + ")"); " (" + (iteration + 1) + "/" + questions.size() + ")");
embedBuilder.addField("❓ Question", currentTriviaQuestion.question(), false); embedBuilder.addField("❓ Question", currentTriviaQuestion.question(), false);

View File

@@ -27,7 +27,8 @@ public class CommandUtil
private static final Logger LOGGER = LoggerFactory.getLogger(CommandUtil.class); private static final Logger LOGGER = LoggerFactory.getLogger(CommandUtil.class);
private CommandUtil() { private CommandUtil()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -40,7 +41,8 @@ public class CommandUtil
public static void delete(ButtonInteractionEvent event) public static void delete(ButtonInteractionEvent event)
{ {
// check if the user interacting is the same one who ran the command // check if the user interacting is the same one who ran the command
if (!(Cache.getDatabaseSource().isUserTrackedFor(event.getUser().getId(), event.getMessageId()))) { if (!(Cache.getDatabaseSource().isUserTrackedFor(event.getUser().getId(), event.getMessageId())))
{
event.reply("❌ You did not run this command!").setEphemeral(true).queue(); event.reply("❌ You did not run this command!").setEphemeral(true).queue();
return; return;
} }
@@ -63,8 +65,10 @@ public class CommandUtil
// populate commands list from registered commands // populate commands list from registered commands
List<CommandData> allCommands = new ArrayList<>(); List<CommandData> allCommands = new ArrayList<>();
for(SlashCommand cmd : Cache.getSlashCommandListener().getRegisteredCommands()) for (SlashCommand cmd : Cache.getSlashCommandListener().getRegisteredCommands())
{ allCommands.add(cmd.getSlashCommandData()); } {
allCommands.add(cmd.getSlashCommandData());
}
JDA jdaInstance = HidekoBot.getAPI(); JDA jdaInstance = HidekoBot.getAPI();
@@ -73,22 +77,22 @@ public class CommandUtil
boolean update = false; boolean update = false;
if(force) if (force)
{ {
update = true; update = true;
} else } else
{ {
// for each command that we have already registered... // for each command that we have already registered...
for(Command currRegCmd : registeredCommands) for (Command currRegCmd : registeredCommands)
{ {
boolean found = false; boolean found = false;
// iterate through all "recognized" commands // iterate through all "recognized" commands
for(CommandData cmdData : allCommands) for (CommandData cmdData : allCommands)
{ {
// if we find the same command... // if we find the same command...
if(cmdData.getName().equals(currRegCmd.getName())) if (cmdData.getName().equals(currRegCmd.getName()))
{ {
// quit the loop since we found it. // quit the loop since we found it.
found = true; found = true;
@@ -98,7 +102,7 @@ public class CommandUtil
// if no match was found, we need to send an updated command list because // if no match was found, we need to send an updated command list because
// an old command was probably removed. // an old command was probably removed.
if(!found) if (!found)
{ {
update = true; update = true;
@@ -108,18 +112,18 @@ public class CommandUtil
} }
// if an update is not already queued... // if an update is not already queued...
if(!update) if (!update)
{ {
// for each "recognized" valid command // for each "recognized" valid command
for(CommandData currCmdData : allCommands) for (CommandData currCmdData : allCommands)
{ {
boolean found = false; boolean found = false;
// iterate through all already registered commands. // iterate through all already registered commands.
for(Command cmd : registeredCommands) for (Command cmd : registeredCommands)
{ {
// if this command was already registered... // if this command was already registered...
if(cmd.getName().equals(currCmdData.getName())) if (cmd.getName().equals(currCmdData.getName()))
{ {
// quit the loop since we found a match. // quit the loop since we found a match.
found = true; found = true;
@@ -129,7 +133,7 @@ public class CommandUtil
// if no match was found, we need to send an updated command list because // if no match was found, we need to send an updated command list because
// a new command was probably added. // a new command was probably added.
if(!found) if (!found)
{ {
update = true; update = true;
@@ -142,7 +146,7 @@ public class CommandUtil
LOGGER.info("Found {} commands.", registeredCommands.size()); LOGGER.info("Found {} commands.", registeredCommands.size());
if(update) if (update)
{ {
// send updated command list. // send updated command list.
jdaInstance.updateCommands().addCommands(allCommands).queue(); jdaInstance.updateCommands().addCommands(allCommands).queue();
@@ -169,18 +173,18 @@ public class CommandUtil
MessageChannel textChannel = null; MessageChannel textChannel = null;
// this should never happen, but only message channels are supported. // this should never happen, but only message channels are supported.
if(!msgChannelType.isMessage()) if (!msgChannelType.isMessage())
{ {
databaseSource.untrackExpiredMessage(messageId); databaseSource.untrackExpiredMessage(messageId);
return; return;
} }
// if this is a DM // if this is a DM
if(!(msgChannelType.isGuild())) if (!(msgChannelType.isGuild()))
{ {
String userId = databaseSource.getTrackedReplyUserId(messageId); String userId = databaseSource.getTrackedReplyUserId(messageId);
User user = userId == null ? null : HidekoBot.getAPI().retrieveUserById(userId).complete(); User user = userId == null ? null : HidekoBot.getAPI().retrieveUserById(userId).complete();
if(user == null) if (user == null)
{ {
// if user is not found, consider it expired // if user is not found, consider it expired
// (deleted profile, or blocked the bot) // (deleted profile, or blocked the bot)
@@ -189,12 +193,11 @@ public class CommandUtil
} }
textChannel = user.openPrivateChannel().complete(); textChannel = user.openPrivateChannel().complete();
} } else
else
{ {
String guildId = databaseSource.getQueuedExpiringMessageGuild(messageId); String guildId = databaseSource.getQueuedExpiringMessageGuild(messageId);
Guild guild = guildId == null ? null : HidekoBot.getAPI().getGuildById(guildId); Guild guild = guildId == null ? null : HidekoBot.getAPI().getGuildById(guildId);
if(guild == null) if (guild == null)
{ {
// if guild is not found, consider it expired // if guild is not found, consider it expired
// (server was deleted or bot was kicked) // (server was deleted or bot was kicked)
@@ -204,7 +207,7 @@ public class CommandUtil
textChannel = guild.getTextChannelById(channelId); textChannel = guild.getTextChannelById(channelId);
} }
if(textChannel == null) if (textChannel == null)
{ {
// if channel is not found, count it as expired // if channel is not found, count it as expired
// (channel was deleted or bot permissions restricted) // (channel was deleted or bot permissions restricted)
@@ -215,11 +218,11 @@ public class CommandUtil
RestAction<Message> retrieveAction = textChannel.retrieveMessageById(messageId); RestAction<Message> retrieveAction = textChannel.retrieveMessageById(messageId);
if(Cache.isVerbose()) LOGGER.info("cleaning up: {}", messageId); if (Cache.isVerbose()) LOGGER.info("cleaning up: {}", messageId);
retrieveAction.queue( retrieveAction.queue(
message -> { message -> {
if(message == null) if (message == null)
{ {
databaseSource.untrackExpiredMessage(messageId); databaseSource.untrackExpiredMessage(messageId);
return; return;

View File

@@ -12,7 +12,8 @@ import java.util.Arrays;
public class FormatUtil public class FormatUtil
{ {
private FormatUtil() { private FormatUtil()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -60,21 +61,25 @@ public class FormatUtil
* *
* @return the formatted String * @return the formatted String
*/ */
public static String getNiceDuration(Duration duration) { public static String getNiceDuration(Duration duration)
{
long days = duration.toDays(); long days = duration.toDays();
long hours = duration.toHoursPart(); long hours = duration.toHoursPart();
long minutes = duration.toMinutesPart(); long minutes = duration.toMinutesPart();
long seconds = duration.toSecondsPart(); long seconds = duration.toSecondsPart();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (days > 0) { if (days > 0)
{
sb.append(days).append("d "); sb.append(days).append("d ");
sb.append(hours).append("h "); sb.append(hours).append("h ");
sb.append(minutes).append("m "); sb.append(minutes).append("m ");
} else if (hours > 0) { } else if (hours > 0)
{
sb.append(hours).append("h "); sb.append(hours).append("h ");
sb.append(minutes).append("m "); sb.append(minutes).append("m ");
} else if (minutes > 0) { } else if (minutes > 0)
{
sb.append(minutes).append("m "); sb.append(minutes).append("m ");
} }
sb.append(seconds).append("s"); sb.append(seconds).append("s");
@@ -93,7 +98,7 @@ public class FormatUtil
public static Duration parseDuration(String duration) public static Duration parseDuration(String duration)
{ {
// sanitize a bit to avoid cluttering with garbled strings // sanitize a bit to avoid cluttering with garbled strings
if(duration.length() > 16) duration = duration.substring(0, 16); if (duration.length() > 16) duration = duration.substring(0, 16);
duration = duration.replaceAll("[^\\w]", ""); //only keep digits and word characters duration = duration.replaceAll("[^\\w]", ""); //only keep digits and word characters
duration = duration.toLowerCase(); duration = duration.toLowerCase();
@@ -105,7 +110,7 @@ public class FormatUtil
{1,10} is used to limit the size of the input to parse, to avoid stack overflows. {1,10} is used to limit the size of the input to parse, to avoid stack overflows.
no one should be typing more than 10 arguments, or more than 10 digits for a single argument anyway. no one should be typing more than 10 arguments, or more than 10 digits for a single argument anyway.
*/ */
if(!duration.matches("(\\d{1,10}[a-zA-Z]{1,10}){1,10}")) if (!duration.matches("(\\d{1,10}[a-zA-Z]{1,10}){1,10}"))
return null; return null;
String[] durationTimes = duration.split("[a-zA-Z]+"); String[] durationTimes = duration.split("[a-zA-Z]+");
@@ -116,7 +121,7 @@ public class FormatUtil
Duration fullDuration = Duration.ZERO; Duration fullDuration = Duration.ZERO;
for(int i = 0; i < durationTimes.length; i++) for (int i = 0; i < durationTimes.length; i++)
{ {
String durationTimeStr = durationTimes[i]; String durationTimeStr = durationTimes[i];
String durationUnitStr = durationUnits[i]; String durationUnitStr = durationUnits[i];
@@ -124,7 +129,7 @@ public class FormatUtil
int durationValue = Integer.parseInt(durationTimeStr); int durationValue = Integer.parseInt(durationTimeStr);
TemporalUnit unit = parseTimeUnit(durationUnitStr); TemporalUnit unit = parseTimeUnit(durationUnitStr);
if(unit != null) if (unit != null)
fullDuration = fullDuration.plus(durationValue, unit); fullDuration = fullDuration.plus(durationValue, unit);
else return null; // if we failed finding the time unit, instantly quit with failed parsing. else return null; // if we failed finding the time unit, instantly quit with failed parsing.
} }

View File

@@ -50,7 +50,8 @@ public class Logger<T>
{ {
// create a new scheduled executor with an anonymous runnable... // create a new scheduled executor with an anonymous runnable...
//... after waiting <delay> seconds. //... after waiting <delay> seconds.
try (ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor()) { try (ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor())
{
executor.schedule(() -> log(message), delay, TimeUnit.SECONDS); executor.schedule(() -> log(message), delay, TimeUnit.SECONDS);
} }

View File

@@ -10,7 +10,8 @@ import java.util.Random;
public class RandomUtil public class RandomUtil
{ {
private RandomUtil() { private RandomUtil()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@@ -27,8 +28,8 @@ public class RandomUtil
*/ */
public static int getRandomNumber(int min, int max) public static int getRandomNumber(int min, int max)
{ {
if(min == max) return min; // dumbass if (min == max) return min; // dumbass
if(min > max) // swap em if (min > max) // swap em
{ {
min = min - max; min = min - max;
max = min + max; max = min + max;
@@ -47,7 +48,8 @@ public class RandomUtil
} }
public static Random getRandom() { public static Random getRandom()
{
return randomInstance; return randomInstance;
} }

View File

@@ -10,33 +10,38 @@ import java.util.List;
public class SerializationUtil public class SerializationUtil
{ {
private SerializationUtil() { private SerializationUtil()
{
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
public static <T> String serializeBase64(List<T> 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))
{
so.writeObject(dataList); so.writeObject(dataList);
so.flush(); so.flush();
return Base64.getEncoder().encodeToString(bo.toByteArray()); return Base64.getEncoder().encodeToString(bo.toByteArray());
} } catch (IOException e)
catch (IOException e) { {
throw new SerializationException("Error during serialization", e); throw new SerializationException("Error during serialization", e);
} }
} }
public static <T> LinkedList<T> 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);
ObjectInputStream si; ObjectInputStream si;
try { try
{
si = new ObjectInputStream(bi); si = new ObjectInputStream(bi);
return LinkedList.class.cast(si.readObject()); return LinkedList.class.cast(si.readObject());
} } catch (IOException | ClassNotFoundException e)
catch (IOException | ClassNotFoundException e) { {
throw new SerializationException("Error during deserialization", e); throw new SerializationException("Error during deserialization", e);
} }
} }