diff --git a/languages/en-GB.yml b/languages/en-GB.yml index dcbb56d4c..7b0152337 100644 --- a/languages/en-GB.yml +++ b/languages/en-GB.yml @@ -238,6 +238,7 @@ message: other: "The Birthday of %s has been removed!" noPerms: "You don't have the permission to remove a Birthday!" wish: "Happy birthday to <@%s>!" + list: "Here are all Birthday wishes:\n```%s```" instagramNotifier: added: "A Instagram Notifier has been created for the User %s!" list: "Here are all Instagram Notifier that have been setup:\n```%s```" diff --git a/pom.xml b/pom.xml index ec1ba0178..b3f640bb7 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ de.presti Ree6 - 3.1.13 + 4.0.0-alpha.4 jar @@ -18,6 +18,7 @@ UTF-8 dxssucuk https://sonarcloud.io + 3.4.2 @@ -55,9 +56,9 @@ - net.dv8tion + io.github.JDA-Fork JDA - 5.1.2 + 55d824408c @@ -81,9 +82,9 @@ 1.1.2 - club.minnced + de.ree6 discord-webhooks - 0.8.4 + f67bf93e5f @@ -182,7 +183,7 @@ de.ree6 Ree6-SQL - da620ec7a5 + 7916908de2 @@ -260,7 +261,6 @@ 3.1.9 - org.apache.httpcomponents.client5 @@ -286,6 +286,19 @@ gson 2.11.0 + + + + org.pf4j + pf4j + 3.12.0 + + + org.slf4j + slf4j-simple + + + @@ -351,6 +364,9 @@ ^git.build.(time|version)$ ^git.commit.id.(abbrev|full)$ + ^git.dirty$ + ^git.branch$ + ^git.remote.origin.url$ full ddMMyyyy diff --git a/src/main/java/de/presti/ree6/addons/Addon.java b/src/main/java/de/presti/ree6/addons/Addon.java deleted file mode 100644 index 0777379d6..000000000 --- a/src/main/java/de/presti/ree6/addons/Addon.java +++ /dev/null @@ -1,106 +0,0 @@ -package de.presti.ree6.addons; - -import java.io.File; - -/** - * Created a new Local-Addon - * - * @param addonInterface AddonInterface. - * @param name Add-on Name. - * @param author Add-on Author. - * @param version Add-on Version. - * @param apiVersion Ree6 Version used for the Addon. - * @param classPath Path to the Main-Class in the JAR. - * @param file The actual JAR as File. - */ -public record Addon(AddonInterface addonInterface, String name, String author, String version, - String apiVersion, String classPath, File file) { - - /** - * Get the AddonInterface. - * - * @return AddonInterface. - */ - public AddonInterface getAddonInterface() { - return addonInterface; - } - - /** - * Get the Add-on Name. - * - * @return Add-on Name. - */ - public String getName() { - return name; - } - - /** - * Get the Author Name. - * - * @return Author Name. - */ - public String getAuthor() { - return author; - } - - /** - * Get the Add-on Version. - * - * @return Add-on Version. - */ - public String getVersion() { - return version; - } - - /** - * Get the Ree6 Version used for the Addon. - * - * @return used Ree6 Version. - */ - public String getApiVersion() { - return apiVersion; - } - - /** - * Get the Path to the Main class. - * - * @return Main class Path. - */ - public String getClassPath() { - return classPath; - } - - /** - * Get the actual File. - * - * @return File. - */ - public File getFile() { - return file; - } - - /** - * Get the ClassLoader of the Addon. - * @return ClassLoader. - */ - public ClassLoader getClassLoader() { - return addonInterface.getClass().getClassLoader(); - } - - /** - * Get everything in a single String. - * - * @return a String with every data. - */ - @Override - public String toString() { - return "Addon{" + - "name='" + getName() + '\'' + - ", author='" + getAuthor() + '\'' + - ", version='" + getVersion() + '\'' + - ", api='" + getApiVersion() + '\'' + - ", path='" + getClassPath() + '\'' + - ", file=" + getFile().getAbsolutePath() + - '}'; - } -} diff --git a/src/main/java/de/presti/ree6/addons/AddonInterface.java b/src/main/java/de/presti/ree6/addons/AddonInterface.java deleted file mode 100644 index 7de4ffb9b..000000000 --- a/src/main/java/de/presti/ree6/addons/AddonInterface.java +++ /dev/null @@ -1,17 +0,0 @@ -package de.presti.ree6.addons; - -/** - * The Interface used for the Addons. - */ -public interface AddonInterface { - - /** - * Called methode when the Addon gets started (What a surprise isn't it :)) - */ - void onEnable(); - - /** - * Called methode when the Addon get stopped. - */ - void onDisable(); -} diff --git a/src/main/java/de/presti/ree6/addons/AddonLoader.java b/src/main/java/de/presti/ree6/addons/AddonLoader.java deleted file mode 100644 index 6557e7794..000000000 --- a/src/main/java/de/presti/ree6/addons/AddonLoader.java +++ /dev/null @@ -1,207 +0,0 @@ -package de.presti.ree6.addons; - -import de.presti.ree6.addons.utils.AddonClassLoader; -import de.presti.ree6.main.Main; -import lombok.extern.slf4j.Slf4j; -import org.simpleyaml.configuration.file.FileConfiguration; -import org.simpleyaml.configuration.file.YamlConfiguration; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.StandardCharsets; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -/** - * The actual Addon-Loader which Loads every single Addon from the Addon Folder. - */ -@Slf4j -@SuppressWarnings("ResultOfMethodCallIgnored") -public class AddonLoader { - - /** - * Constructor should not be called, since it is a utility class that doesn't need an instance. - * - * @throws IllegalStateException it is a utility class. - */ - private AddonLoader() { - throw new IllegalStateException("Utility class"); - } - - /** - * Create the Folder if not existing. - */ - private static void createFolders() { - if (!new File("addons/").exists()) { - new File("addons/").mkdir(); - } - - if (!new File("addons/tmp/").exists()) { - new File("addons/tmp/").mkdir(); - } - } - - /** - * Load every Addon. - */ - public static void loadAllAddons() { - - // Create Folder if not existing. - createFolders(); - - // Get every single File from the Folder. - File[] files = new File("addons/").listFiles(); - - // Check if there are any Files. - assert files != null; - for (File file : files) { - - // Check if it's a jar File. - if (file.getName().endsWith("jar")) { - try { - // Try creating a Local-Addon and adding it into the loaded Addon List. - Addon addon = loadAddon(file.getName()); - - if (addon == null) { - log.error("Couldn't pre-load the addon {}", file.getName()); - } - - Main.getInstance().getAddonManager().loadAddon(addon); - } catch (Exception ex) { - // If the Methode loadAddon fails notify. - log.error("[AddonManager] Couldn't load the Addon {}\nException: {}", file.getName(), ex.getMessage()); - } - } - } - - } - - /** - * Actually load a Addon. - * - * @param fileName Name of the File. - * @return a Local-Addon. - * @throws IOException If it is an invalid Addon. - */ - public static Addon loadAddon(String fileName) throws IOException { - - // Initialize local Variables to save Information about the Addon. - String name = null, author = null, version = null, apiVersion = null, classPath = null; - - - // Create a ZipInputStream to get every single class inside the JAR. I'm pretty sure there is a faster and more efficient way, but I didn't have the time to find it. - try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("addons/" + fileName))) { - ZipEntry entry; - - // While there a still Classes inside the JAR, it should check them. - while ((entry = zipInputStream.getNextEntry()) != null) { - try { - // Get the current name of the class. - String entryName = entry.getName(); - - // Check if it is a Directory if so don't do anything and skip. - // If it is the addon.yml then get the Data from it. - if (!entry.isDirectory() && entryName.equalsIgnoreCase("addon.yml")) { - String content; - // Create a FileOutputStream of the temporal File and write every bite from the File inside the JAR. - try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { - - for (int c = zipInputStream.read(); c != -1; c = zipInputStream.read()) { - os.write(c); - } - - content = os.toString(StandardCharsets.UTF_8); - } - - if (content == null) { - log.info("Error while trying to pre-load the Addon {}\nException: {}", fileName, "Content is null"); - continue; - } - - // Load it as a YAML-Config and fill the Variables. - FileConfiguration conf = YamlConfiguration.loadConfigurationFromString(content); - - name = conf.getString("name"); - author = conf.getString("author"); - version = conf.getString("version"); - apiVersion = conf.getString("api-version"); - classPath = conf.getString("main"); - break; - } - } catch (Exception e) { - log.error("Error while trying to pre-load the Addon {}\nException: {}", fileName, e.getMessage()); - zipInputStream.closeEntry(); - } finally { - zipInputStream.closeEntry(); - } - } - } - - // Check if there is any data core data if not throw this error. - if (name == null && classPath == null) { - log.error("Error while trying to pre-load the Addon {}, no addon.yml given.", fileName); - } else { - File addonFile = new File("addons/" + fileName); - AddonInterface addonInterface = null; - // Try loading the Class with a URL Class Loader. - try (AddonClassLoader urlClassLoader = new AddonClassLoader(new URL[] { addonFile.toURI().toURL() }, AddonLoader.class.getClassLoader())) { - - // Get the Addon Class. - Class> addonClass = getClass(urlClassLoader, classPath); - - // If valid, call the onEnable methode. - if (addonClass != null) { - log.info("[AddonManager] Loaded {} ({}) by {}", name, version, author); - addonInterface = (AddonInterface) addonClass.getDeclaredConstructor().newInstance(); - } else { - // If not inform about an invalid Addon. - log.error("[AddonManager] Couldn't load the Addon {}({}) by {}", name, version, author); - log.error("[AddonManager] The given Main class doesn't not implement our AddonInterface!"); - } - } catch (Exception e) { - log.error("[AddonManager] Couldn't start the Addon {}({}) by {}", name, version, author); - log.error("[AddonManager] Exception: {}", e.getMessage()); - } - - if (addonInterface == null) { - log.error("Error while trying to pre-load the Addon {}\nException: {}", fileName, "AddonInterface is null"); - return null; - } - - return new Addon(addonInterface, name, author, version, apiVersion, classPath, new File("addons/" + fileName)); - } - - return null; - } - - /** - * Get the Addon Class from the Class-Loader and its path. - * - * @param classLoader the Class Loader of the File. - * @param classPath the Path to the Main class. - * @return the Main class of the Addon. - * @throws ClassNotFoundException if there is no file with the given Path. - */ - private static Class> getClass(AddonClassLoader classLoader, String classPath) throws ClassNotFoundException { - // Class from the loader. - Class> urlCl = classLoader.loadClass(classPath); - - // Get the Interfaces. - Class>[] ifs = urlCl.getInterfaces(); - - // Check if any of the Interfaces is the AddonInterface. - for (Class> anIf : ifs) { - - // If it has the AddonInterface mark it as valid. - if (anIf.getName().equalsIgnoreCase("de.presti.ree6.addons.AddonInterface")) { - return urlCl; - } - } - - return null; - } -} diff --git a/src/main/java/de/presti/ree6/addons/AddonManager.java b/src/main/java/de/presti/ree6/addons/AddonManager.java deleted file mode 100644 index ad53246b1..000000000 --- a/src/main/java/de/presti/ree6/addons/AddonManager.java +++ /dev/null @@ -1,123 +0,0 @@ -package de.presti.ree6.addons; - -import de.presti.ree6.bot.BotWorker; -import de.presti.ree6.utils.others.VersionUtil; -import lombok.extern.slf4j.Slf4j; - -import java.util.ArrayList; - -/** - * The AddonManager has been created to save every Addon in a List to keep track of them - * and to unload them if wanted/needed. - */ -@Slf4j -public class AddonManager { - /** - * The actual List with the Addons. - */ - public final ArrayList addons = new ArrayList<>(); - - /** - * Reload the AddonManager by stopping every Addon and reading them. - */ - public void reload() { - stopAddons(); - - addons.clear(); - - AddonLoader.loadAllAddons(); - - startAddons(); - } - - /** - * Try starting an Addon by calling the Class with a URL-Class Loader. - * - * @param addon the Local-Addon. - */ - public void startAddon(Addon addon) { - log.info("[AddonManager] Loading {} ({}) by {}", addon.getName(), addon.getVersion(), addon.getAuthor()); - - // Check if it's made for the current Ree6 Version if not inform. - if (!addon.getApiVersion().equalsIgnoreCase(BotWorker.getBuild())) { - - VersionUtil.VersionType difference = VersionUtil.compareVersion(BotWorker.getBuild(), addon.getApiVersion()); - - boolean isAddonForOlder = true; - - if (difference == VersionUtil.VersionType.NONE) { - VersionUtil.VersionType reverseDifference = VersionUtil.compareVersion(addon.getApiVersion(), BotWorker.getBuild()); - if (reverseDifference != VersionUtil.VersionType.NONE) { - isAddonForOlder = false; - difference = reverseDifference; - } - } - - if (isAddonForOlder) { - log.warn("[AddonManager] The Addon {}({}) by {} is made for an older version of Ree6. Ree6 is on Version {} and the Addon is made for Version {}.", addon.getName(), addon.getVersion(), addon.getAuthor(), BotWorker.getBuild(), addon.getApiVersion()); - } else { - log.warn("[AddonManager] The Addon {}({}) by {} is made for a newer version of Ree6. Ree6 is on Version {} and the Addon is made for Version {}.", addon.getName(), addon.getVersion(), addon.getAuthor().toLowerCase(), BotWorker.getBuild(), addon.getApiVersion()); - } - - if (difference == VersionUtil.VersionType.MAYOR) { - log.warn("[AddonManager] Version difference is at least one mayor version, be advised this will most likely cause Issues or not work at all!"); - } else if (difference == VersionUtil.VersionType.MINOR || difference == VersionUtil.VersionType.PATCH) { - log.warn("[AddonManager] Version difference is at least one " + difference.name().toLowerCase() + " version, be advised this might cause Issues!"); - } - } - - try { - addon.getAddonInterface().onEnable(); - } catch (Exception ex) { - // Throw an error if the Addon is invalid or corrupted. - log.error("[AddonManager] Couldn't start the Addon {}({}) by {}", addon.getName(), addon.getVersion(), addon.getAuthor()); - log.error("[AddonManager] Information: {}, {}, {}", addon.getClassPath(), addon.getVersion(), addon.getApiVersion()); - log.error("[AddonManager] Exception: ", ex); - } - } - - /** - * Start every Addon from the AddonList. - */ - public void startAddons() { - for (Addon addon : addons) { - startAddon(addon); - } - } - - /** - * Try stopping the Addon by calling the Main-Class methode onDisable. - * - * @param addon The Local-Addon. - */ - public void stopAddon(Addon addon) { - log.info("[AddonManager] Unloading {} ({}) by {}", addon.getName(), addon.getVersion(), addon.getAuthor()); - - try { - addon.getAddonInterface().onDisable(); - } catch (Exception ex) { - // Throw an error if the Addon is invalid or corrupted. - log.error("[AddonManager] Couldn't stop the Addon {}({}) by {}", addon.getName(), addon.getVersion(), addon.getAuthor()); - log.error("[AddonManager] Information: {}, {}, {}", addon.getClassPath(), addon.getVersion(), addon.getApiVersion()); - log.error("[AddonManager] Exception: ", ex); - } - } - - /** - * Stop every Addon. - */ - public void stopAddons() { - for (Addon addon : addons) { - stopAddon(addon); - } - } - - /** - * "Load" an Addon. - * - * @param addon the Local-Addon. - */ - public void loadAddon(Addon addon) { - addons.add(addon); - } -} diff --git a/src/main/java/de/presti/ree6/addons/ReePlugin.java b/src/main/java/de/presti/ree6/addons/ReePlugin.java new file mode 100644 index 000000000..7fb8766fa --- /dev/null +++ b/src/main/java/de/presti/ree6/addons/ReePlugin.java @@ -0,0 +1,16 @@ +package de.presti.ree6.addons; + +import org.pf4j.Plugin; + +/** + * The Interface used for the Addons. + */ +public abstract class ReePlugin extends Plugin { + + protected final ReePluginContext context; + + protected ReePlugin(ReePluginContext context) { + super(); + this.context = context; + } +} diff --git a/src/main/java/de/presti/ree6/addons/ReePluginContext.java b/src/main/java/de/presti/ree6/addons/ReePluginContext.java new file mode 100644 index 000000000..c1e0d72a6 --- /dev/null +++ b/src/main/java/de/presti/ree6/addons/ReePluginContext.java @@ -0,0 +1,15 @@ +package de.presti.ree6.addons; + +import lombok.Getter; +import org.pf4j.RuntimeMode; + +@Getter +public class ReePluginContext { + + private final RuntimeMode runtimeMode; + + public ReePluginContext(RuntimeMode runtimeMode) { + this.runtimeMode = runtimeMode; + } + +} diff --git a/src/main/java/de/presti/ree6/addons/ReePluginFactory.java b/src/main/java/de/presti/ree6/addons/ReePluginFactory.java new file mode 100644 index 000000000..c41e31436 --- /dev/null +++ b/src/main/java/de/presti/ree6/addons/ReePluginFactory.java @@ -0,0 +1,25 @@ +package de.presti.ree6.addons; + +import lombok.extern.slf4j.Slf4j; +import org.pf4j.DefaultPluginFactory; +import org.pf4j.Plugin; +import org.pf4j.PluginWrapper; + +import java.lang.reflect.Constructor; + +@Slf4j +public class ReePluginFactory extends DefaultPluginFactory { + + @Override + protected Plugin createInstance(Class> pluginClass, PluginWrapper pluginWrapper) { + ReePluginContext context = new ReePluginContext(pluginWrapper.getRuntimeMode()); + try { + Constructor> constructor = pluginClass.getConstructor(ReePluginContext.class); + return (Plugin) constructor.newInstance(context); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + + return null; + } +} diff --git a/src/main/java/de/presti/ree6/addons/ReePluginManager.java b/src/main/java/de/presti/ree6/addons/ReePluginManager.java new file mode 100644 index 000000000..e307a113f --- /dev/null +++ b/src/main/java/de/presti/ree6/addons/ReePluginManager.java @@ -0,0 +1,35 @@ +package de.presti.ree6.addons; + +import lombok.extern.slf4j.Slf4j; +import org.pf4j.DefaultPluginManager; +import org.pf4j.PluginDescriptorFinder; +import org.pf4j.PluginFactory; + +@Slf4j +public class ReePluginManager extends DefaultPluginManager { + + public ReePluginManager() { + super(); + addPluginStateListener(x -> { + switch (x.getPluginState()) { + case STARTED -> log.info("Plugin '{}' started", x.getPlugin().getPluginId()); + case FAILED -> log.error("Plugin '{}' failed", x.getPlugin().getPluginId()); + case STOPPED -> log.info("Plugin '{}' stopped", x.getPlugin().getPluginId()); + case DISABLED -> log.info("Plugin '{}' disabled", x.getPlugin().getPluginId()); + case UNLOADED -> log.info("Plugin '{}' unloading", x.getPlugin().getPluginId()); + case CREATED -> log.info("Plugin '{}' created", x.getPlugin().getPluginId()); + case RESOLVED -> log.info("Plugin '{}' resolved", x.getPlugin().getPluginId()); + } + }); + } + + @Override + protected PluginDescriptorFinder createPluginDescriptorFinder() { + return new YamlPluginDescriptorFinder(); + } + + @Override + protected PluginFactory createPluginFactory() { + return new ReePluginFactory(); + } +} diff --git a/src/main/java/de/presti/ree6/addons/YamlPluginDescriptorFinder.java b/src/main/java/de/presti/ree6/addons/YamlPluginDescriptorFinder.java new file mode 100644 index 000000000..6b56a3dc4 --- /dev/null +++ b/src/main/java/de/presti/ree6/addons/YamlPluginDescriptorFinder.java @@ -0,0 +1,117 @@ +package de.presti.ree6.addons; + +import lombok.extern.slf4j.Slf4j; +import org.pf4j.*; +import org.pf4j.util.FileUtils; +import org.pf4j.util.StringUtils; +import org.simpleyaml.configuration.file.YamlConfiguration; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +@Slf4j +public class YamlPluginDescriptorFinder implements PluginDescriptorFinder { + + public static final String DEFAULT_PROPERTIES_FILE_NAME = "plugin.yml"; + + public static final String PLUGIN_ID = "id"; + public static final String PLUGIN_DESCRIPTION = "description"; + public static final String PLUGIN_CLASS = "class"; + public static final String PLUGIN_VERSION = "version"; + public static final String PLUGIN_PROVIDER = "provider"; + public static final String PLUGIN_DEPENDENCIES = "dependencies"; + public static final String PLUGIN_REQUIRES = "requires"; + public static final String PLUGIN_LICENSE = "license"; + + protected String propertiesFileName; + + public YamlPluginDescriptorFinder() { + this(DEFAULT_PROPERTIES_FILE_NAME); + } + + public YamlPluginDescriptorFinder(String propertiesFileName) { + this.propertiesFileName = propertiesFileName; + } + + @Override + public boolean isApplicable(Path pluginPath) { + return Files.exists(pluginPath) && (Files.isDirectory(pluginPath) || FileUtils.isZipOrJarFile(pluginPath)); + } + + @Override + public PluginDescriptor find(Path pluginPath) { + YamlConfiguration properties = readYaml(pluginPath); + + return createPluginDescriptor(properties); + } + + protected YamlConfiguration readYaml(Path pluginPath) { + Path yamlPath = getYamlPath(pluginPath, propertiesFileName); + if (yamlPath == null) { + throw new PluginRuntimeException("Cannot find the properties path"); + } + + YamlConfiguration yamlConfiguration = null; + try { + log.debug("Lookup plugin descriptor in '{}'", yamlPath); + if (Files.notExists(yamlPath)) { + throw new PluginRuntimeException("Cannot find '{}' path", yamlPath); + } + + try (InputStream input = Files.newInputStream(yamlPath)) { + yamlConfiguration = YamlConfiguration.loadConfiguration(() -> input); + } catch (IOException e) { + throw new PluginRuntimeException(e); + } + } finally { + FileUtils.closePath(yamlPath); + } + + return yamlConfiguration; + } + + protected Path getYamlPath(Path pluginPath, String propertiesFileName) { + if (Files.isDirectory(pluginPath)) { + return pluginPath.resolve(Paths.get(propertiesFileName)); + } + + // it's a zip or jar file + try { + return FileUtils.getPath(pluginPath, propertiesFileName); + } catch (IOException e) { + throw new PluginRuntimeException(e); + } + } + + protected PluginDescriptor createPluginDescriptor(YamlConfiguration yamlConfiguration) { + String id = yamlConfiguration.getString(PLUGIN_ID); + + String description = yamlConfiguration.getString(PLUGIN_DESCRIPTION); + if (StringUtils.isNullOrEmpty(description)) { + description = ""; + } + + String clazz = yamlConfiguration.getString(PLUGIN_CLASS); + String version = yamlConfiguration.getString(PLUGIN_VERSION); + String provider = yamlConfiguration.getString(PLUGIN_PROVIDER); + List dependencies = yamlConfiguration.getStringList(PLUGIN_DEPENDENCIES); + String requires = yamlConfiguration.getString(PLUGIN_REQUIRES); + String license = yamlConfiguration.getString(PLUGIN_LICENSE); + + DefaultPluginDescriptor pluginDescriptor = createPluginDescriptorInstance(id, description, clazz, version, requires, provider, license); + + for (String dependency : dependencies) { + pluginDescriptor.addDependency(new PluginDependency(dependency)); + } + + return pluginDescriptor; + } + + protected DefaultPluginDescriptor createPluginDescriptorInstance(String id, String description, String clazz, String version, String requires, String provider, String license) { + return new DefaultPluginDescriptor(id, description, clazz, version, requires, provider, license); + } +} diff --git a/src/main/java/de/presti/ree6/addons/utils/AddonClassLoader.java b/src/main/java/de/presti/ree6/addons/utils/AddonClassLoader.java deleted file mode 100644 index cd9284af0..000000000 --- a/src/main/java/de/presti/ree6/addons/utils/AddonClassLoader.java +++ /dev/null @@ -1,45 +0,0 @@ -package de.presti.ree6.addons.utils; - -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Arrays; -import java.util.List; - -public class AddonClassLoader extends URLClassLoader { - - public static final List SHARED_PACKAGES = Arrays.asList( - "de.ree6.sql", - "de.presti.ree6.commands", - "de.presti.ree6.bot.util", - "de.presti.ree6.utils", - "de.presti.ree6.module", - "de.presti.ree6.main", - "de.presti.ree6.language", - "de.presti.ree6.game", - "de.presti.ree6.audio" - ); - - public AddonClassLoader(URL[] urls, ClassLoader parent) { - super(urls, parent); - } - - @Override - protected Class> loadClass(String name, boolean resolve) - throws ClassNotFoundException { - // has the class loaded already? - Class> loadedClass = findLoadedClass(name); - if (loadedClass == null) { - final boolean isSharedClass = SHARED_PACKAGES.stream().anyMatch(name::startsWith); - if (isSharedClass) { - loadedClass = getParent().loadClass(name); - } else { - loadedClass = super.loadClass(name, resolve); - } - } - - if (resolve) { // marked to resolve - resolveClass(loadedClass); - } - return loadedClass; - } -} diff --git a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java index 94a8509d9..15907278c 100644 --- a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java +++ b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java @@ -73,34 +73,40 @@ public class AudioPlayerReceiveHandler implements AudioReceiveHandler { /** * Constructor. * - * @param member The member who started the recording. + * @param member The member who started the recording. * @param audioChannelUnion The voice channel this handler should handle. */ public AudioPlayerReceiveHandler(Member member, AudioChannelUnion audioChannelUnion) { this.creatorId = member.getIdLong(); this.audioChannelUnion = audioChannelUnion; if (audioChannelUnion.getGuild().getSelfMember().hasPermission(Permission.NICKNAME_CHANGE)) { - audioChannelUnion.getGuild().getSelfMember().modifyNickname(LanguageService.getByGuild(member.getGuild(), "label.recording.name")).reason(LanguageService.getByGuild(member.getGuild(), "message.recording.startReason", member.getUser().getName())).onErrorMap(throwable -> { - - boolean canTalk = audioChannelUnion.getType() == ChannelType.STAGE ? - audioChannelUnion.asStageChannel().canTalk() : - audioChannelUnion.asVoiceChannel().canTalk(); - - if (canTalk) audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(member.getGuild(), "message.default.nameChangeFailed")).queue(); - return null; - }).queue(); + LanguageService.getByGuild(member.getGuild(), "label.recording.name").subscribe(name -> + LanguageService.getByGuild(member.getGuild(), "message.recording.startReason", member.getUser().getName()).subscribe(reason -> + audioChannelUnion.getGuild().getSelfMember().modifyNickname(name).reason(reason).onErrorMap(throwable -> { + + boolean canTalk = audioChannelUnion.getType() == ChannelType.STAGE ? + audioChannelUnion.asStageChannel().canTalk() : + audioChannelUnion.asVoiceChannel().canTalk(); + + if (canTalk) { + LanguageService.getByGuild(member.getGuild(), "message.default.nameChangeFailed").subscribe(messageContent -> + audioChannelUnion.asGuildMessageChannel().sendMessage(messageContent).queue()); + } + return null; + }).queue())); } message = audioChannelUnion.asGuildMessageChannel().sendMessageEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(member.getGuild(), "message.recording.started")) - .setColor(Color.YELLOW) - .setFooter(LanguageService.getByGuild(member.getGuild(),"label.footerMessage", member.getEffectiveName(), BotConfig.getAdvertisement()), member.getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(member.getGuild(), "label.recording.start")) + .setDescription(LanguageService.getByGuild(member.getGuild(), "message.recording.started").block()) + .setColor(BotConfig.getMainColor()) + .setFooter(LanguageService.getByGuild(member.getGuild(), "label.footerMessage", member.getEffectiveName(), BotConfig.getAdvertisement()).block(), member.getEffectiveAvatarUrl()) + .setTitle(LanguageService.getByGuild(member.getGuild(), "label.recording.start").block()) .build()).complete(); if (audioChannelUnion.getGuild().getSelfMember().hasPermission(Permission.VOICE_SET_STATUS)) { if (audioChannelUnion.getType() == ChannelType.VOICE) { - audioChannelUnion.asVoiceChannel().modifyStatus(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.name")).queue(); + LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.name").subscribe(name -> + audioChannelUnion.asVoiceChannel().modifyStatus(name).queue()); } } } @@ -166,11 +172,14 @@ public void endReceiving() { audioChannelUnion.asVoiceChannel().canTalk(); if (audioChannelUnion.getGuild().getSelfMember().hasPermission(Permission.NICKNAME_CHANGE)) { - audioChannelUnion.getGuild().getSelfMember().modifyNickname(audioChannelUnion.getGuild().getSelfMember().getUser().getName()).reason(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopReason")).onErrorMap(throwable -> { - - if (canTalk) audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.default.nameChangeFailed")).queue(); - return null; - }).queue(); + LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopReason").subscribe(reason -> + audioChannelUnion.getGuild().getSelfMember().modifyNickname(audioChannelUnion.getGuild().getSelfMember().getUser().getName()).reason(reason).onErrorMap(throwable -> { + + if (canTalk) + LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.default.nameChangeFailed") + .subscribe(messageContent -> audioChannelUnion.asGuildMessageChannel().sendMessage(messageContent).queue()); + return null; + }).queue()); } try { @@ -183,40 +192,32 @@ public void endReceiving() { Recording recording = new Recording(audioChannelUnion.getGuild().getIdLong(), audioChannelUnion.getIdLong(), creatorId, AudioUtil.convertPCMtoWAV(byteBuffer), JsonParser.parseString(new Gson().toJson(participants)).getAsJsonArray()); - boolean failedToUpload = false; - - try { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(recording); - } catch (Exception ignore) { - failedToUpload = true; - } - - if (canTalk) { - message.editMessageEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopped")) - .setColor(Color.GREEN) - .setFooter(BotConfig.getAdvertisement(), audioChannelUnion.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.finished")) - .build()) - .setActionRow( - new ButtonImpl("ree6RedirectButton", LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.download"), ButtonStyle.LINK, - BotConfig.getRecordingUrl() + "?id=" + recording.getIdentifier(), failedToUpload, Emoji.fromCustom("shiba", 941219375535509504L, true)), - Button.primary("r_recordingDownload:" + recording.getIdentifier(), Emoji.fromCustom("sip", 1011956355810209852L, false)) - .withLabel(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.sendToChat")).withDisabled(!BotConfig.allowRecordingInChat() || failedToUpload)).complete(); - - if (failedToUpload) { - audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", "Upload failed")).setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(recording).doOnError(x -> + audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", "Upload failed").block()).setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav"))) + .subscribe(newRecording -> { + if (canTalk) { + message.editMessageEmbeds(new EmbedBuilder() + .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopped").block()) + .setColor(BotConfig.getMainColor()) + .setFooter(BotConfig.getAdvertisement(), audioChannelUnion.getGuild().getIconUrl()) + .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.finished").block()) + .build()) + .setActionRow( + new ButtonImpl("ree6RedirectButton", LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.download").block(), ButtonStyle.LINK, + BotConfig.getRecordingUrl() + "?id=" + recording.getIdentifier(), true, Emoji.fromCustom("shiba", 941219375535509504L, true)), + Button.primary("r_recordingDownload:" + recording.getIdentifier(), Emoji.fromCustom("sip", 1011956355810209852L, false)) + .withLabel(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.sendToChat").block()).withDisabled(!BotConfig.allowRecordingInChat())).complete(); } - } + }); // Find a way to still notify that the bot couldn't send the audio. } catch (Exception ex) { if (canTalk) { message.editMessageEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", ex.getMessage())) + .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", ex.getMessage()).block()) .setColor(Color.RED) .setFooter(BotConfig.getAdvertisement(), audioChannelUnion.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.error")) + .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.error").block()) .build()).complete(); } diff --git a/src/main/java/de/presti/ree6/audio/music/MusicWorker.java b/src/main/java/de/presti/ree6/audio/music/MusicWorker.java index 7b369e39a..1dedc4f06 100644 --- a/src/main/java/de/presti/ree6/audio/music/MusicWorker.java +++ b/src/main/java/de/presti/ree6/audio/music/MusicWorker.java @@ -12,12 +12,12 @@ import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import de.presti.ree6.api.events.MusicPlayerStateChangeEvent; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.apis.SpotifyAPIHandler; import de.presti.ree6.utils.apis.YouTubeAPIHandler; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import dev.lavalink.youtube.YoutubeAudioSourceManager; import io.sentry.Sentry; @@ -185,10 +185,10 @@ public void loadAndPlay(final Guild guild, GuildMessageChannelUnion channel, Aud Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guild, "message.music.notPlaying")) + .setDescription(LanguageService.getByGuild(guild, "message.music.notPlaying").block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()) , channel, interactionHook); return; @@ -209,10 +209,10 @@ public void trackLoaded(AudioTrack track) { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setImage((track.getInfo().artworkUrl != null && track.getInfo().artworkUrl.isBlank()) ? guild.getJDA().getSelfUser().getEffectiveAvatarUrl() : track.getInfo().artworkUrl) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.default", FormatUtil.filter(track.getInfo().title))) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.default", FormatUtil.filter(track.getInfo().title)).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); play(finalAudioChannel, musicManager, track, force); @@ -234,10 +234,10 @@ public void playlistLoaded(AudioPlaylist playlist) { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.firstOfList", FormatUtil.filter(firstTrack.getInfo().title), FormatUtil.filter(playlist.getName()))) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.firstOfList", FormatUtil.filter(firstTrack.getInfo().title), FormatUtil.filter(playlist.getName())).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); play(finalAudioChannel, musicManager, firstTrack, force); @@ -259,10 +259,10 @@ public void noMatches() { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.searchUrlFailed", FormatUtil.filter(trackUrl))) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(guild, "message.music.searchUrlFailed", FormatUtil.filter(trackUrl)).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); } @@ -276,10 +276,10 @@ public void loadFailed(FriendlyException exception) { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.failedLoading", exception.getMessage())) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(guild, "message.music.failedLoading", exception.getMessage()).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); } }); @@ -369,10 +369,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer")) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", value)) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", value).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); return; @@ -406,10 +406,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer")) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFoundMultiple", loadFailed.size())) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFoundMultiple", loadFailed.size()).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); } @@ -422,10 +422,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann } catch (Exception exception) { EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer")) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.searchFailed")) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.searchFailed").block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); log.error("Error while searching for " + value + " on YouTube", exception); @@ -435,10 +435,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann if (ytResult == null) { EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer")) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.YELLOW) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", FormatUtil.filter(value))) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", FormatUtil.filter(value)).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); } else { @@ -469,10 +469,10 @@ public void skipTrack(GuildMessageChannelUnion channel, InteractionHook interact public void skipTrack(GuildMessageChannelUnion channel, InteractionHook interactionHook, int skipAmount, boolean silent) { if (!silent) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setAuthor(channel.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), channel.getJDA().getSelfUser().getAvatarUrl()) - .setTitle(LanguageService.getByGuild(channel.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(channel.getGuild(), "label.musicPlayer").block()) .setThumbnail(channel.getJDA().getSelfUser().getAvatarUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(channel.getGuild(), "message.music.skip")) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(channel.getGuild(), "message.music.skip").block()) .setFooter(channel.getGuild().getName() + " - " + BotConfig.getAdvertisement(), channel.getGuild().getIconUrl()), 5, channel, interactionHook); } @@ -483,10 +483,11 @@ public void skipTrack(GuildMessageChannelUnion channel, InteractionHook interact * A method used to seek to a specific position in the current AudioTrack. * * @param channel the TextChannel, used to inform the user about the seek. + * @param interactionHook the Interactionhook incase it was used in a slash command. * @param seekAmountInSeconds the number of seconds that should be seeked. */ - public void seekInTrack(GuildMessageChannelUnion channel, int seekAmountInSeconds) { - getGuildAudioPlayer(channel.getGuild()).getScheduler().seekPosition(channel, seekAmountInSeconds); + public void seekInTrack(GuildMessageChannelUnion channel, InteractionHook interactionHook, long seekAmountInSeconds) { + getGuildAudioPlayer(channel.getGuild()).getScheduler().seekPosition(channel, interactionHook, seekAmountInSeconds); } /** diff --git a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java index f09272014..da82f7345 100644 --- a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java +++ b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java @@ -5,9 +5,9 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason; import de.presti.ree6.api.events.MusicPlayerStateChangeEvent; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import lavalink.client.player.IPlayer; import lavalink.client.player.event.AudioEventAdapterWrapped; @@ -16,7 +16,6 @@ import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.channel.unions.GuildMessageChannelUnion; -import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion; import net.dv8tion.jda.api.interactions.InteractionHook; import java.awt.*; @@ -173,14 +172,13 @@ public void nextTrack(GuildMessageChannelUnion textChannel, int position, boolea } if (track != null) { - // TODO:: Really stupid workaround for https://github.com/Ree6-Applications/Ree6/issues/299! This should be rechecked later if it even worked. if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songNext", FormatUtil.filter(track.getInfo().title))) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songNext", FormatUtil.filter(track.getInfo().title)).block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); Main.getInstance().getEventBus().post(new MusicPlayerStateChangeEvent(guildMusicManager.getGuild(), MusicPlayerStateChangeEvent.State.PLAYING, track)); @@ -189,10 +187,10 @@ public void nextTrack(GuildMessageChannelUnion textChannel, int position, boolea if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songQueueReachedEnd")) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songQueueReachedEnd").block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); Main.getInstance().getEventBus().post(new MusicPlayerStateChangeEvent(guildMusicManager.getGuild(), MusicPlayerStateChangeEvent.State.QUEUE_EMPTY, null)); @@ -203,32 +201,33 @@ public void nextTrack(GuildMessageChannelUnion textChannel, int position, boolea * Seek to a specific position in the current track. * * @param channel the Text-Channel where the command have been performed from. + * @param interactionHook the Interactionhook if it was used in a slashcommand * @param seekAmountInSeconds the amount of seconds to seek to. */ - public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSeconds) { + public void seekPosition(GuildMessageChannelUnion channel, InteractionHook interactionHook, long seekAmountInSeconds) { if (player.getPlayingTrack() == null) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying")) - .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying").block()) + .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel(), interactionHook); return; } if (player.getPlayingTrack().getPosition() / 1000 + seekAmountInSeconds > player.getPlayingTrack().getDuration() / 1000) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.failed")) - .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.failed").block()) + .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel(), interactionHook); return; } - long skipPosition = player.getPlayingTrack().getPosition() + ((long) seekAmountInSeconds * 1000); + long skipPosition = player.getPlayingTrack().getPosition() + (seekAmountInSeconds * 1000); if (skipPosition < 0) { player.getPlayingTrack().setPosition(0L); } else { @@ -237,11 +236,11 @@ public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSecon Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.success", FormatUtil.formatTime(player.getPlayingTrack().getPosition()))) - .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.success", FormatUtil.formatTime(player.getPlayingTrack().getPosition())).block()) + .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel(), interactionHook); } @Override @@ -276,10 +275,10 @@ public void onTrackEnd(IPlayer player, AudioTrack track, AudioTrackEndReason end if (getChannel() != null) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), "Track does not exist (Internally?)")) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), "Track does not exist (Internally?)").block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); } @@ -292,10 +291,10 @@ public void onTrackEnd(IPlayer player, AudioTrack track, AudioTrackEndReason end if (getChannel() != null) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name())) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name()).block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); } @@ -313,10 +312,10 @@ public void onTrackEnd(IPlayer player, AudioTrack track, AudioTrackEndReason end Main.getInstance().getEventBus().post(new MusicPlayerStateChangeEvent(guildMusicManager.getGuild(), MusicPlayerStateChangeEvent.State.ERROR, null)); Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name())) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name()).block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); } nextTrack(getChannel(), track.getSourceManager() instanceof LocalAudioSourceManager); @@ -341,16 +340,16 @@ public void stopAll(InteractionHook interactionHook) { Main.getInstance().getMusicWorker().disconnect(guildMusicManager.getGuild()); em.setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")); + em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()); em.setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); - em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.stop")); + em.setColor(BotConfig.getMainColor()); + em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.stop").block()); } else { em.setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")); + em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()); em.setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); em.setColor(Color.RED); - em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying")); + em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying").block()); } em.setFooter(BotConfig.getAdvertisement()); diff --git a/src/main/java/de/presti/ree6/bot/BotConfig.java b/src/main/java/de/presti/ree6/bot/BotConfig.java index 34e33cf64..84654bf82 100644 --- a/src/main/java/de/presti/ree6/bot/BotConfig.java +++ b/src/main/java/de/presti/ree6/bot/BotConfig.java @@ -21,7 +21,7 @@ private BotConfig() { /** * Color values to be preset to prevent parsing hex codes from the config over and over and over and over and over again. */ - private static Color rankTextColor, rankDetailColor, rankHighlightColor, rankProgressbarColor, rankProgressbarBackgroundColor; + private static Color rankTextColor, rankDetailColor, rankHighlightColor, rankProgressbarColor, rankProgressbarBackgroundColor, mainColor; /** * Get the configured Discord Bot status. @@ -290,5 +290,16 @@ public static Color getRankProgressbarBackgroundColor() { } //endregion + + /** + * Get the configured color for the background of the progressbar on the rank card. + * @return the color for the background of the progressbar on the rank card from the config. + */ + public static Color getMainColor() { + if (mainColor == null) { + mainColor = Color.decode(Main.getInstance().getConfig().getConfiguration().getString("bot.misc.mainColor", "#B9010B")); + } + return mainColor; + } } diff --git a/src/main/java/de/presti/ree6/bot/BotWorker.java b/src/main/java/de/presti/ree6/bot/BotWorker.java index 1085a7f39..52ebde78d 100644 --- a/src/main/java/de/presti/ree6/bot/BotWorker.java +++ b/src/main/java/de/presti/ree6/bot/BotWorker.java @@ -240,7 +240,7 @@ public static BotVersion getVersion() { public static String getBuild() { if (build == null) { build = Objects.requireNonNullElse(Main.class.getPackage().getImplementationVersion(), - Objects.requireNonNullElse(gitVersion, "3.1.13")); + Objects.requireNonNullElse(gitVersion, "4.0.0")); } return build; } @@ -278,7 +278,10 @@ public static String getBranch() { * @return the repository. */ public static String getRepository() { - return gitRepository == null ? "https://github.com/Ree6-Applications/Ree6" : gitRepository; + if (gitRepository == null) { + gitRepository = "https://github.com/Ree6-Applications/Ree6"; + } + return gitRepository; } /** diff --git a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java index 5ceefd91f..e278e3581 100644 --- a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java +++ b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java @@ -3,9 +3,11 @@ import club.minnced.discord.webhook.WebhookClient; import club.minnced.discord.webhook.send.WebhookMessage; import de.presti.ree6.bot.BotWorker; -import de.presti.ree6.logger.LogMessage; import de.presti.ree6.main.Main; +import de.presti.ree6.module.logger.LogMessage; import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.ScheduledMessage; +import de.presti.ree6.sql.entities.Tickets; import de.presti.ree6.sql.entities.webhook.*; import de.presti.ree6.sql.entities.webhook.base.Webhook; import de.presti.ree6.sql.entities.webhook.base.WebhookSocial; @@ -34,9 +36,10 @@ private WebhookUtil() { * * @param message the MessageContent. * @param webhook the Webhook. + * @param typ the typ of the Webhook */ - public static void sendWebhook(WebhookMessage message, Webhook webhook) { - sendWebhook(null, message, webhook.getWebhookId(), webhook.getToken(), false); + public static void sendWebhook(WebhookMessage message, Webhook webhook, WebhookTyp typ) { + sendWebhook(null, message, webhook.getWebhookId(), webhook.getToken(), typ); } /** @@ -45,10 +48,10 @@ public static void sendWebhook(WebhookMessage message, Webhook webhook) { * @param loggerMessage the MessageContent, if it has been merged. * @param message the MessageContent. * @param webhook the Webhook. - * @param isLog is the Webhook Message a Log-Message? + * @param typ the typ of the Webhook */ - public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, Webhook webhook, boolean isLog) { - sendWebhook(loggerMessage, message, webhook.getWebhookId(), webhook.getToken(), isLog); + public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, Webhook webhook, WebhookTyp typ) { + sendWebhook(loggerMessage, message, webhook.getWebhookId(), webhook.getToken(), typ); } /** @@ -56,9 +59,10 @@ public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, * * @param message the MessageContent. * @param webhook the Webhook. + * @param typ the typ of the Webhook */ - public static void sendWebhook(WebhookMessage message, WebhookSocial webhook) { - sendWebhook(null, message, webhook.getWebhookId(), webhook.getToken(), false); + public static void sendWebhook(WebhookMessage message, WebhookSocial webhook, WebhookTyp typ) { + sendWebhook(null, message, webhook.getWebhookId(), webhook.getToken(), typ); } /** @@ -67,10 +71,10 @@ public static void sendWebhook(WebhookMessage message, WebhookSocial webhook) { * @param loggerMessage the MessageContent, if it has been merged. * @param message the MessageContent. * @param webhook the Webhook. - * @param isLog is the Webhook Message a Log-Message? + * @param typ the typ of the Webhook */ - public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, WebhookSocial webhook, boolean isLog) { - sendWebhook(loggerMessage, message, webhook.getWebhookId(), webhook.getToken(), isLog); + public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, WebhookSocial webhook, WebhookTyp typ) { + sendWebhook(loggerMessage, message, webhook.getWebhookId(), webhook.getToken(), typ); } @@ -81,120 +85,125 @@ public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, * @param message the MessageContent. * @param webhookId the ID of the Webhook. * @param webhookToken the Auth-Token of the Webhook. - * @param isLog is the Webhook Message a Log-Message? + * @param typ the typ of the Webhook */ - public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, long webhookId, String webhookToken, boolean isLog) { - Main.getInstance().logAnalytic("Received a Webhook to send. (Log-Typ: {})", isLog ? loggerMessage != null ? loggerMessage.getType().name() : "NONE-LOG" : "NONE-LOG"); + public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, long webhookId, String webhookToken, WebhookTyp typ) { + Main.getInstance().logAnalytic("Received a Webhook to send. (Log-Typ: {})", typ == WebhookTyp.LOG ? loggerMessage != null ? loggerMessage.getType().name() : "NONE-LOG" : "NONE-LOG"); // Check if the given data is valid. if (webhookToken.contains("Not setup!") || webhookId == 0) return; // Check if the given data is in the Database. - if (isLog && !SQLSession.getSqlConnector().getSqlWorker().existsLogData(webhookId, webhookToken)) return; + if (typ == WebhookTyp.LOG) { + SQLSession.getSqlConnector().getSqlWorker().existsLogData(webhookId, webhookToken).subscribe(x -> { + if (!x) { + // If not, inform about invalid send. + log.error("[Webhook] Invalid Webhook: {} - {}", webhookId, webhookToken); + } else { + // Check if the LoggerMessage is canceled. + if ((loggerMessage == null || loggerMessage.isCanceled())) { + // If so, inform about invalid send. + log.error("[Webhook] Got a Invalid or canceled LoggerMessage!"); + return; + } - // Check if the LoggerMessage is canceled. - if (isLog && (loggerMessage == null || loggerMessage.isCanceled())) { - // If so, inform about invalid send. - log.error("[Webhook] Got a Invalid or canceled LoggerMessage!"); - return; + sendWebhookMessage(loggerMessage, message, webhookId, webhookToken, typ); + } + }); + } else { + sendWebhookMessage(loggerMessage, message, webhookId, webhookToken, typ); } + } + private static void sendWebhookMessage(LogMessage loggerMessage, WebhookMessage message, long webhookId, String webhookToken, WebhookTyp typ) { // Try sending a Webhook to the given data. try (WebhookClient wcl = WebhookClient.withId(webhookId, webhookToken)) { // Send the message and handle exceptions. wcl.send(message).exceptionally(throwable -> { // If error 404 comes, that means that the webhook is invalid. if (throwable.getMessage().contains("failure 404")) { - // Inform and delete invalid webhook. - if (isLog) { - SQLSession.getSqlConnector().getSqlWorker().deleteLogWebhook(webhookId, webhookToken); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - } else { - boolean deleted = false; - - // TODO:: find a better way, because this is getting ridiculously long. - - WebhookWelcome welcome = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookWelcome(), "FROM WebhookWelcome WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - if (welcome != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(welcome); - deleted = true; - } - - WebhookYouTube webhookYouTube = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookYouTube(), "FROM WebhookYouTube WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookYouTube != null && !deleted) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookYouTube); - deleted = true; - } - - if (!deleted) { - WebhookTwitter webhookTwitter = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitter(), "FROM WebhookTwitter WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookTwitter != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitter); - deleted = true; - } - } - - if (!deleted) { - WebhookTwitch webhookTwitch = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitch(), "FROM WebhookTwitch WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookTwitch != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitch); - deleted = true; - } - } - - if (!deleted) { - WebhookReddit webhookReddit = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookReddit(), "FROM WebhookReddit WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookReddit != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookReddit); - deleted = true; - } - } - - if (!deleted) { - WebhookInstagram webhookInstagram = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookInstagram(), "FROM WebhookInstagram WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookInstagram != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookInstagram); - deleted = true; - } - } - - if (!deleted) { - WebhookTikTok webhookTikTok = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTikTok(), "FROM WebhookTikTok WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookTikTok != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTikTok); - deleted = true; - } - } - - if (!deleted) { - RSSFeed webhookRss = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new RSSFeed(), "FROM RSSFeed WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookRss != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookRss); - deleted = true; - } - } - - if (deleted) { - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - } else { - log.error("[Webhook] Invalid Webhook: {} - {}, has not been deleted since we couldn't find the correct typ. (Most likely a Ticket Webhook!)", webhookId, webhookToken); - } + switch (typ) { + case LOG -> + SQLSession.getSqlConnector().getSqlWorker().deleteLogWebhook(webhookId, webhookToken); + + case WELCOME -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookWelcome(), "FROM WebhookWelcome WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case YOUTUBE -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookYouTube(), "FROM WebhookYouTube WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case TWITTER -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitter(), "FROM WebhookTwitter WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case TWITCH -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitch(), "FROM WebhookTwitch WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case REDDIT -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookReddit(), "FROM WebhookReddit WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case SPOTIFY -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookSpotify(), "FROM WebhookSpotify WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case TIKTOK -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTikTok(), "FROM WebhookTikTok WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case INSTAGRAM -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookInstagram(), "FROM WebhookInstagram WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case RSS -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new RSSFeed(), "FROM RSSFeed WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case SCHEDULE -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ScheduledMessage(), "FROM ScheduledMessage WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case TICKET -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE logChannelWebhookId = :cid AND logChannelWebhookToken = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); } + log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else if (throwable.getMessage().contains("failure 400")) { // If 404 inform that the Message had an invalid Body. log.error("[Webhook] Invalid Body with LogTyp: {}", loggerMessage.getType().name()); @@ -227,4 +236,8 @@ public static void deleteWebhook(long guildId, Webhook webhookEntity) { .forEach(webhook -> webhook.delete().queue())); } } + + public enum WebhookTyp { + LOG, WELCOME, TIKTOK, SPOTIFY, YOUTUBE, REDDIT, TWITCH, TWITTER, INSTAGRAM, RSS, SCHEDULE, TICKET + } } \ No newline at end of file diff --git a/src/main/java/de/presti/ree6/bot/version/BotVersion.java b/src/main/java/de/presti/ree6/bot/version/BotVersion.java index 1639be0f0..e66f9e432 100644 --- a/src/main/java/de/presti/ree6/bot/version/BotVersion.java +++ b/src/main/java/de/presti/ree6/bot/version/BotVersion.java @@ -13,19 +13,28 @@ public enum BotVersion { /** * Version for Development tests. */ - DEVELOPMENT("bot.tokens.dev"), + DEVELOPMENT("Dev","bot.tokens.dev"), /** * Version for a not yet fully stable release. */ - BETA("bot.tokens.beta"), + BETA("Beta", "bot.tokens.beta"), /** * Version for a stable release. */ - RELEASE("bot.tokens.release"); + RELEASE("Release", "bot.tokens.release"); + + /** + * The name of the Version. + */ + final String name; /** * The Token-Path in the config file. */ final String tokenPath; + @Override + public String toString() { + return name; + } } diff --git a/src/main/java/de/presti/ree6/commands/Category.java b/src/main/java/de/presti/ree6/commands/Category.java index b8de7dd43..6405c8a17 100644 --- a/src/main/java/de/presti/ree6/commands/Category.java +++ b/src/main/java/de/presti/ree6/commands/Category.java @@ -1,46 +1,49 @@ package de.presti.ree6.commands; +import lombok.Getter; + /** * Different Categories for the commands. */ +@Getter public enum Category { /** - * Category used for informativ Commands. + * Category used for information Commands. */ - INFO("re_icon_info", 1019221661070917632L, false, "category.info"), + INFO("re_icon_info", 1019221661070917632L, false, "category.info", true), /** - * Category used for moderativ Commands. + * Category used for moderate Commands. */ - MOD("re_icon_mod", 1019221710932803624L, false, "category.moderation"), + MOD("re_icon_mod", 1019221710932803624L, false, "category.moderation", true), /** * Category used for music Commands. */ - MUSIC("re_icon_music", 1019221781762023575L, false, "category.music"), + MUSIC("re_icon_music", 1019221781762023575L, false, "category.music", true), /** * Category used for fun Commands. */ - FUN("re_icon_fun", 1019221814670532628L, false, "category.fun"), + FUN("re_icon_fun", 1019221814670532628L, false, "category.fun", false), /** * Category used for level Commands. */ - LEVEL("re_icon_level", 1019221845972635809L, false, "category.level"), + LEVEL("re_icon_level", 1019221845972635809L, false, "category.level", true), /** * Category used for community Commands. */ - COMMUNITY("re_icon_community", 1019221884686057552L, false, "category.community"), + COMMUNITY("re_icon_community", 1019221884686057552L, false, "category.community", true), /** * Category used for economy Commands. */ - ECONOMY("re_icon_economy", 0L, false, "category.economy"), + ECONOMY("re_icon_economy", 0L, false, "category.economy", true), /** * Category used for NSFW Commands. */ - NSFW("re_icon_nsfw", 1019221923466584166L, false, "category.nsfw"), + NSFW("re_icon_nsfw", 1019221923466584166L, false, "category.nsfw", false), /** * Category used for admin Commands. */ - HIDDEN("re_icon_hidden", 1019221957817933865L, false, "category.hidden"); + HIDDEN("re_icon_hidden", 1019221957817933865L, false, "category.hidden", true); /** * The Name of the Icon. @@ -62,6 +65,11 @@ public enum Category { */ private final String description; + /** + * Value for knowledge about the Command being Guild only or not. + */ + private final boolean guildOnly; + /** * Constructor. * @@ -69,47 +77,13 @@ public enum Category { * @param iconId the Icon ID. * @param iconAnimated the info if the Icon is animated. * @param description a short description. + * @param guildOnly the info if the Command is Guild only. */ - Category(String icon, long iconId, boolean iconAnimated, String description) { + Category(String icon, long iconId, boolean iconAnimated, String description, boolean guildOnly) { this.icon = icon; this.iconId = iconId; this.iconAnimated = iconAnimated; this.description = description; - } - - /** - * The Icon Name for the Category. - * - * @return the Name. - */ - public String getIcon() { - return icon; - } - - /** - * The Icon ID for the Category. - * - * @return the Icon ID. - */ - public long getIconId() { - return iconId; - } - - /** - * The Information if the Icon is animated. - * - * @return true, if yes | false, if not. - */ - public boolean isIconAnimated() { - return iconAnimated; - } - - /** - * Short description of the Category. - * - * @return the short description. - */ - public String getDescription() { - return description; + this.guildOnly = guildOnly; } } diff --git a/src/main/java/de/presti/ree6/commands/CommandEvent.java b/src/main/java/de/presti/ree6/commands/CommandEvent.java index 6c0118114..bd9141a20 100644 --- a/src/main/java/de/presti/ree6/commands/CommandEvent.java +++ b/src/main/java/de/presti/ree6/commands/CommandEvent.java @@ -1,12 +1,13 @@ package de.presti.ree6.commands; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import lombok.Getter; +import lombok.extern.java.Log; import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.entities.channel.unions.GuildMessageChannelUnion; -import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -20,6 +21,7 @@ /** * Event class used to parse and provide Information about a command execution. */ +@Log public class CommandEvent { /** @@ -75,7 +77,7 @@ public class CommandEvent { * @param arguments the given Arguments. * @param slashCommandInteractionEvent the {@link SlashCommandInteractionEvent} Entity. */ - public CommandEvent(String command, @Nonnull Member member, @Nonnull Guild guild, @Nullable Message message, @Nonnull GuildMessageChannelUnion textChannel, @Nullable String[] arguments, @Nullable SlashCommandInteractionEvent slashCommandInteractionEvent) { + public CommandEvent(String command, @Nonnull Member member, @Nonnull Guild guild, @Nullable Message message, @Nonnull GuildMessageChannelUnion textChannel, @Nullable String[] arguments, @Nullable SlashCommandInteractionEvent slashCommandInteractionEvent, boolean isEphermal) { this.command = command; this.member = member; this.guild = guild; @@ -83,6 +85,7 @@ public CommandEvent(String command, @Nonnull Member member, @Nonnull Guild guild this.channel = textChannel; this.arguments = arguments; this.slashCommandInteractionEvent = slashCommandInteractionEvent; + setEphemeral(isEphermal); } /** @@ -152,7 +155,8 @@ public void reply(MessageCreateData message, int deleteSecond) { /** * Update a Message that has been sent. - * @param message the Message that has been sent. + * + * @param message the Message that has been sent. * @param messageEditData the Message Edit that is being used to update the message. */ public void update(@Nullable Message message, MessageEditData messageEditData) { @@ -167,6 +171,7 @@ public void update(@Nullable Message message, MessageEditData messageEditData) { /** * If the message default should be ephemeral or not. + * * @param ephemeral if the message should be ephemeral. */ public void setEphemeral(boolean ephemeral) { @@ -175,6 +180,13 @@ public void setEphemeral(boolean ephemeral) { } } + /** + * Delete the Message that has been sent. + */ + public void delete() { + Main.getInstance().getCommandManager().deleteMessageWithoutException(message, getInteractionHook()); + } + /** * Get a Message from the Guild specific Language Setting. * @@ -183,7 +195,7 @@ public void setEphemeral(boolean ephemeral) { * @return the Message. */ public String getResource(String key, Object... parameters) { - return LanguageService.getByEvent(this, key, parameters); + return LanguageService.getByEvent(this, key, parameters).block(); } /** @@ -208,6 +220,22 @@ public String getResource(String key, Object... parameters) { return member; } + /** + * Check if the Member is the Bot Owner. + * @return true, if the Member is the Bot Owner. | false, if not. + */ + public boolean isBotOwner() { + return BotConfig.getBotOwner().equals(member.getId()); + } + + /** + * Check if the command event is run via App-Command. + * @return true, if it has been run via App-Command. + */ + public boolean isDetached() { + return getGuild().isDetached(); + } + /** * Get the {@link Guild} Entity associated with the Event. * @@ -249,7 +277,6 @@ public String[] getArguments() { * Get the Arguments associated with the Event. * * @param parseFromSlash if the Arguments should be parsed from the SlashCommandInteractionEvent. - * * @return the Arguments. */ public String[] getArguments(boolean parseFromSlash) { @@ -280,6 +307,7 @@ public String[] getArguments(boolean parseFromSlash) { /** * Get an option from the slash command! + * * @param name The option name. * @return the {@link OptionMapping} of the option | or null. */ @@ -291,6 +319,7 @@ public String[] getArguments(boolean parseFromSlash) { /** * Get the Subcommand of the Slash Command. + * * @return the Subcommand. */ public String getSubcommand() { @@ -303,6 +332,7 @@ public String getSubcommand() { /** * Get the Subcommand Group of the Slash Command. + * * @return the Subcommand Group. */ public String getSubcommandGroup() { @@ -328,7 +358,7 @@ public boolean isSlashCommand() { * @return the {@link InteractionHook} Entity. */ public InteractionHook getInteractionHook() { - if (isSlashCommand()) return getSlashCommandInteractionEvent().getHook().setEphemeral(true); + if (isSlashCommand()) return getSlashCommandInteractionEvent().getHook(); return null; } diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index 3894e4b59..6e25160b6 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -1,5 +1,6 @@ package de.presti.ree6.commands; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.exceptions.CommandInitializerException; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; @@ -10,7 +11,7 @@ import de.presti.ree6.sql.entities.custom.CustomCommand; import de.presti.ree6.sql.util.SettingsManager; import de.presti.ree6.utils.data.ArrayUtil; -import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.utils.data.RegExUtil; import de.presti.ree6.utils.others.ThreadUtil; import lombok.AccessLevel; import lombok.Getter; @@ -24,9 +25,10 @@ import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; import net.dv8tion.jda.api.entities.channel.unions.GuildMessageChannelUnion; -import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.DiscordLocale; +import net.dv8tion.jda.api.interactions.IntegrationType; +import net.dv8tion.jda.api.interactions.InteractionContextType; import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -39,6 +41,8 @@ import net.dv8tion.jda.api.utils.messages.MessageCreateData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; import org.reflections.Reflections; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; import java.lang.reflect.InvocationTargetException; import java.time.Duration; @@ -208,35 +212,47 @@ public void addSlashCommand(JDA jda) { commandData.setNSFW(true); } + if (commandAnnotation.category().isGuildOnly()) { + commandData.setIntegrationTypes(IntegrationType.GUILD_INSTALL); + } else { + if (commandAnnotation.allowAppInstall()) { + commandData.setIntegrationTypes(IntegrationType.ALL); + } else { + commandData.setIntegrationTypes(IntegrationType.GUILD_INSTALL); + } + } + if (commandData instanceof CommandDataImpl commandData1) { + boolean isValidDescription = commandAnnotation.description().matches(RegExUtil.ALLOWED_LANGUAGE_PATHS); + for (DiscordLocale discordLocale : DiscordLocale.values()) { if (!LanguageService.languageResources.containsKey(discordLocale)) continue; - if (commandAnnotation.description().endsWith(".") || !commandAnnotation.description().contains(".")) + if (!isValidDescription) continue; - String description = LanguageService.getByLocale(discordLocale, commandAnnotation.description()); + String localizedDescription = LanguageService.getByLocale(discordLocale, commandAnnotation.description()).block(); - if (description.equals("Missing language resource!")) { - description = LanguageService.getDefault(commandAnnotation.description()); + if (localizedDescription != null && localizedDescription.equals("Missing language resource!")) { + localizedDescription = LanguageService.getDefault(commandAnnotation.description()).block(); } - if (!description.equals("Missing language resource!")) { - commandData1.setDescriptionLocalization(discordLocale, description); + if (localizedDescription != null && !localizedDescription.equals("Missing language resource!")) { + commandData1.setDescriptionLocalization(discordLocale, localizedDescription); } commandData1.getSubcommandGroups().forEach(subcommandGroupData -> translateSubgroups(subcommandGroupData, discordLocale)); } - String description = LanguageService.getDefault(commandAnnotation.description()); + if (isValidDescription) { + String localizedDescription = LanguageService.getDefault(commandAnnotation.description()).block(); - if (!description.equals("Missing language resource!")) { - commandData1.setDescription(description); + if (localizedDescription != null && !localizedDescription.equals("Missing language resource!")) { + commandData1.setDescription(localizedDescription); + } } - // TODO:: add the same language check to option names/description and add a translation to it. Also for the love of god Imma need to optimize this. - if (commandAnnotation.category() == Category.MOD && commandData.getDefaultPermissions() == DefaultMemberPermissions.ENABLED) { commandData1.setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.ADMINISTRATOR)); } @@ -250,7 +266,7 @@ public void addSlashCommand(JDA jda) { commandData.setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.ADMINISTRATOR)); } - commandData.setGuildOnly(true); + commandData.setContexts(InteractionContextType.GUILD); //noinspection ResultOfMethodCallIgnored listUpdateAction.addCommands(commandData); @@ -260,35 +276,67 @@ public void addSlashCommand(JDA jda) { listUpdateAction.queue(); } - public void translateSubgroups(SubcommandGroupData subcommandGroupData, DiscordLocale locale) { + private void translateSubgroups(SubcommandGroupData subcommandGroupData, DiscordLocale locale) { String groupDescription = subcommandGroupData.getDescription(); - if (groupDescription.contains(".") && !groupDescription.endsWith(".")) { - groupDescription = LanguageService.getByLocale(locale, groupDescription); - - if (groupDescription.equals("Missing language resource!")) { - groupDescription = LanguageService.getDefault(subcommandGroupData.getDescription()); + if (groupDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { + if (LanguageService.hasTranslation(locale, groupDescription).block()) { + groupDescription = LanguageService.getByLocale(locale, groupDescription).block(); + } else if (LanguageService.hasDefaultTranslation(groupDescription).block()) { + groupDescription = LanguageService.getDefault(groupDescription).block(); } - if (!groupDescription.equals("Missing language resource!")) { - subcommandGroupData.setDescriptionLocalization(locale, groupDescription); - } + subcommandGroupData.setDescriptionLocalization(locale, groupDescription); } + // Translate Subcommands for (SubcommandData subcommandData : subcommandGroupData.getSubcommands()) { - String commandDescription = subcommandData.getDescription(); + translateSubcomand(subcommandData, locale); + } + } - if (commandDescription.contains(".") && !commandDescription.endsWith(".")) { - commandDescription = LanguageService.getByLocale(locale, commandDescription); + private void translateSubcomand(SubcommandData subcommandData, DiscordLocale locale) { + String commandDescription = subcommandData.getDescription(); - if (commandDescription.equals("Missing language resource!")) { - commandDescription = LanguageService.getDefault(subcommandData.getDescription()); - } + if (commandDescription != null && commandDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { + if (LanguageService.hasTranslation(locale, commandDescription).block()) { + commandDescription = LanguageService.getByLocale(locale, commandDescription).block(); + } else if (LanguageService.hasDefaultTranslation(commandDescription).block()) { + commandDescription = LanguageService.getDefault(commandDescription).block(); + } - if (!commandDescription.equals("Missing language resource!")) { - subcommandData.setDescriptionLocalization(locale, commandDescription); - } + subcommandData.setDescriptionLocalization(locale, commandDescription); + } + + // Translate Options + for (OptionData optionData : subcommandData.getOptions()) { + translateOption(optionData, locale); + } + } + + private void translateOption(OptionData optionData, DiscordLocale locale) { + // Name translation + String optionName = optionData.getName(); + if (optionName != null && optionName.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { + if (LanguageService.hasTranslation(locale, optionName).block()) { + optionName = LanguageService.getByLocale(locale, optionName).block(); + } else if (LanguageService.hasDefaultTranslation(optionName).block()) { + optionName = LanguageService.getDefault(optionName).block(); + } + + optionData.setNameLocalization(locale, optionName); + } + + // Description translation + String optionDescription = optionData.getDescription(); + if (optionDescription != null && optionDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { + if (LanguageService.hasTranslation(locale, optionDescription).block()) { + optionDescription = LanguageService.getByLocale(locale, optionDescription).block(); + } else if (LanguageService.hasDefaultTranslation(optionDescription).block()) { + optionDescription = LanguageService.getDefault(optionDescription).block(); } + + optionData.setDescriptionLocalization(locale, optionDescription); } } @@ -322,7 +370,8 @@ public void addCommand(ICommand command) throws CommandInitializerException { * @return the {@link ICommand} with the same Name. */ public ICommand getCommandByName(String name) { - return getCommands().stream().filter(command -> command.getClass().getAnnotation(Command.class).name().equalsIgnoreCase(name) || Arrays.stream(command.getAlias()).anyMatch(s -> s.equalsIgnoreCase(name))).findFirst().orElse(null); + return getCommands().stream().filter(command -> command.getClass().getAnnotation(Command.class).name().equalsIgnoreCase(name) || + Arrays.stream(command.getAlias()).anyMatch(s -> s.equalsIgnoreCase(name))).findFirst().orElse(null); } @@ -333,7 +382,8 @@ public ICommand getCommandByName(String name) { * @return the {@link ICommand} with the same Name. */ public ICommand getCommandBySlashName(String name) { - return getCommands().stream().filter(command -> (command.getCommandData() != null && command.getCommandData().getName().equalsIgnoreCase(name)) || (command.getClass().isAnnotationPresent(Command.class) && command.getClass().getAnnotation(Command.class).name().equalsIgnoreCase(name))).findFirst().orElse(null); + return getCommands().stream().filter(command -> (command.getCommandData() != null && command.getCommandData().getName().equalsIgnoreCase(name)) || + (command.getClass().isAnnotationPresent(Command.class) && command.getClass().getAnnotation(Command.class).name().equalsIgnoreCase(name))).findFirst().orElse(null); } /** @@ -357,52 +407,66 @@ public void removeCommand(ICommand command) { * @param slashCommandInteractionEvent the Slash Command Event if it was a Slash Command. * @return true, if a command has been performed. */ - public boolean perform(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { + public Mono perform(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { + boolean isSlashCommand = slashCommandInteractionEvent != null; + + if (!isSlashCommand && guild.isDetached()) { + return Mono.just(false); + } + + if (BotConfig.isDebug()) + log.info("Called perform"); + // Check if the User is under Cooldown. if (isTimeout(member.getUser())) { // Check if it is a Slash Command or not. - if (slashCommandInteractionEvent != null) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown"), 5, messageChannel, slashCommandInteractionEvent.getHook().setEphemeral(true)); - deleteMessage(message, slashCommandInteractionEvent.getHook().setEphemeral(true)); - } else if (messageContent.toLowerCase().startsWith(SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").getStringValue().toLowerCase())) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown"), 5, messageChannel, null); - deleteMessage(message, null); - } + if (isSlashCommand) { + return LanguageService.getByGuild(guild, "command.perform.cooldown").map(messageCreateData -> { + slashCommandInteractionEvent.getHook().sendMessage(messageCreateData).queue(); + deleteMessage(message, slashCommandInteractionEvent.getHook().setEphemeral(true)); + return false; + }); + } else { + return SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").publishOn(Schedulers.boundedElastic()).mapNotNull(setting -> { + if (setting.isPresent() && messageContent.toLowerCase().startsWith(setting.get().getStringValue().toLowerCase())) { + final Mono booleanMono = LanguageService.getByGuild(guild, "command.perform.cooldown").map(translation -> { + sendMessage(String.valueOf(translation), 5, messageChannel, null); + deleteMessage(message, null); + return false; + }).thenReturn(false); + return booleanMono.block(); + } - // Return false. - return false; + return false; + }); + } } // Check if it is a Slash Command. - if (slashCommandInteractionEvent != null) { - if (!BotConfig.isModuleActive("slashcommands")) return false; - if (!performSlashCommand(messageChannel, slashCommandInteractionEvent)) { - return false; - } + if (isSlashCommand) { + if (!BotConfig.isModuleActive("slashcommands")) return Mono.just(false); + return performSlashCommand(messageChannel, slashCommandInteractionEvent); } else { - if (!BotConfig.isModuleActive("messagecommands")) return false; - if (!performMessageCommand(member, guild, messageContent, message, messageChannel)) { - return false; - } + if (!BotConfig.isModuleActive("messagecommands")) return Mono.just(false); + return performMessageCommand(member, guild, messageContent, message, messageChannel); } + } + public void timeoutUser(User user) { // Check if this is a Developer build, if not then cooldown the User. - if (!BotConfig.isDebug()) { - ThreadUtil.createThread(x -> ArrayUtil.commandCooldown.remove(member.getUser().getId()), null, Duration.ofSeconds(5), false, false); - } + if (!BotConfig.isDebug()) return; + + ThreadUtil.createThread(x -> ArrayUtil.commandCooldown.remove(user.getId()), null, Duration.ofSeconds(5), false, false); // Add them to the Cooldown. - if (!ArrayUtil.commandCooldown.contains(member.getUser().getId()) && !BotConfig.isDebug()) { - ArrayUtil.commandCooldown.add(member.getUser().getId()); + if (!ArrayUtil.commandCooldown.contains(user.getId())) { + ArrayUtil.commandCooldown.add(user.getId()); } - - // Return that a command has been performed. - return true; } /** - * Perform a Message based Command. + * Perform a Message-based Command. * * @param member the Member that performed the command. * @param guild the Guild the Member is from. @@ -411,79 +475,121 @@ public boolean perform(Member member, Guild guild, String messageContent, Messag * @param textChannel the TextChannel where the command has been performed. * @return true, if a command has been performed. */ - private boolean performMessageCommand(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion textChannel) { + private Mono performMessageCommand(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion textChannel) { // Check if the Message is null. if (message == null) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.error"), 5, textChannel, null); - return false; + if (BotConfig.isDebug()) + log.info("Message is null."); + sendMessage(LanguageService.getByGuild(guild, "command.perform.error").block(), 5, textChannel, null); + return Mono.just(false); } - String currentPrefix = SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").getStringValue().toLowerCase(); + if (BotConfig.isDebug()) + log.info("Called performMessageCommand"); - // Check if the message starts with the prefix. - if (!messageContent.toLowerCase().startsWith(currentPrefix)) - return false; + return SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").publishOn(Schedulers.boundedElastic()).mapNotNull(setting -> { - // Parse the Message and remove the prefix from it. - messageContent = messageContent.substring(currentPrefix.length()); + if (BotConfig.isDebug()) + log.info("Got to prefix check."); - // Split all Arguments. - String[] arguments = messageContent.split("\\s+"); - - if (arguments.length == 0 || arguments[0].isBlank()) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.missingCommand"), 5, textChannel, null); - return false; - } + String currentPrefix = setting.orElseGet(() -> new Setting(-1, "chatprefix", "Chat Prefix", BotConfig.getDefaultPrefix())).getStringValue(); - // Get the Command by the name. - ICommand command = getCommandByName(arguments[0]); - - // Check if there is even a Command with that name. - if (command == null && BotConfig.isModuleActive("customcommands")) { - CustomCommand customCommand = SQLSession.getSqlConnector().getSqlWorker().getEntity(new CustomCommand(), "FROM CustomCommand WHERE guildId=:gid AND name=:command", Map.of("gid", guild.getIdLong(), "command", arguments[0].toLowerCase())); - if (customCommand != null) { - GuildMessageChannelUnion messageChannelUnion = textChannel; - - if (customCommand.getChannelId() != -1) { - messageChannelUnion = guild.getChannelById(GuildMessageChannelUnion.class, customCommand.getChannelId()); - } + // Check if the message starts with the prefix. + if (!messageContent.toLowerCase().startsWith(currentPrefix)) { + if (BotConfig.isDebug()) + log.info("Wrong prefix"); + return false; + } - if (customCommand.getMessageResponse() != null) { - sendMessage(customCommand.getMessageResponse(), 5, messageChannelUnion, null); - } + // Split all Arguments. + String[] arguments = messageContent.substring(currentPrefix.length()).split("\\s+"); - if (customCommand.getEmbedResponse() != null) { - EmbedBuilder embedBuilder = EmbedBuilder.fromData(DataObject.fromJson(customCommand.getEmbedResponse().toString())); - sendMessage(embedBuilder, 5, messageChannelUnion, null); - } + if (arguments.length == 0 || arguments[0].isBlank()) { + return LanguageService.getByGuild(guild, "command.perform.missingCommand").map(translated -> { + sendMessage(translated, 5, textChannel, null); + if (BotConfig.isDebug()) + log.info("Missing command from string."); + return false; + }).block(); + } - return true; + if (BotConfig.isDebug()) + log.info("Passed parsing."); + + // Get the Command by the name. + ICommand command = getCommandByName(arguments[0]); + + // Check if there is even a Command with that name. + if (command == null && BotConfig.isModuleActive("customcommands")) { + return SQLSession.getSqlConnector().getSqlWorker().getEntity(new CustomCommand(), "FROM CustomCommand WHERE guildId=:gid AND name=:command", + Map.of("gid", guild.getIdLong(), "command", arguments[0].toLowerCase())) + .flatMap(customCommand -> { + if (BotConfig.isDebug()) + log.info("Got custom command."); + + if (customCommand.isPresent()) { + if (BotConfig.isDebug()) + log.info("Custom command is present."); + GuildMessageChannelUnion messageChannelUnion = textChannel; + CustomCommand customCommandEntity = customCommand.get(); + if (customCommandEntity.getChannelId() != -1) { + messageChannelUnion = guild.getChannelById(GuildMessageChannelUnion.class, customCommandEntity.getChannelId()); + } + + if (customCommandEntity.getMessageResponse() != null) { + sendMessage(customCommandEntity.getMessageResponse(), 5, messageChannelUnion, null); + } + + if (customCommandEntity.getEmbedResponse() != null) { + EmbedBuilder embedBuilder = EmbedBuilder.fromData(DataObject.fromJson(customCommandEntity.getEmbedResponse().toString())); + sendMessage(embedBuilder, 5, messageChannelUnion, null); + } + + return Mono.just(true); + } + + if (BotConfig.isDebug()) + log.info("Custom command is not present."); + + return LanguageService.getByGuild(guild, "command.perform.notFound").map(translated -> { + sendMessage(translated, 5, textChannel, null); + return false; + }); + }).block(); + } else if (command == null) { + return LanguageService.getByGuild(guild, "command.perform.notFound").map(translated -> { + sendMessage(translated, 5, textChannel, null); + return false; + }).block(); } - sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound"), 5, textChannel, null); - return false; - } else if (command == null) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound"), 5, textChannel, null); - return false; - } + if (BotConfig.isDebug()) + log.info("Finished command check."); - if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN) { - Setting blacklistSetting = SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()); + Command commandAnnotation = command.getClass().getAnnotation(Command.class); - // Check if the Command is blacklisted. - if (blacklistSetting != null && !blacklistSetting.getBooleanValue()) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.blocked"), 5, textChannel, null); - return false; + if (commandAnnotation.category() != Category.HIDDEN) { + Optional blacklist = SQLSession.getSqlConnector().getSqlWorker() + .getSetting(guild.getIdLong(), "command_" + commandAnnotation.name().toLowerCase()).block(); + + // Check if the Command is blacklisted. + if (blacklist != null && blacklist.isPresent() && !blacklist.get().getBooleanValue()) { + return LanguageService.getByGuild(guild, "command.perform.blocked").map(translated -> { + sendMessage(translated, 5, textChannel, null); + return false; + }).block(); + } } - } - // Parse the arguments. - String[] argumentsParsed = Arrays.copyOfRange(arguments, 1, arguments.length); + if (BotConfig.isDebug()) + log.info("Finished blacklist."); - // Perform the Command. - command.onASyncPerform(new CommandEvent(command.getClass().getAnnotation(Command.class).name(), member, guild, message, textChannel, argumentsParsed, null)); + // Parse the arguments. + String[] argumentsParsed = Arrays.copyOfRange(arguments, 1, arguments.length); - return true; + // Perform the Command. + return command.onMonoPerform(new CommandEvent(commandAnnotation.name(), member, guild, message, textChannel, argumentsParsed, null, true)).block(); + }); } /** @@ -493,30 +599,37 @@ private boolean performMessageCommand(Member member, Guild guild, String message * @param slashCommandInteractionEvent the Slash-Command Event. * @return true, if a command has been performed. */ - private boolean performSlashCommand(GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { + private Mono performSlashCommand(GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { //Get the Command by the Slash Command Name. ICommand command = getCommandBySlashName(slashCommandInteractionEvent.getName()); // Check if there is a command with that Name. if (command == null || slashCommandInteractionEvent.getGuild() == null || slashCommandInteractionEvent.getMember() == null) { - sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.notFound"), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); - return false; + sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.notFound").block(), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); + return Mono.just(false); } - if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN) { - Setting blacklistSetting = SQLSession.getSqlConnector().getSqlWorker().getSetting(slashCommandInteractionEvent.getGuild().getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()); + Command annotation = command.getClass().getAnnotation(Command.class); - // Check if the Command is blacklisted. - if (blacklistSetting != null && !blacklistSetting.getBooleanValue()) { - sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.blocked"), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); - return false; - } - } + Guild guild = slashCommandInteractionEvent.getGuild(); + + if (!annotation.allowAppInstall() && guild.isDetached()) return Mono.just(false); - // Perform the Command. - command.onASyncPerform(new CommandEvent(command.getClass().getAnnotation(Command.class).name(), slashCommandInteractionEvent.getMember(), slashCommandInteractionEvent.getGuild(), null, messageChannel, null, slashCommandInteractionEvent)); + CommandEvent commandEvent = new CommandEvent(annotation.name(), slashCommandInteractionEvent.getMember(), guild, null, messageChannel, null, slashCommandInteractionEvent, true); - return true; + if (guild.isDetached()) { + return command.onMonoPerform(commandEvent); + } else { + return SQLSession.getSqlConnector().getSqlWorker().getSetting(slashCommandInteractionEvent.getGuild().getIdLong(), "command_" + annotation.name().toLowerCase()).publishOn(Schedulers.boundedElastic()).mapNotNull(setting -> { + if (annotation.category() != Category.HIDDEN && setting.isPresent() && !setting.get().getBooleanValue()) { + sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.blocked").block(), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); + return false; + } + + // Perform the Command. + return command.onMonoPerform(commandEvent).block(); + }); + } } /** @@ -608,6 +721,50 @@ public void sendMessage(MessageCreateData messageCreateData, int deleteSecond, M } } + /** + * Send a message to a special Message-Channel. + * + * @param message the Message content as {@link Mono}. + * @param messageChannel the Message-Channel. + */ + public void sendMessage(Mono message, MessageChannel messageChannel) { + message.subscribe(s -> sendMessage(s, messageChannel)); + } + + /** + * Send a message to a special Message-Channel, with a deletion delay. + * + * @param message the Message content as {@link Mono}. + * @param deleteSecond the delete delay + * @param messageChannel the Message-Channel. + */ + public void sendMessage(Mono message, int deleteSecond, MessageChannel messageChannel) { + message.subscribe(s -> sendMessage(s, deleteSecond, messageChannel)); + } + + /** + * Send a message to a special Message-Channel. + * + * @param message the Message content as {@link Mono}. + * @param messageChannel the Message-Channel. + * @param interactionHook the Interaction-hook if it is a slash command. + */ + public void sendMessage(Mono message, MessageChannel messageChannel, InteractionHook interactionHook) { + message.subscribe(s -> sendMessage(s, messageChannel, interactionHook)); + } + + /** + * Send a message to a special Message-Channel, with a deletion delay. + * + * @param messageContent the Message content as {@link Mono}. + * @param messageChannel the Message-Channel. + * @param interactionHook the Interaction-hook if it is a slash command. + * @param deleteSecond the delete delay + */ + public void sendMessage(Mono messageContent, int deleteSecond, MessageChannel messageChannel, InteractionHook interactionHook) { + messageContent.subscribe(s -> sendMessage(s, deleteSecond, messageChannel, interactionHook)); + } + /** * Send a message to a special Message-Channel. * @@ -709,10 +866,24 @@ public void deleteMessage(Message message, InteractionHook interactionHook) { !message.isEphemeral() && interactionHook == null) { message.delete().onErrorMap(throwable -> { - log.error("[CommandManager] Couldn't delete a Message!", throwable); + log.error("[CommandManager] Couldn't delete a Message -> {}", throwable.getMessage()); return null; }).queue(); } } + /** + * Delete a specific message. + * + * @param message the {@link Message} entity. + * @param interactionHook the Interaction-hook, if it is a slash event. + */ + public void deleteMessageWithoutException(Message message, InteractionHook interactionHook) { + try { + deleteMessage(message, interactionHook); + } catch (Exception e) { + log.error("[CommandManager] Couldn't delete a Message -> {}", e.getMessage()); + } + } + } \ No newline at end of file diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java b/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java index befcfd6f3..806863f65 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java @@ -4,10 +4,11 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.BirthdayWish; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -43,6 +44,21 @@ public void onPerform(CommandEvent commandEvent) { OptionMapping birthYearMapping = commandEvent.getOption("year"); switch (command) { + case "list" -> { + if (commandEvent.getMember().hasPermission(Permission.ADMINISTRATOR)) { + SQLSession.getSqlConnector().getSqlWorker().getBirthdays(commandEvent.getGuild().getIdLong()).subscribe(birthdayWishes -> { + StringBuilder sb = new StringBuilder(); + for (BirthdayWish wish : birthdayWishes) { + Member member = commandEvent.getGuild().getMemberById(wish.getUserId()); + GuildChannel guildChannel = commandEvent.getGuild().getGuildChannelById(wish.getChannelId()); + sb.append("@" + member.getUser().getName()).append(" ").append("-").append(" ").append("#").append(guildChannel.getName()).append("\n"); + } + commandEvent.reply(commandEvent.getResource("message.birthday.list", sb)); + }); + } else { + commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.ADMINISTRATOR.getName()), 5); + } + } case "remove" -> { if (userMapping == null) { SQLSession.getSqlConnector().getSqlWorker().removeBirthday(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()); @@ -100,9 +116,10 @@ public void onPerform(CommandEvent commandEvent) { @Override public CommandData getCommandData() { return new CommandDataImpl("birthday", - LanguageService.getDefault("command.description.birthday")) + "command.description.birthday") .addSubcommands(new SubcommandData("remove", "Remove a Birthday entry!") .addOptions(new OptionData(OptionType.USER, "user", "The User which should get their birthday entry removed.", false)), + new SubcommandData("list", "See all of the Birthday entries!"), new SubcommandData("add", "Add a Birthday entry!") .addOptions(new OptionData(OptionType.INTEGER, "day", "The day of the month.", true).setMinValue(1).setMaxValue(31), new OptionData(OptionType.INTEGER, "month", "Your birth month.", true).setMinValue(1).setMaxValue(12), diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java b/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java index e78934fe6..9543df983 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.utils.data.RegExUtil; @@ -100,9 +99,15 @@ public void onPerform(CommandEvent commandEvent) { new de.presti.ree6.sql.entities.Giveaway(message.getIdLong(), commandEvent.getMember().getIdLong(), commandEvent.getGuild().getIdLong(), commandEvent.getChannel().getIdLong(), prize, winners, endTime); - giveaway = SQLSession.getSqlConnector().getSqlWorker().updateEntity(giveaway); - Main.getInstance().getGiveawayManager().add(giveaway); - commandEvent.reply(commandEvent.getResource("message.giveaway.created", message.getId())); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(giveaway).subscribe(giveaway1 -> { + if (giveaway1 == null) { + commandEvent.reply(commandEvent.getResource("message.default.internalError")); + return; + } + + Main.getInstance().getGiveawayManager().add(giveaway1); + commandEvent.reply(commandEvent.getResource("message.giveaway.created", message.getId())); + }); }); } @@ -301,7 +306,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("giveaway", LanguageService.getDefault("command.description.giveaway")) + return new CommandDataImpl("giveaway", "command.description.giveaway") .addSubcommands(new SubcommandData("create", "Create a Giveaway.") .addOption(OptionType.STRING, "prize", "The Prize of the Giveaway.", true) .addOption(OptionType.INTEGER, "winners", "The amount of winners.", true) diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java b/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java index cdbf4a16a..5af344937 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java @@ -69,90 +69,90 @@ public void onPerform(CommandEvent commandEvent) { StringBuilder end = new StringBuilder("\n"); switch (command) { - case "instagram" -> { - - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers(commandEvent.getGuild().getIdLong())) { - end.append(users).append("\n"); - } - - commandEvent.reply(commandEvent.getResource("message.instagramNotifier.list", end.toString()), 10); - } - - case "youtube" -> { - - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels(commandEvent.getGuild().getIdLong())) { - - ChannelResult channelResult = null; - - try { - channelResult = YouTubeAPIHandler.getInstance().isValidChannelId(users) ? - YouTubeAPIHandler.getInstance().getYouTubeChannelById(users) : - YouTubeAPIHandler.getInstance().getYouTubeChannelBySearch(users); - } catch (Exception ignore) { - } - - end.append(users); + case "instagram" -> + SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers(commandEvent.getGuild().getIdLong()).subscribe(users -> { + for (String user : users) { + end.append(user).append("\n"); + } - if (channelResult != null) { - end.append(" ").append("-").append(" ").append(channelResult.getTitle()); - } + commandEvent.reply(commandEvent.getResource("message.instagramNotifier.list", end.toString()), 10); + }); - end.append("\n"); - } + case "youtube" -> + SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels(commandEvent.getGuild().getIdLong()).subscribe(userList -> { + for (String users : userList) { - commandEvent.reply(commandEvent.getResource("message.youtubeNotifier.list", end.toString()), 10); - } + ChannelResult channelResult = null; - case "twitch" -> { + try { + channelResult = YouTubeAPIHandler.getInstance().isValidChannelId(users) ? + YouTubeAPIHandler.getInstance().getYouTubeChannelById(users) : + YouTubeAPIHandler.getInstance().getYouTubeChannelBySearch(users); + } catch (Exception ignore) { + } - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames(commandEvent.getGuild().getIdLong())) { - end.append(users).append("\n"); - } + end.append(users); - commandEvent.reply(commandEvent.getResource("message.twitchNotifier.list", end.toString()), 10); - } + if (channelResult != null) { + end.append(" ").append("-").append(" ").append(channelResult.getTitle()); + } - case "twitter" -> { + end.append("\n"); + } - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames(commandEvent.getGuild().getIdLong())) { - end.append(users).append("\n"); - } + commandEvent.reply(commandEvent.getResource("message.youtubeNotifier.list", end.toString()), 10); + }); - commandEvent.reply(commandEvent.getResource("message.twitterNotifier.list", end.toString()), 10); - } + case "twitch" -> + SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames(commandEvent.getGuild().getIdLong()).subscribe(users -> { + for (String user : users) { + end.append(user).append("\n"); + } - case "tiktok" -> { + commandEvent.reply(commandEvent.getResource("message.twitchNotifier.list", end.toString()), 10); + }); - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames(commandEvent.getGuild().getIdLong())) { - end.append(users); - try { - TikTokUser tikTokUser = TikTokWrapper.getUser(Long.parseLong(users), false); - end.append(" ").append("-").append(" ").append(tikTokUser.getName()); - } catch (Exception ignore) { - } - end.append("\n"); - } + case "twitter" -> + SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames(commandEvent.getGuild().getIdLong()).subscribe(users -> { + for (String user : users) { + end.append(user).append("\n"); + } - commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.list", end.toString()), 10); - } + commandEvent.reply(commandEvent.getResource("message.twitterNotifier.list", end.toString()), 10); + }); - case "reddit" -> { + case "tiktok" -> + SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames(commandEvent.getGuild().getIdLong()).subscribe(users -> { + for (String user : users) { + end.append(user); + try { + TikTokUser tikTokUser = TikTokWrapper.getUser(Long.parseLong(user), false); + end.append(" ").append("-").append(" ").append(tikTokUser.getName()); + } catch (Exception ignore) { + } + end.append("\n"); + } - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits(commandEvent.getGuild().getIdLong())) { - end.append(users).append("\n"); - } + commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.list", end.toString()), 10); + }); - commandEvent.reply(commandEvent.getResource("message.redditNotifier.list", end.toString()), 10); - } + case "reddit" -> + SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits(commandEvent.getGuild().getIdLong()).subscribe(users -> { + for (String user : users) { + end.append(user).append("\n"); + } - case "rss" -> { + commandEvent.reply(commandEvent.getResource("message.redditNotifier.list", end.toString()), 10); + }); - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls(commandEvent.getGuild().getIdLong())) { - end.append(users).append("\n"); - } + case "rss" -> + SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls(commandEvent.getGuild().getIdLong()).subscribe(users -> { + for (String user : users) { + end.append(user).append("\n"); + } - commandEvent.reply(commandEvent.getResource("message.rssNotifier.list", end.toString()), 10); - } + commandEvent.reply(commandEvent.getResource("message.rssNotifier.list", end.toString()), 10); + }); default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); } @@ -161,7 +161,7 @@ public void onPerform(CommandEvent commandEvent) { switch (command) { case "instagram" -> { // Ignore this, because the Compiler would otherwise scream: - // "OMG YOU CAN NOT INITIALIZE THE VARIABLE BELOW BECAUSE YOU CANT REACH IT!!!!" + // "OMG YOU CANNOT INITIALIZE THE VARIABLE BELOW BECAUSE YOU CANT REACH IT!!!!" if (true) { commandEvent.reply("This feature is currently broken. Please wait for a fix.", 10); return; @@ -188,8 +188,8 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.instagramNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isInstagramUserRegistered(name)) { - Main.getInstance().getNotifier().registerInstagramUser(name); + if (!Main.getInstance().getNotifier().getInstagramSonic().contains(name)) { + Main.getInstance().getNotifier().getInstagramSonic().add(name); } } @@ -240,8 +240,8 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.youtubeNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isYouTubeRegistered(channelResult.getId())) { - Main.getInstance().getNotifier().registerYouTubeChannel(channelResult.getId()); + if (!Main.getInstance().getNotifier().getYouTubeSonic().contains(channelResult.getId())) { + Main.getInstance().getNotifier().getYouTubeSonic().add(channelResult.getId()); } } @@ -267,14 +267,14 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.twitchNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isTwitchRegistered(name)) { - Main.getInstance().getNotifier().registerTwitchChannel(name); + if (!Main.getInstance().getNotifier().getTwitchSonic().contains(name)) { + Main.getInstance().getNotifier().getTwitchSonic().add(name); } } case "twitter" -> { // Ignore this, because the Compiler would otherwise scream: - // "OMG YOU CAN NOT INITIALIZE THE VARIABLE BELOW BECAUSE YOU CANT REACH IT!!!!" + // "OMG YOU CANNOT INITIALIZE THE VARIABLE BELOW BECAUSE YOU CANT REACH IT!!!!" if (true) { commandEvent.reply("This feature is currently broken. Please wait for a fix.", 10); return; @@ -301,8 +301,8 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.twitterNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isTwitterRegistered(name)) { - Main.getInstance().getNotifier().registerTwitterUser(name); + if (!Main.getInstance().getNotifier().getTwitterSonic().contains(name)) { + Main.getInstance().getNotifier().getTwitterSonic().add(name); } } @@ -337,8 +337,8 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isTikTokUserRegistered(Long.parseLong(tikTokUser.getId()))) { - Main.getInstance().getNotifier().registerTikTokUser(Long.parseLong(tikTokUser.getId())); + if (!Main.getInstance().getNotifier().getTikTokSonic().contains(Long.parseLong(tikTokUser.getId()))) { + Main.getInstance().getNotifier().getTikTokSonic().add(Long.parseLong(tikTokUser.getId())); } } catch (Exception e) { commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.invalidUser", name), 5); @@ -367,8 +367,8 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.redditNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isSubredditRegistered(name)) { - Main.getInstance().getNotifier().registerSubreddit(name); + if (!Main.getInstance().getNotifier().getRedditSonic().contains(name)) { + Main.getInstance().getNotifier().getRedditSonic().add(name); } } @@ -395,8 +395,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().addRSSWebhook(commandEvent.getGuild().getIdLong(), channel.getIdLong(), w.getIdLong(), w.getToken(), name.toLowerCase())); commandEvent.reply(commandEvent.getResource("message.rssNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isRSSRegistered(name)) { - Main.getInstance().getNotifier().registerRSS(name); + if (!Main.getInstance().getNotifier().getRssSonic().contains(name)) { + Main.getInstance().getNotifier().getRedditSonic().add(name); } } @@ -415,8 +415,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeInstagramWebhook(commandEvent.getGuild().getIdLong(), name); commandEvent.reply(commandEvent.getResource("message.instagramNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isInstagramUserRegistered(name)) { - Main.getInstance().getNotifier().unregisterInstagramUser(name); + if (Main.getInstance().getNotifier().getInstagramSonic().contains(name)) { + Main.getInstance().getNotifier().getInstagramSonic().remove(name); } } @@ -449,8 +449,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeYouTubeWebhook(commandEvent.getGuild().getIdLong(), channelResult.getId()); commandEvent.reply(commandEvent.getResource("message.youtubeNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isYouTubeRegistered(channelResult.getId())) { - Main.getInstance().getNotifier().unregisterYouTubeChannel(channelResult.getId()); + if (Main.getInstance().getNotifier().getYouTubeSonic().contains(channelResult.getId())) { + Main.getInstance().getNotifier().getYouTubeSonic().remove(channelResult.getId()); } } @@ -464,8 +464,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeTwitchWebhook(commandEvent.getGuild().getIdLong(), name); commandEvent.reply(commandEvent.getResource("message.twitchNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isTwitchRegistered(name)) { - Main.getInstance().getNotifier().unregisterTwitchChannel(name); + if (Main.getInstance().getNotifier().getTwitchSonic().contains(name)) { + Main.getInstance().getNotifier().getTwitchSonic().remove(name); } } @@ -479,8 +479,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeTwitterWebhook(commandEvent.getGuild().getIdLong(), name); commandEvent.reply(commandEvent.getResource("message.twitterNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isTwitterRegistered(name)) { - Main.getInstance().getNotifier().unregisterTwitterUser(name); + if (Main.getInstance().getNotifier().getTwitterSonic().contains(name)) { + Main.getInstance().getNotifier().getTwitterSonic().remove(name); } } @@ -499,8 +499,8 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isTikTokUserRegistered(Long.parseLong(tikTokUser.getId()))) { - Main.getInstance().getNotifier().unregisterTikTokUser(Long.parseLong(tikTokUser.getId())); + if (Main.getInstance().getNotifier().getTikTokSonic().contains(Long.parseLong(tikTokUser.getId()))) { + Main.getInstance().getNotifier().getTikTokSonic().remove(Long.parseLong(tikTokUser.getId())); } } catch (Exception e) { commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.invalidUser", name), 5); @@ -517,8 +517,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeRedditWebhook(commandEvent.getGuild().getIdLong(), name); commandEvent.reply(commandEvent.getResource("message.redditNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isSubredditRegistered(name)) { - Main.getInstance().getNotifier().unregisterSubreddit(name); + if (Main.getInstance().getNotifier().getRedditSonic().contains(name)) { + Main.getInstance().getNotifier().getRedditSonic().remove(name); } } @@ -532,8 +532,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeRSSWebhook(commandEvent.getGuild().getIdLong(), name); commandEvent.reply(commandEvent.getResource("message.rssNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isRSSRegistered(name)) { - Main.getInstance().getNotifier().unregisterRSS(name); + if (Main.getInstance().getNotifier().getRssSonic().contains(name)) { + Main.getInstance().getNotifier().getRssSonic().remove(name); } } diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java b/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java index 7972fdf31..de8059b6e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java @@ -63,7 +63,7 @@ public void onPerform(CommandEvent commandEvent) { }).queue(msg -> { if (msg == null) return; MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - messageCreateBuilder.setContent(LanguageService.getByGuild(commandEvent.getGuild(), "message.reactions.reactionNeeded", role.getAsRole().getAsMention())); + messageCreateBuilder.setContent(LanguageService.getByGuild(commandEvent.getGuild(), "message.reactions.reactionNeeded", role.getAsRole().getAsMention()).block()); msg.reply(messageCreateBuilder.build()).queue(); }); @@ -85,15 +85,15 @@ public void onPerform(CommandEvent commandEvent) { return; } - ReactionRole reactionRole = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND guildRoleId.roleId=:roleId AND messageId=:messageId", - Map.of("gid", commandEvent.getGuild().getIdLong(), "roleId", role.getAsRole().getIdLong(), "messageId", messageId)); + Map.of("gid", commandEvent.getGuild().getIdLong(), "roleId", role.getAsRole().getIdLong(), "messageId", messageId)).subscribe(reactionRole -> { + if (reactionRole.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(reactionRole.get()).block(); - if (reactionRole != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(reactionRole); - - commandEvent.reply(commandEvent.getResource("message.reactions.removed", role.getAsRole().getIdLong()), 5); - } + commandEvent.reply(commandEvent.getResource("message.reactions.removed", role.getAsRole().getIdLong()), 5); + } + }); } default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); @@ -105,9 +105,9 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("reactions", LanguageService.getDefault("command.description.reactions")) + return new CommandDataImpl("reactions", "command.description.reactions") .addSubcommands(new SubcommandData("remove", "Remove a reaction role.") - .addOption(OptionType.STRING,"message", "The ID of the Message.", true) + .addOption(OptionType.STRING, "message", "The ID of the Message.", true) .addOption(OptionType.ROLE, "role", "The Role to be given.", true), new SubcommandData("add", "Add a reaction role.") .addOption(OptionType.STRING, "message", "The ID of the Message.", true) diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java b/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java index 7f77745b9..7da669be3 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java @@ -55,35 +55,34 @@ public void onPerform(CommandEvent commandEvent) { switch (subCommand) { - case "list" -> { - StringBuilder stringBuilder = new StringBuilder(); - - for (ScheduledMessage scheduledMessage : SQLSession.getSqlConnector().getSqlWorker() - .getEntityList(new ScheduledMessage(), "FROM ScheduledMessage WHERE guildAndId.guildId = :gid ", - Map.of("gid", commandEvent.getGuild().getIdLong()))) { - stringBuilder.append(scheduledMessage.getId()).append(" ").append("-").append(" ") - .append(scheduledMessage.getMessage()).append(" ") - .append("->").append(" ") - .append(Instant.ofEpochMilli(scheduledMessage.getDelayAmount()) - .atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH/mm"))); - } - - commandEvent.reply(commandEvent.getResource("message.schedule.list", stringBuilder.toString())); - } + case "list" -> SQLSession.getSqlConnector().getSqlWorker() + .getEntityList(new ScheduledMessage(), "FROM ScheduledMessage WHERE guildAndId.guildId = :gid ", + Map.of("gid", commandEvent.getGuild().getIdLong())).subscribe(scheduledMessages -> { + StringBuilder stringBuilder = new StringBuilder(); + + for (ScheduledMessage scheduledMessage : scheduledMessages) { + stringBuilder.append(scheduledMessage.getId()).append(" ").append("-").append(" ") + .append(scheduledMessage.getMessage()).append(" ") + .append("->").append(" ") + .append(Instant.ofEpochMilli(scheduledMessage.getDelayAmount()) + .atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH/mm"))); + } + commandEvent.reply(commandEvent.getResource("message.schedule.list", stringBuilder.toString())); + }); case "delete" -> { OptionMapping id = commandEvent.getOption("id"); - ScheduledMessage scheduledMessage = SQLSession.getSqlConnector().getSqlWorker() + SQLSession.getSqlConnector().getSqlWorker() .getEntity(new ScheduledMessage(), "FROM ScheduledMessage WHERE guildAndId.guildId = :gid AND guildAndId.id = :id", - Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id.getAsLong())); - - if (scheduledMessage != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); - commandEvent.reply(commandEvent.getResource("message.schedule.delete.success")); - } else { - commandEvent.reply(commandEvent.getResource("message.schedule.delete.failed")); - } + Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id.getAsLong())).subscribe(scheduledMessage -> { + if (scheduledMessage.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage.get()).block(); + commandEvent.reply(commandEvent.getResource("message.schedule.delete.success")); + } else { + commandEvent.reply(commandEvent.getResource("message.schedule.delete.failed")); + } + }); } case "create" -> { @@ -94,6 +93,8 @@ public void onPerform(CommandEvent commandEvent) { OptionMapping channel = commandEvent.getOption("channel"); OptionMapping repeat = commandEvent.getOption("repeat"); + boolean shouldRepeat = repeat != null && repeat.getAsBoolean(); + long fullTime = 0; if (month != null) fullTime += Duration.ofDays(31 * month.getAsLong()).toMillis(); if (day != null) fullTime += Duration.ofDays(day.getAsLong()).toMillis(); @@ -109,22 +110,23 @@ public void onPerform(CommandEvent commandEvent) { ScheduledMessage scheduledMessage = new ScheduledMessage(); - WebhookScheduledMessage webhookScheduledMessage = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookScheduledMessage(), + long finalFullTime = fullTime; + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookScheduledMessage(), "FROM WebhookScheduledMessage WHERE guildAndId.guildId = :gid AND channelId = :channel", - Map.of("gid", commandEvent.getGuild().getId(),"channel", guildChannel.getIdLong())); - - if (webhookScheduledMessage == null) { - Webhook webhook = guildChannel.asStandardGuildMessageChannel().createWebhook(BotConfig.getBotName() + "-Schedule").complete(); - - webhookScheduledMessage = SQLSession.getSqlConnector().getSqlWorker() - .updateEntity(new WebhookScheduledMessage(commandEvent.getGuild().getIdLong(), guildChannel.getIdLong(), webhook.getIdLong(), webhook.getToken())); - } - - scheduledMessage.setScheduledMessageWebhook(webhookScheduledMessage); - scheduledMessage.setDelayAmount(fullTime); - scheduledMessage.setRepeated(repeat.getAsBoolean()); - commandEvent.reply(commandEvent.getResource("message.schedule.added")); + Map.of("gid", commandEvent.getGuild().getId(), "channel", guildChannel.getIdLong())).subscribe(webhookScheduledMessage -> { + WebhookScheduledMessage webhookScheduledMessageEntity = webhookScheduledMessage.orElse(new WebhookScheduledMessage()); + if (webhookScheduledMessage.isEmpty()) { + Webhook webhook = guildChannel.asStandardGuildMessageChannel().createWebhook(BotConfig.getBotName() + "-Schedule").complete(); + + webhookScheduledMessageEntity = SQLSession.getSqlConnector().getSqlWorker() + .updateEntity(new WebhookScheduledMessage(commandEvent.getGuild().getIdLong(), guildChannel.getIdLong(), webhook.getIdLong(), webhook.getToken())).block(); + } + + scheduledMessage.setScheduledMessageWebhook(webhookScheduledMessageEntity); + scheduledMessage.setDelayAmount(finalFullTime); + scheduledMessage.setRepeated(shouldRepeat); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).subscribe(x -> commandEvent.reply(commandEvent.getResource("message.schedule.added"))); + }); } default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); @@ -138,8 +140,8 @@ public void onPerform(CommandEvent commandEvent) { public CommandData getCommandData() { return new CommandDataImpl("schedule", "command.description.schedule") .addSubcommands(new SubcommandData("create", "Create a new scheduled Message.") - .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The channel it should be sent to.", true).setChannelTypes(ChannelType.NEWS, ChannelType.TEXT)) - .addOption(OptionType.BOOLEAN, "repeat", "If the schedule should be repeated.", true) + .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The channel it should be sent to.", true).setChannelTypes(ChannelType.NEWS, ChannelType.TEXT)) + .addOption(OptionType.BOOLEAN, "repeat", "If the schedule should be repeated.", true) .addOption(OptionType.INTEGER, "month", "The months of the delay.", false) .addOption(OptionType.INTEGER, "day", "The days of the delay.", false) .addOption(OptionType.INTEGER, "hour", "The hours of the delay.", false) diff --git a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java index 843f26688..aa17a3049 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java @@ -2,18 +2,17 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.container.StreamActionContainer; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.StreamAction; import de.presti.ree6.sql.entities.TwitchIntegration; -import de.presti.ree6.actions.streamtools.container.StreamActionContainer; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -27,7 +26,6 @@ import java.nio.charset.StandardCharsets; import java.util.Arrays; -import java.util.List; import java.util.Map; /** @@ -62,167 +60,150 @@ public void onPerform(CommandEvent commandEvent) { String subCommand = commandEvent.getSubcommand(); switch (subCommandGroup) { - case "manage" -> { - StreamAction streamAction = SQLSession.getSqlConnector().getSqlWorker() - .getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", - Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())); + case "manage" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamActionOptional -> { + if (streamActionOptional.isPresent()) { + StreamAction streamAction = streamActionOptional.get(); + switch (subCommand) { + case "create" -> { + OptionMapping action = commandEvent.getOption("action"); - if (streamAction != null) { - switch (subCommand) { - case "create" -> { - OptionMapping action = commandEvent.getOption("action"); + String[] values = action.getAsString().split("\\s+"); - String[] values = action.getAsString().split("\\s+"); + JsonObject jsonObject = new JsonObject(); + String actionName = values[0]; + jsonObject.addProperty("action", actionName); - JsonObject jsonObject = new JsonObject(); - String actionName = values[0]; - jsonObject.addProperty("action", actionName); + values = Arrays.stream(values).skip(1).toArray(String[]::new); - values = Arrays.stream(values).skip(1).toArray(String[]::new); + jsonObject.addProperty("value", String.join(" ", values)); - jsonObject.addProperty("value", String.join(" ", values)); + if (streamAction.getActions() == null || !streamAction.getActions().isJsonArray()) { + streamAction.setActions(new JsonArray()); + } - if (streamAction.getActions() == null || !streamAction.getActions().isJsonArray()) { - streamAction.setActions(new JsonArray()); - } + streamAction.getActions().getAsJsonArray().add(jsonObject); - streamAction.getActions().getAsJsonArray().add(jsonObject); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).subscribe(); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction); - - commandEvent.reply(commandEvent.getResource("message.stream-action.addedLine", actionName)); - } - - case "delete" -> { - try { - OptionMapping line = commandEvent.getOption("line"); - int value = line.getAsInt(); - if (streamAction.getActions().getAsJsonArray().size() >= value && value > 0) { - streamAction.getActions().getAsJsonArray().remove(value - 1); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction); - commandEvent.reply(commandEvent.getResource("message.stream-action.deletedLine", "" + value)); - } else { - commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + commandEvent.reply(commandEvent.getResource("message.stream-action.addedLine", actionName)); } - } catch (Exception exception) { - commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); - } - } - case "list" -> { - StreamActionContainer streamActionContainer = new StreamActionContainer(streamAction); + case "delete" -> { + try { + OptionMapping line = commandEvent.getOption("line"); + int value = line.getAsInt(); + if (streamAction.getActions().getAsJsonArray().size() >= value && value > 0) { + streamAction.getActions().getAsJsonArray().remove(value - 1); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).subscribe(); + commandEvent.reply(commandEvent.getResource("message.stream-action.deletedLine", "" + value)); + } else { + commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + } + } catch (Exception exception) { + commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + } + } - StringBuilder stringBuilder = new StringBuilder(); - streamActionContainer.getActions() - .forEach(actionRun -> - stringBuilder.append(actionRun.getAction().getClass().getAnnotation(ActionInfo.class).name()) - .append(" -> ") - .append(String.join(" ", actionRun.getArguments())).append("\n")); + case "list" -> { + StreamActionContainer streamActionContainer = new StreamActionContainer(streamAction); - commandEvent.reply(commandEvent.getResource("message.stream-action.actionList", stringBuilder.toString())); - } + StringBuilder stringBuilder = new StringBuilder(); + streamActionContainer.getActions().forEach(actionRun -> stringBuilder.append(actionRun.getAction().getClass().getAnnotation(ActionInfo.class).name()).append(" -> ").append(String.join(" ", actionRun.getArguments())).append("\n")); - case "listener" -> { - OptionMapping listener = commandEvent.getOption("listener"); - String[] values = listener.getAsString().split("\\s+"); - - if (values.length >= 1) { - if (values[0].equalsIgnoreCase("redemption")) { - streamAction.setListener(0); - } else if (values[0].equalsIgnoreCase("follow")) { - streamAction.setListener(1); - } else if (values[0].equalsIgnoreCase("subscribe")) { - streamAction.setListener(2); - } else { - commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); - return; + commandEvent.reply(commandEvent.getResource("message.stream-action.actionList", stringBuilder.toString())); } - if (values.length >= 2) - streamAction.setArgument(values[1]); - - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction); - if (values.length >= 2) { - commandEvent.reply(commandEvent.getResource("message.stream-action.listenerArgument", values[0], values[1])); - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.listener", values[0])); + case "listener" -> { + OptionMapping listener = commandEvent.getOption("listener"); + String[] values = listener.getAsString().split("\\s+"); + + if (values.length >= 1) { + if (values[0].equalsIgnoreCase("redemption")) { + streamAction.setListener(0); + } else if (values[0].equalsIgnoreCase("follow")) { + streamAction.setListener(1); + } else if (values[0].equalsIgnoreCase("subscribe")) { + streamAction.setListener(2); + } else { + commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + return; + } + + if (values.length >= 2) streamAction.setArgument(values[1]); + + SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).subscribe(); + if (values.length >= 2) { + commandEvent.reply(commandEvent.getResource("message.stream-action.listenerArgument", values[0], values[1])); + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.listener", values[0])); + } + } else { + commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + } } - } else { - commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + + default -> + commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); } + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.notFound", name.getAsString())); } - - default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); - } - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.notFound", name.getAsString())); - } - } + }); default -> { switch (subCommand) { - case "create" -> { - StreamAction streamAction = SQLSession.getSqlConnector().getSqlWorker() - .getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", - Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())); - - if (streamAction == null) { - TwitchIntegration twitchIntegration = SQLSession.getSqlConnector().getSqlWorker() - .getEntity(new TwitchIntegration(),"FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())); - if (twitchIntegration != null) { - streamAction = new StreamAction(); - streamAction.setIntegration(twitchIntegration); - streamAction.setGuildId(commandEvent.getGuild().getIdLong()); - streamAction.setName(name.getAsString()); - - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction); - commandEvent.reply(commandEvent.getResource("message.stream-action.added", name.getAsString())); - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.noTwitch", BotConfig.getTwitchAuth())); - } - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.alreadyExisting", name.getAsString())); - } - } - - case "delete" -> { - StreamAction streamAction = SQLSession.getSqlConnector().getSqlWorker() - .getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", - Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())); - if (streamAction != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(streamAction); - commandEvent.reply(commandEvent.getResource("message.stream-action.deleted", name.getAsString())); - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.notFound", name.getAsString())); - } - } - - case "list" -> { - List streamActions = SQLSession.getSqlConnector().getSqlWorker() - .getEntityList(new StreamAction(), "FROM StreamAction WHERE guildAndName.guildId = :gid", - Map.of("gid", commandEvent.getGuild().getIdLong())); - - commandEvent.reply(LanguageService.getByEvent(commandEvent, "message.stream-action.list", - String.join("\n", streamActions.stream().map(StreamAction::getName).toArray(String[]::new)))); - } - - case "points" -> { - TwitchIntegration twitchIntegration = SQLSession.getSqlConnector().getSqlWorker() - .getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())); - if (twitchIntegration != null) { - StringBuilder stringBuilder = new StringBuilder(); - Main.getInstance().getNotifier().getTwitchClient().getHelix() - .getCustomRewards(twitchIntegration.getToken(), twitchIntegration.getChannelId(), null, false) - .execute().getRewards().forEach(c -> stringBuilder.append(c.getId()).append(" - ").append(c.getTitle()).append("\n")); - MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - messageCreateBuilder.setContent(commandEvent.getResource("message.stream-action.points")); - messageCreateBuilder.addFiles(FileUpload.fromData(stringBuilder.toString().getBytes(StandardCharsets.UTF_8), "points.txt")); - commandEvent.reply(messageCreateBuilder.build()); - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.noTwitch", BotConfig.getTwitchAuth())); - } - } + case "create" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamActionOptional -> { + if (streamActionOptional.isEmpty()) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())) + .subscribe(twitchIntegrationOptional -> { + if (twitchIntegrationOptional.isPresent()) { + StreamAction newStreamAction = new StreamAction(); + newStreamAction.setIntegration(twitchIntegrationOptional.get()); + newStreamAction.setGuildId(commandEvent.getGuild().getIdLong()); + newStreamAction.setName(name.getAsString()); + + SQLSession.getSqlConnector().getSqlWorker().updateEntity(newStreamAction).subscribe(); + commandEvent.reply(commandEvent.getResource("message.stream-action.added", name.getAsString())); + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.noTwitch", BotConfig.getTwitchAuth())); + } + }); + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.alreadyExisting", name.getAsString())); + } + }); + + case "delete" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamAction -> { + if (streamAction.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(streamAction.get()).block(); + commandEvent.reply(commandEvent.getResource("message.stream-action.deleted", name.getAsString())); + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.notFound", name.getAsString())); + } + }); + + case "list" -> + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new StreamAction(), "FROM StreamAction WHERE guildAndName.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).subscribe(streamActions -> + commandEvent.reply(commandEvent.getResource("message.stream-action.list", String.join("\n", streamActions.stream().map(StreamAction::getName).toArray(String[]::new))))); + + case "points" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())).subscribe(twitchIntegrationOptional -> { + if (twitchIntegrationOptional.isPresent()) { + TwitchIntegration twitchIntegration = twitchIntegrationOptional.get(); + StringBuilder stringBuilder = new StringBuilder(); + Main.getInstance().getNotifier().getTwitchClient().getHelix().getCustomRewards(twitchIntegration.getToken(), twitchIntegration.getChannelId(), null, false).execute().getRewards().forEach(c -> stringBuilder.append(c.getId()).append(" - ").append(c.getTitle()).append("\n")); + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setContent(commandEvent.getResource("message.stream-action.points")); + messageCreateBuilder.addFiles(FileUpload.fromData(stringBuilder.toString().getBytes(StandardCharsets.UTF_8), "points.txt")); + commandEvent.reply(messageCreateBuilder.build()); + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.noTwitch", BotConfig.getTwitchAuth())); + } + }); default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); } @@ -235,8 +216,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("stream-action", - LanguageService.getDefault("command.description.stream-action")) + return new CommandDataImpl("stream-action", "command.description.stream-action") .addSubcommands(new SubcommandData("create", "Create a new Stream-Action.") .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true)) .addSubcommands(new SubcommandData("delete", "Delete a Stream-Action.") @@ -244,9 +224,10 @@ public CommandData getCommandData() { .addSubcommands(new SubcommandData("list", "List all Stream-Actions.")) .addSubcommands(new SubcommandData("points", "List all your ChannelPoint Rewards.")) .addSubcommandGroups(new SubcommandGroupData("manage", "Manage a existing Stream-action.") - .addSubcommands(new SubcommandData("listener", "Set the listener of the Stream-Action.") - .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true) - .addOption(OptionType.STRING, "listener", "The listener of the Stream-Action.", true), + .addSubcommands( + new SubcommandData("listener", "Set the listener of the Stream-Action.") + .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true) + .addOption(OptionType.STRING, "listener", "The listener of the Stream-Action.", true), new SubcommandData("delete", "Delete a line of the Stream-Action.") .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true) .addOptions(new OptionData(OptionType.INTEGER, "line", "The line of the Stream-Action.", true).setMinValue(1)), diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java index fd355f42d..71672c5ff 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java @@ -1,5 +1,6 @@ package de.presti.ree6.commands.impl.community; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; @@ -8,7 +9,6 @@ import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Tickets; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.channel.ChannelType; @@ -23,7 +23,6 @@ import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.internal.interactions.CommandDataImpl; -import java.awt.*; import java.util.EnumSet; import java.util.Map; @@ -59,45 +58,42 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder embedBuilder = new EmbedBuilder(); - Tickets tickets = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())); - - if (tickets != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets); - } - - StandardGuildMessageChannel channel = logChannel.getAsChannel().asStandardGuildMessageChannel(); - - tickets = new Tickets(); - tickets.setChannelId(ticketChannel.getAsChannel().getIdLong()); - tickets.setGuildId(commandEvent.getGuild().getIdLong()); - tickets.setLogChannelId(logChannel.getAsChannel().getIdLong()); - - Tickets finalTickets = tickets; - - channel.createWebhook("Ticket-Log").queue(webhook -> { - finalTickets.setLogChannelWebhookId(webhook.getIdLong()); - finalTickets.setLogChannelWebhookToken(webhook.getToken()); - commandEvent.getGuild().createCategory("Tickets").addPermissionOverride(commandEvent.getGuild().getPublicRole(), null, EnumSet.of(Permission.VIEW_CHANNEL)).queue(category1 -> { - finalTickets.setTicketCategory(category1.getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(finalTickets); - - MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - messageCreateBuilder.setEmbeds(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket")) - .setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_ticket_menu").getStringValue()) - .setColor(0x55ff00) - .setThumbnail(commandEvent.getGuild().getIconUrl()) - .setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) - .build()); - messageCreateBuilder.setActionRow(Button.of(ButtonStyle.PRIMARY, "re_ticket_open", LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket"), Emoji.fromUnicode("U+1F4E9"))); - Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), ticketChannel.getAsChannel().asTextChannel()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())).subscribe(tickets -> { + + tickets.ifPresent(value -> SQLSession.getSqlConnector().getSqlWorker().deleteEntity(value).block()); + + StandardGuildMessageChannel channel = logChannel.getAsChannel().asStandardGuildMessageChannel(); + + Tickets ticketEntity = new Tickets(); + ticketEntity.setChannelId(ticketChannel.getAsChannel().getIdLong()); + ticketEntity.setGuildId(commandEvent.getGuild().getIdLong()); + ticketEntity.setLogChannelId(logChannel.getAsChannel().getIdLong()); + + channel.createWebhook("Ticket-Log").queue(webhook -> { + ticketEntity.setLogChannelWebhookId(webhook.getIdLong()); + ticketEntity.setLogChannelWebhookToken(webhook.getToken()); + commandEvent.getGuild().createCategory("Tickets").addPermissionOverride(commandEvent.getGuild().getPublicRole(), null, EnumSet.of(Permission.VIEW_CHANNEL)).queue(category1 -> { + ticketEntity.setTicketCategory(category1.getIdLong()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(ticketEntity).block(); + + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setEmbeds(new EmbedBuilder() + .setTitle(LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket").block()) + .setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_ticket_menu").block().get().getStringValue()) + .setColor(0x55ff00) + .setThumbnail(commandEvent.getGuild().getIconUrl()) + .setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) + .build()); + messageCreateBuilder.setActionRow(Button.of(ButtonStyle.PRIMARY, "re_ticket_open", LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket").block(), Emoji.fromUnicode("U+1F4E9"))); + Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), ticketChannel.getAsChannel().asTextChannel()); + }); }); - }); - embedBuilder.setDescription(LanguageService.getByGuild(commandEvent.getGuild(), "message.ticket.setupSuccess")); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setDescription(commandEvent.getResource("message.ticket.setupSuccess")); + embedBuilder.setColor(BotConfig.getMainColor()); - commandEvent.reply(embedBuilder.build()); + commandEvent.reply(embedBuilder.build()); + }); } /** @@ -105,7 +101,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("tickets", LanguageService.getDefault("command.description.tickets")) + return new CommandDataImpl("tickets", "command.description.tickets") .addOptions(new OptionData(OptionType.CHANNEL, "supportchannel", "The channel that should have the ticket creation message.", true).setChannelTypes(ChannelType.NEWS, ChannelType.TEXT), new OptionData(OptionType.CHANNEL, "logchannel", "The channel that should receive the transcripts.", true).setChannelTypes(ChannelType.NEWS, ChannelType.TEXT)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Money.java b/src/main/java/de/presti/ree6/commands/impl/economy/Money.java index 876dcb65e..6ca9f7327 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Money.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Money.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.economy.MoneyHolder; import de.presti.ree6.utils.data.EconomyUtil; import de.presti.ree6.utils.others.RandomUtils; import net.dv8tion.jda.api.Permission; @@ -21,7 +19,7 @@ /** * Command to manage the player specific economy. */ -@Command(name = "money", description = "command.description.money", category = Category.ECONOMY) +@Command(name = "money", description = "command.description.money.default", category = Category.ECONOMY) public class Money implements ICommand { @Override @@ -47,14 +45,14 @@ public void onPerform(CommandEvent commandEvent) { double withdrawAmount = RandomUtils.round(amount.getAsDouble(), 2); - MoneyHolder moneyHolder = EconomyUtil.getMoneyHolder(commandEvent.getMember()); - - if (EconomyUtil.hasEnoughMoney(moneyHolder, withdrawAmount, true)) { - EconomyUtil.pay(moneyHolder, moneyHolder, withdrawAmount, true, false); - commandEvent.reply(commandEvent.getResource("message.money.withdraw", EconomyUtil.formatMoney(withdrawAmount)), 5); - } else { - commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); - } + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { + if (EconomyUtil.hasEnoughMoney(moneyHolder, withdrawAmount, true)) { + EconomyUtil.pay(moneyHolder, moneyHolder, withdrawAmount, true, false); + commandEvent.reply(commandEvent.getResource("message.money.withdraw", EconomyUtil.formatMoney(withdrawAmount)), 5); + } else { + commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); + } + }); } case "deposit" -> { if (amount == null) { @@ -64,14 +62,14 @@ public void onPerform(CommandEvent commandEvent) { double depositAmount = RandomUtils.round(amount.getAsDouble(), 2); - MoneyHolder moneyHolder = EconomyUtil.getMoneyHolder(commandEvent.getMember()); - - if (EconomyUtil.hasEnoughMoney(moneyHolder, depositAmount, false)) { - EconomyUtil.pay(moneyHolder, moneyHolder, depositAmount, false, true); - commandEvent.reply(commandEvent.getResource("message.money.deposit", EconomyUtil.formatMoney(depositAmount)), 5); - } else { - commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); - } + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { + if (EconomyUtil.hasEnoughMoney(moneyHolder, depositAmount, false)) { + EconomyUtil.pay(moneyHolder, moneyHolder, depositAmount, false, true); + commandEvent.reply(commandEvent.getResource("message.money.deposit", EconomyUtil.formatMoney(depositAmount)), 5); + } else { + commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); + } + }); } case "send" -> { if (user == null || amount == null) { @@ -88,14 +86,14 @@ public void onPerform(CommandEvent commandEvent) { double sendAmount = RandomUtils.round(amount.getAsDouble(), 2); - MoneyHolder moneyHolder = EconomyUtil.getMoneyHolder(commandEvent.getMember()); - MoneyHolder target = EconomyUtil.getMoneyHolder(member); - - if (EconomyUtil.pay(moneyHolder, target, sendAmount, true, true)) { - commandEvent.reply(commandEvent.getResource("message.money.send", EconomyUtil.formatMoney(sendAmount), member.getAsMention())); - } else { - commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); - } + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> + EconomyUtil.getMoneyHolder(member).subscribe(target -> { + if (EconomyUtil.pay(moneyHolder, target, sendAmount, true, true)) { + commandEvent.reply(commandEvent.getResource("message.money.send", EconomyUtil.formatMoney(sendAmount), member.getAsMention())); + } else { + commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); + } + })); } default -> { if (user != null) { @@ -106,11 +104,13 @@ public void onPerform(CommandEvent commandEvent) { return; } - MoneyHolder moneyHolder = EconomyUtil.getMoneyHolder(member); - commandEvent.reply(commandEvent.getResource("message.money.balance", member.getAsMention(), EconomyUtil.formatMoney(moneyHolder.getAmount()), EconomyUtil.formatMoney(moneyHolder.getBankAmount()))); + EconomyUtil.getMoneyHolder(member).subscribe(moneyHolder -> + commandEvent.reply(commandEvent.getResource("message.money.balance", member.getAsMention(), + EconomyUtil.formatMoney(moneyHolder.getAmount()), EconomyUtil.formatMoney(moneyHolder.getBankAmount())))); } else { - MoneyHolder moneyHolder = EconomyUtil.getMoneyHolder(commandEvent.getMember()); - commandEvent.reply(commandEvent.getResource("message.money.balance", commandEvent.getMember().getAsMention(), EconomyUtil.formatMoney(moneyHolder.getAmount()), EconomyUtil.formatMoney(moneyHolder.getBankAmount()))); + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> + commandEvent.reply(commandEvent.getResource("message.money.balance", commandEvent.getMember().getAsMention(), + EconomyUtil.formatMoney(moneyHolder.getAmount()), EconomyUtil.formatMoney(moneyHolder.getBankAmount())))); } } } @@ -140,22 +140,22 @@ public void onPerform(CommandEvent commandEvent) { if (subcommandGroup.equals("admin")) { switch (subcommand) { - case "add" -> { - EconomyUtil.pay(EconomyUtil.getMoneyHolder(commandEvent.getMember()), - EconomyUtil.getMoneyHolder(member), optionAmount, false, - transferToBank, true); - commandEvent.reply(commandEvent.getResource("message.money.add", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); - } - case "set" -> { - EconomyUtil.set(EconomyUtil.getMoneyHolder(member), optionAmount, transferToBank); + case "add" -> EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> + EconomyUtil.getMoneyHolder(member).subscribe(target -> { + EconomyUtil.pay(moneyHolder, target, optionAmount, false, transferToBank, true); + commandEvent.reply(commandEvent.getResource("message.money.add", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); + })); + case "set" -> EconomyUtil.getMoneyHolder(member).subscribe(moneyHolder -> { + EconomyUtil.set(moneyHolder, optionAmount, transferToBank); commandEvent.reply(commandEvent.getResource("message.money.set", member.getAsMention(), EconomyUtil.formatMoney(optionAmount)), 5); - } - case "remove" -> { - EconomyUtil.pay(EconomyUtil.getMoneyHolder(commandEvent.getMember()), - EconomyUtil.getMoneyHolder(member), -optionAmount, false, - transferToBank, true); - commandEvent.reply(commandEvent.getResource("message.money.remove", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); - } + }); + case "remove" -> EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> + EconomyUtil.getMoneyHolder(member).subscribe(target -> { + EconomyUtil.pay(moneyHolder, target, -optionAmount, false, transferToBank, true); + commandEvent.reply(commandEvent.getResource("message.money.remove", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); + })); + + default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); } } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java index 4cb8a9747..a162171f2 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java @@ -5,8 +5,6 @@ import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.Setting; -import de.presti.ree6.sql.entities.economy.MoneyHolder; import de.presti.ree6.utils.data.EconomyUtil; import de.presti.ree6.utils.others.RandomUtils; import de.presti.ree6.utils.others.ThreadUtil; @@ -18,7 +16,6 @@ import java.time.Duration; import java.util.ArrayList; -import java.util.Map; /** * Steal money from other users. @@ -43,51 +40,65 @@ public void onPerform(CommandEvent commandEvent) { String entryString = commandEvent.getGuild().getIdLong() + "-" + commandEvent.getMember().getIdLong(); - long delay = Long.parseLong((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_steal_delay")).getValue()); - - if (stealTimeout.contains(entryString)) { - commandEvent.reply(commandEvent.getResource("message.steal.cooldown", delay)); - return; - } - - OptionMapping user = commandEvent.getOption("user"); - - if (user == null) { - commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); - return; - } - - Member member = user.getAsMember(); - - if (member == null) { - commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); - return; - } - - if (member.getIdLong() == commandEvent.getMember().getIdLong()) { - commandEvent.reply(commandEvent.getResource("message.steal.self"), 5); - return; - } - - MoneyHolder targetHolder = EconomyUtil.getMoneyHolder(commandEvent.getGuild().getIdLong(), member.getIdLong(), false); - - // Leave them poor people alone ong. - if (!EconomyUtil.hasCash(targetHolder) || targetHolder.getAmount() <= 50) { - commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); - return; - } - - double stealAmount = RandomUtils.round(targetHolder.getAmount() * RandomUtils.nextDouble(0.01, 0.25), 2); - if (EconomyUtil.pay(targetHolder, EconomyUtil.getMoneyHolder(commandEvent.getMember()), stealAmount, false, false)) { - // TODO:: more variation in the messages. - commandEvent.reply(commandEvent.getResource("message.steal.success", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); - } else { - commandEvent.reply(commandEvent.getResource("message.steal.failed", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); - } - - stealTimeout.add(entryString); - ThreadUtil.createThread(x -> stealTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), + "configuration_steal_delay").subscribe(value -> { + long delay = Long.parseLong(value.get().getStringValue()); + + if (stealTimeout.contains(entryString)) { + commandEvent.reply(commandEvent.getResource("message.steal.cooldown", delay)); + return; + } + + OptionMapping user = commandEvent.getOption("user"); + + if (user == null) { + commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); + return; + } + + Member member = user.getAsMember(); + + if (member == null) { + commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); + return; + } + + if (member.getIdLong() == commandEvent.getMember().getIdLong()) { + commandEvent.reply(commandEvent.getResource("message.steal.self"), 5); + return; + } + + EconomyUtil.getMoneyHolder(commandEvent.getGuild().getIdLong(), member.getIdLong(), false).subscribe(targetHolder -> { + if (targetHolder == null) { + commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); + return; + } + + // Leave them poor people alone ong. + if (!EconomyUtil.hasCash(targetHolder) || targetHolder.getAmount() <= 50) { + commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); + return; + } + + double stealAmount = RandomUtils.round(targetHolder.getAmount() * RandomUtils.nextDouble(0.01, 0.25), 2); + + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(holder -> { + if (holder == null) { + commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); + return; + } + + if (EconomyUtil.pay(targetHolder, holder, stealAmount, false, false)) { + commandEvent.reply(commandEvent.getResource("message.steal.success", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); + } else { + commandEvent.reply(commandEvent.getResource("message.steal.failed", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); + } + + stealTimeout.add(entryString); + ThreadUtil.createThread(x -> stealTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + }); + }); + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java index bb17b90e9..79d2bd66f 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java @@ -5,7 +5,6 @@ import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.utils.data.EconomyUtil; import de.presti.ree6.utils.others.RandomUtils; import de.presti.ree6.utils.others.ThreadUtil; @@ -13,7 +12,6 @@ import java.time.Duration; import java.util.ArrayList; -import java.util.Map; /** * Work for money. @@ -33,31 +31,35 @@ public class Work implements ICommand { public void onPerform(CommandEvent commandEvent) { String entryString = commandEvent.getGuild().getIdLong() + "-" + commandEvent.getMember().getIdLong(); - long delay = Long.parseLong((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_delay")).getValue()); + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_work_delay").subscribe(value -> { + long delay = Long.parseLong(value.get().getStringValue()); - if (workTimeout.contains(entryString)) { - commandEvent.reply(commandEvent.getResource("message.work.cooldown", delay)); - return; - } + if (workTimeout.contains(entryString)) { + commandEvent.reply(commandEvent.getResource("message.work.cooldown", delay)); + return; + } - double min = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_min")).getValue()); + double min = Double.parseDouble(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), + "configuration_work_min").block().get().getStringValue()); - double max = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_max")).getValue()); + double max = Double.parseDouble(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), + "configuration_work_max").block().get().getStringValue()); - double amount = RandomUtils.round(RandomUtils.nextDouble(min, max), 2); + double amount = RandomUtils.round(RandomUtils.nextDouble(min, max), 2); - if (EconomyUtil.pay(null, EconomyUtil.getMoneyHolder(commandEvent.getMember()), amount, false, false, true)) { - // TODO:: add more variation messages. - commandEvent.reply(commandEvent.getResource("message.work.success", EconomyUtil.formatMoney(amount))); - } else { - commandEvent.reply(commandEvent.getResource("message.work.fail")); - } + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { + if (moneyHolder == null) return; - workTimeout.add(entryString); - ThreadUtil.createThread(x -> workTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + if (EconomyUtil.pay(null, moneyHolder, amount, false, false, true)) { + commandEvent.reply(commandEvent.getResource("message.work.success", EconomyUtil.formatMoney(amount))); + } else { + commandEvent.reply(commandEvent.getResource("message.work.fail")); + } + + workTimeout.add(entryString); + ThreadUtil.createThread(x -> workTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + }); + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java b/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java index cdbc4bce1..34263eb69 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java @@ -3,13 +3,12 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; @@ -61,9 +60,10 @@ public void onPerform(CommandEvent commandEvent) { /** * Send the anime to the channel. + * * @param commandEvent the CommandEvent. - * @param message the Message. - * @param query the query. + * @param message the Message. + * @param query the query. */ public void sendAnime(CommandEvent commandEvent, Message message, String query) { RequestUtility.Request request = RequestUtility.Request.builder() @@ -131,6 +131,7 @@ public void sendAnime(CommandEvent commandEvent, Message message, String query) em.setTitle(name, url); em.setThumbnail(thumbnailUrl); em.setDescription(description); + em.setColor(BotConfig.getMainColor()); em.addField(":hourglass_flowing_sand: **" + commandEvent.getResource("label.status") + "**", status, true); em.addField(":dividers: **" + commandEvent.getResource("label.typ") + "**", type, true); em.addField(":arrow_right: **" + commandEvent.getResource("label.genres") + "**", genres, false); @@ -141,7 +142,7 @@ public void sendAnime(CommandEvent commandEvent, Message message, String query) em.addField(":trophy: **" + commandEvent.getResource("label.rank") + "**", "**TOP " + rank + "**", true); em.setFooter(commandEvent.getMember().getEffectiveName() + " - " + BotConfig.getAdvertisement(), commandEvent.getMember().getEffectiveAvatarUrl()); - if (commandEvent.isSlashCommand()) { + if (commandEvent.isSlashCommand() && !commandEvent.isDetached()) { message.editMessage(commandEvent.getResource("message.anime.found")).queue(); Main.getInstance().getCommandManager().sendMessage(em, commandEvent.getChannel(), null); } else { @@ -157,7 +158,7 @@ public void sendAnime(CommandEvent commandEvent, Message message, String query) */ @Override public CommandData getCommandData() { - return new CommandDataImpl("anime", LanguageService.getDefault("command.description.anime")) + return new CommandDataImpl("anime", "command.description.anime") .addOption(OptionType.STRING, "search", "The search query to search for.", true); } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java index 9081d1f24..247036ac7 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java @@ -1,12 +1,11 @@ package de.presti.ree6.commands.impl.fun; import com.google.gson.JsonArray; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -28,7 +27,7 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder em = new EmbedBuilder(); em.setTitle(commandEvent.getResource("label.randomCatImage")); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); em.setImage(js.get(0).getAsJsonObject().get("url").getAsString()); em.setFooter(commandEvent.getResource("label.footerMessage", commandEvent.getMember().getEffectiveName(), BotConfig.getAdvertisement()), commandEvent.getMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java b/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java index c895864da..4d134239a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java @@ -4,15 +4,13 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; /** * A command to let the bot response to the last Message with a cringe Image. */ -@Command(name = "cringe", description = "command.description.cringe", category = Category.FUN) +@Command(name = "cringe", description = "command.description.cringe", category = Category.FUN, allowAppInstall = false) public class Cringe implements ICommand { /** @@ -27,7 +25,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getChannel().getHistoryBefore(commandEvent.getMessage().getIdLong(), 1).complete().getRetrievedHistory().get(0).reply("https://images.ree6.de/cringe.gif").queue(); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** @@ -35,7 +33,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("shrekimage", LanguageService.getDefault("command.description.cringe_slash")); + return new CommandDataImpl("shrekimage", "command.description.cringe_slash"); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java index a33a1edd5..747c0070a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java @@ -1,12 +1,11 @@ package de.presti.ree6.commands.impl.fun; import com.google.gson.JsonObject; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -27,7 +26,7 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder em = new EmbedBuilder(); em.setTitle(commandEvent.getResource("label.randomDogImage")); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); em.setImage(js.get("message").getAsString()); em.setFooter(commandEvent.getResource("label.footerMessage", commandEvent.getMember().getEffectiveName(), BotConfig.getAdvertisement()), commandEvent.getMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Game.java b/src/main/java/de/presti/ree6/commands/impl/fun/Game.java index c1aa3d446..2fa79837a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Game.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Game.java @@ -4,12 +4,11 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.game.core.GameManager; -import de.presti.ree6.game.core.GameSession; -import de.presti.ree6.game.core.base.GameInfo; -import de.presti.ree6.game.core.base.GamePlayer; -import de.presti.ree6.game.core.base.GameState; -import de.presti.ree6.language.LanguageService; +import de.presti.ree6.module.game.core.GameManager; +import de.presti.ree6.module.game.core.GameSession; +import de.presti.ree6.module.game.core.base.GameInfo; +import de.presti.ree6.module.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GameState; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -23,7 +22,7 @@ /** * Command used to access the Game System. */ -@Command(name = "game", description = "command.description.game", category = Category.FUN) +@Command(name = "game", description = "command.description.game", category = Category.FUN, allowAppInstall = false) public class Game implements ICommand { /** @@ -52,7 +51,7 @@ public void onPerform(CommandEvent commandEvent) { if (GameManager.getGameNames().stream().noneMatch(c -> c.equalsIgnoreCase(nameMapping.getAsString().trim()))) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(commandEvent.getResource("message.game.availableGames")).append("```"); - GameManager.getGameCache().forEach((entry, entryValue) -> stringBuilder.append("\n").append(entry).append("- ").append(LanguageService.getByEvent(commandEvent,entryValue.getAnnotation(GameInfo.class).description()))); + GameManager.getGameCache().forEach((entry, entryValue) -> stringBuilder.append("\n").append(entry).append("- ").append(commandEvent.getResource(entryValue.getAnnotation(GameInfo.class).description()))); stringBuilder.append("```"); commandEvent.reply(stringBuilder.toString()); return; @@ -61,7 +60,7 @@ public void onPerform(CommandEvent commandEvent) { ArrayList participants = new ArrayList<>(); participants.add(commandEvent.getUser()); - GamePlayer gamePlayer = new GamePlayer(commandEvent.getMember().getUser()); + GamePlayer gamePlayer = new GamePlayer(commandEvent.getUser()); gamePlayer.setInteractionHook(commandEvent.getInteractionHook()); GameManager.createGameSession(GameManager.generateInvite(), nameMapping.getAsString(), commandEvent.getMember(), @@ -85,8 +84,8 @@ public void onPerform(CommandEvent commandEvent) { return; } - gameSession.getParticipants().add(commandEvent.getMember().getUser()); - GamePlayer gamePlayer = new GamePlayer(commandEvent.getMember().getUser()); + gameSession.getParticipants().add(commandEvent.getUser()); + GamePlayer gamePlayer = new GamePlayer(commandEvent.getUser()); gamePlayer.setInteractionHook(commandEvent.getInteractionHook()); gameSession.getGame().joinGame(gamePlayer); } @@ -94,7 +93,7 @@ public void onPerform(CommandEvent commandEvent) { case "list" -> { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(commandEvent.getResource("message.game.availableGames")).append("```"); - GameManager.getGameCache().forEach((entry, entryValue) -> stringBuilder.append("\n").append(entry).append(" ").append("-").append(" ").append(LanguageService.getByEvent(commandEvent,entryValue.getAnnotation(GameInfo.class).description()))); + GameManager.getGameCache().forEach((entry, entryValue) -> stringBuilder.append("\n").append(entry).append(" ").append("-").append(" ").append(commandEvent.getResource(entryValue.getAnnotation(GameInfo.class).description()))); stringBuilder.append("```"); commandEvent.reply(stringBuilder.toString()); } @@ -108,7 +107,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("game", LanguageService.getDefault("command.description.game")) + return new CommandDataImpl("game", "command.description.game") .addSubcommands(new SubcommandData("create", "Create a new Game match.") .addOptions(new OptionData(OptionType.STRING, "name", "The Game name.", true).addChoice("Blackjack", "blackjack").addChoice("Music Quiz", "musicquiz")), new SubcommandData("join", "Join a Game match.") diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java b/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java index d47407f0f..6bdd8b5c1 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.data.ImageCreationUtility; import net.dv8tion.jda.api.entities.Member; @@ -53,7 +52,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("behave", LanguageService.getDefault("command.description.hornyjail_slash")).addOptions(new OptionData(OptionType.USER, "target", "The User that should be put into the Hornyjail!").setRequired(true)); + return new CommandDataImpl("behave", "command.description.hornyjail_slash") + .addOptions(new OptionData(OptionType.USER, "target", "The User that should be put into the Hornyjail!").setRequired(true)); } /** @@ -73,9 +73,15 @@ public void sendHornyJail(Member member, CommandEvent commandEvent) { try { MessageCreateBuilder createBuilder = new MessageCreateBuilder(); createBuilder.addFiles(FileUpload.fromData(ImageCreationUtility.createHornyJailImage(member.getUser()), "hornyjail.png")); - Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.hornyJail", member.getAsMention()), commandEvent.getChannel(), commandEvent.getInteractionHook()); - commandEvent.getChannel().sendMessage(createBuilder.build()).queue(); - if (commandEvent.isSlashCommand()) commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + String messageContent = commandEvent.getResource("message.hornyJail", member.getAsMention()); + if (commandEvent.isDetached()) { + createBuilder.setContent(messageContent); + commandEvent.reply(createBuilder.build()); + } else { + Main.getInstance().getCommandManager().sendMessage(messageContent, commandEvent.getChannel(), commandEvent.getInteractionHook()); + commandEvent.getChannel().sendMessage(createBuilder.build()).queue(); + if (commandEvent.isSlashCommand()) commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + } } catch (Exception ex) { Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("command.perform.error"), commandEvent.getChannel(), commandEvent.getInteractionHook()); log.error("Error while sending Horny-jail!", ex); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java b/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java index 1985621f8..0da6b4e89 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.apis.Neko4JsAPI; import net.dv8tion.jda.api.entities.Member; @@ -12,6 +11,7 @@ import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.internal.interactions.CommandDataImpl; import pw.aru.api.nekos4j.image.Image; import pw.aru.api.nekos4j.image.ImageProvider; @@ -54,7 +54,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("hug", LanguageService.getDefault("command.description.hug")).addOptions(new OptionData(OptionType.USER, "target", "The User that should be hugged!").setRequired(true)); + return new CommandDataImpl("hug", "command.description.hug") + .addOptions(new OptionData(OptionType.USER, "target", "The User that should be hugged!").setRequired(true)); } /** @@ -71,7 +72,6 @@ public String[] getAlias() { * @param commandEvent The CommandEvent. */ public void sendHug(Member member, CommandEvent commandEvent) { - Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.hug", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); ImageProvider ip = Neko4JsAPI.imageAPI.getImageProvider(); @@ -81,8 +81,17 @@ public void sendHug(Member member, CommandEvent commandEvent) { } catch (Exception ignored) { } - Main.getInstance().getCommandManager().sendMessage((im != null ? im.getUrl() : "https://images.ree6.de/notfound.png"), commandEvent.getChannel(), null); - if (commandEvent.isSlashCommand()) commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + if (!commandEvent.isDetached()) { + Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.hug", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); + + Main.getInstance().getCommandManager().sendMessage((im != null ? im.getUrl() : "https://images.ree6.de/notfound.png"), commandEvent.getChannel(), null); + if (commandEvent.isSlashCommand()) + commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + } else { + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setContent(commandEvent.getResource("message.hug", member.getAsMention(), commandEvent.getMember().getAsMention()) + "\n" + (im != null ? im.getUrl() : "https://images.ree6.de/notfound.png")); + commandEvent.reply(messageCreateBuilder.build()); + } } } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java b/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java index 050a047a0..9d3bb8bea 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.apis.Neko4JsAPI; import net.dv8tion.jda.api.entities.Member; @@ -12,6 +11,7 @@ import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.internal.interactions.CommandDataImpl; import pw.aru.api.nekos4j.image.Image; import pw.aru.api.nekos4j.image.ImageProvider; @@ -54,7 +54,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("kiss", LanguageService.getDefault("command.description.kiss")) + return new CommandDataImpl("kiss", "command.description.kiss") .addOptions(new OptionData(OptionType.USER, "target", "The User that should be kissed!").setRequired(true)); } @@ -72,7 +72,6 @@ public String[] getAlias() { * @param commandEvent The command event. */ public void sendKiss(Member member, CommandEvent commandEvent) { - Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.kiss", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); ImageProvider ip = Neko4JsAPI.imageAPI.getImageProvider(); @@ -82,7 +81,16 @@ public void sendKiss(Member member, CommandEvent commandEvent) { } catch (Exception ignored) { } - Main.getInstance().getCommandManager().sendMessage((im != null ? im.getUrl() : "https://images.ree6.de/notfound.png"), commandEvent.getChannel(), null); - if (commandEvent.isSlashCommand()) commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + if (!commandEvent.isDetached()) { + Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.kiss", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); + + Main.getInstance().getCommandManager().sendMessage(im != null ? im.getUrl() : "https://images.ree6.de/notfound.png", commandEvent.getChannel(), null); + if (commandEvent.isSlashCommand()) + commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + } else { + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setContent(commandEvent.getResource("message.kiss", member.getAsMention(), commandEvent.getMember().getAsMention()) + "\n" + (im != null ? im.getUrl() : "https://images.ree6.de/notfound.png")); + commandEvent.reply(messageCreateBuilder.build()); + } } } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java b/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java index e62390981..0d8f3df19 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java @@ -3,13 +3,12 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; @@ -131,6 +130,7 @@ public void sendManga(CommandEvent commandEvent, Message message, String query) em.setTitle(name, url); em.setThumbnail(thumbnailUrl); em.setDescription(description); + em.setColor(BotConfig.getMainColor()); em.addField(":hourglass_flowing_sand: **" + commandEvent.getResource("label.status") + "**", status, true); em.addField(":dividers: **" + commandEvent.getResource("label.typ") + "**", type, true); em.addField(":arrow_right: **" + commandEvent.getResource("label.genres") + "**", genres, false); @@ -141,7 +141,7 @@ public void sendManga(CommandEvent commandEvent, Message message, String query) em.addField(":trophy: **" + commandEvent.getResource("label.rank") + "**", "**TOP " + rank + "**", true); em.setFooter(commandEvent.getMember().getEffectiveName() + " - " + BotConfig.getAdvertisement(), commandEvent.getMember().getEffectiveAvatarUrl()); - if (commandEvent.isSlashCommand()) { + if (commandEvent.isSlashCommand() && !commandEvent.isDetached()) { message.editMessage(commandEvent.getResource("message.manga.found")).queue(); Main.getInstance().getCommandManager().sendMessage(em, commandEvent.getChannel(), null); } else { @@ -203,7 +203,7 @@ public String tryResolvingGenres(JsonObject data) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("manga", LanguageService.getDefault("command.description.manga")) + return new CommandDataImpl("manga", "command.description.manga") .addOption(OptionType.STRING, "search", "The search query to search for.", true); } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java index 5b16f4c36..8b40966f7 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java @@ -1,12 +1,11 @@ package de.presti.ree6.commands.impl.fun; import com.google.gson.JsonObject; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -28,7 +27,7 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder em = new EmbedBuilder(); em.setTitle(commandEvent.getResource("label.randomMemeImage")); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); if (js.has("url")) { em.setImage(js.get("url").getAsString()); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Monkey.java b/src/main/java/de/presti/ree6/commands/impl/fun/Monkey.java index ac4d51c30..22786777e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Monkey.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Monkey.java @@ -1,11 +1,10 @@ package de.presti.ree6.commands.impl.fun; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -23,7 +22,7 @@ public void onPerform(CommandEvent commandEvent) { final EmbedBuilder em = new EmbedBuilder(); em.setTitle(commandEvent.getResource("label.monkey")); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); em.setImage("https://c.tenor.com/Y89PE1f7exQAAAAd/reject-modernity-return-to-monke.gif"); em.setFooter(commandEvent.getResource("label.footerMessage", commandEvent.getMember().getEffectiveName(), BotConfig.getAdvertisement()), commandEvent.getMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/PremiumCommand.java b/src/main/java/de/presti/ree6/commands/impl/fun/PremiumCommand.java index 724bcaa4d..87c083b69 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/PremiumCommand.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/PremiumCommand.java @@ -14,7 +14,7 @@ public class PremiumCommand implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { - if (GuildUtil.isSupporter(commandEvent.getMember().getUser())) { + if (GuildUtil.isSupporter(commandEvent.getUser())) { commandEvent.setEphemeral(false); commandEvent.reply("Thank you for helping with funding Ree6 " + commandEvent.getMember().getAsMention() + "!"); } else { diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Record.java b/src/main/java/de/presti/ree6/commands/impl/fun/Record.java index 19994dd86..99f8134e4 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Record.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Record.java @@ -6,20 +6,18 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.GuildVoiceState; import net.dv8tion.jda.api.entities.channel.ChannelType; -import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel; import net.dv8tion.jda.api.entities.channel.unions.AudioChannelUnion; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.managers.AudioManager; +import net.dv8tion.jda.internal.interactions.CommandDataImpl; /** * A command used to record the conversation of a voice channel. */ -@Command(name = "record", description = "command.description.record", category = Category.FUN) +@Command(name = "record", description = "command.description.record", category = Category.FUN, allowAppInstall = false) public class Record implements ICommand { /** @@ -86,7 +84,7 @@ public void connectAndRecord(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return null; + return new CommandDataImpl("record", "command.description.record"); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java index d85c6cd56..d69b4dd13 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java @@ -2,13 +2,11 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -36,11 +34,10 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder em = new EmbedBuilder(); em.setTitle(commandEvent.getResource("label.randomShibaImage")); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); em.setImage(js.get(0).getAsString()); em.setFooter(commandEvent.getResource("label.footerMessage", commandEvent.getMember().getEffectiveName(), BotConfig.getAdvertisement()), commandEvent.getMember().getEffectiveAvatarUrl()); - - Main.getInstance().getCommandManager().sendMessage(em, commandEvent.getChannel(), commandEvent.getInteractionHook()); + commandEvent.reply(em.build()); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java b/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java index 14a02c44e..cb3dbd806 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.apis.Neko4JsAPI; import net.dv8tion.jda.api.entities.Member; @@ -12,6 +11,7 @@ import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.internal.interactions.CommandDataImpl; import pw.aru.api.nekos4j.image.Image; import pw.aru.api.nekos4j.image.ImageProvider; @@ -54,7 +54,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("gracetheface", LanguageService.getDefault("command.description.slap")) + return new CommandDataImpl("gracetheface", "command.description.slap") .addOptions(new OptionData(OptionType.USER, "target", "The User that should be slapped!").setRequired(true)); } @@ -72,17 +72,24 @@ public String[] getAlias() { * @param commandEvent The CommandEvent. */ public void sendSlap(Member member, CommandEvent commandEvent) { - Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.slap", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); - ImageProvider ip = Neko4JsAPI.imageAPI.getImageProvider(); Image im = null; try { im = ip.getRandomImage("slap").execute(); - } catch (Exception ignored) { + } catch (Exception exception) { + log.error("Failed to get Image from Neko4J API!", exception); } - Main.getInstance().getCommandManager().sendMessage((im != null ? im.getUrl() : "https://images.ree6.de/notfound.png"), commandEvent.getChannel(), null); - if (commandEvent.isSlashCommand()) commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + if (!commandEvent.isDetached()) { + Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.slap", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); + Main.getInstance().getCommandManager().sendMessage(im != null ? im.getUrl() : "https://images.ree6.de/notfound.png", commandEvent.getChannel(), null); + if (commandEvent.isSlashCommand()) + commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + } else { + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setContent(commandEvent.getResource("message.slap", member.getAsMention(), commandEvent.getMember().getAsMention()) + "\n" + (im != null ? im.getUrl() : "https://images.ree6.de/notfound.png")); + commandEvent.reply(messageCreateBuilder.build()); + } } } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java b/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java index 093e9dac3..98f142d3b 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -61,7 +60,7 @@ public void onPerform(CommandEvent commandEvent) { sendTwitterTweet(commandEvent.getMessage().getMentions().getMembers().get(0), stringBuilder.toString(), commandEvent); } } else { - commandEvent.reply(commandEvent.getResource("message.default.usage","twitter @User Yourtexthere"), 5); + commandEvent.reply(commandEvent.getResource("message.default.usage", "twitter @User Yourtexthere"), 5); } } } @@ -71,7 +70,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("twitter", LanguageService.getDefault("command.description.twitter")) + return new CommandDataImpl("twitter", "command.description.twitter") .addOptions(new OptionData(OptionType.USER, "target", "The User that should tweet something!").setRequired(true)) .addOptions(new OptionData(OptionType.STRING, "content", "The Tweet Content!").setRequired(true)); } @@ -86,8 +85,9 @@ public String[] getAlias() { /** * The method to create the Tweet. - * @param member The Member that should tweet. - * @param content The content of the Tweet. + * + * @param member The Member that should tweet. + * @param content The content of the Tweet. * @param commandEvent The CommandEvent. */ public void sendTwitterTweet(Member member, String content, CommandEvent commandEvent) { @@ -102,10 +102,14 @@ public void sendTwitterTweet(Member member, String content, CommandEvent command MessageCreateBuilder createBuilder = new MessageCreateBuilder(); createBuilder.addFiles(FileUpload.fromData(response.getEntity().getContent().readAllBytes(), "twitter.png")); - commandEvent.getChannel().sendMessage(createBuilder.build()).queue(); + if (!commandEvent.isDetached()) { + commandEvent.getChannel().sendMessage(createBuilder.build()).queue(); - if (commandEvent.isSlashCommand()) - commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + if (commandEvent.isSlashCommand()) + commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + } else { + commandEvent.reply(createBuilder.build()); + } } catch (Exception ex) { commandEvent.reply(commandEvent.getResource("message.perform.error")); log.error("An error occurred while creating a Tweet!", ex); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java b/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java index cd97db826..ee467048b 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java @@ -2,11 +2,11 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -90,6 +90,7 @@ public void onPerform(CommandEvent commandEvent) { from = commandEvent.getResource("message.default.retrievalError"); } + em.setColor(BotConfig.getMainColor()); em.addField("**" + commandEvent.getResource("label.from") + "**", from, true); em.setFooter(commandEvent.getMember().getEffectiveName() + " - " + BotConfig.getAdvertisement(), commandEvent.getMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java index caf997154..b6bf20e6e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java @@ -1,17 +1,21 @@ package de.presti.ree6.commands.impl.hidden; -import de.presti.ree6.addons.AddonLoader; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; +import de.presti.ree6.commands.exceptions.CommandInitializerException; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import io.sentry.Sentry; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; +import org.pf4j.PluginState; +import org.pf4j.PluginWrapper; + +import java.nio.file.Path; +import java.util.List; /** * A command to either reload all Addons or list all of them. @@ -19,14 +23,12 @@ @Command(name = "addon", description = "command.description.addon", category = Category.HIDDEN) public class Addon implements ICommand { - // TODO:: add messages to language file. - /** * @inheritDoc */ @Override public void onPerform(CommandEvent commandEvent) { - if (!commandEvent.getMember().getUser().getId().equalsIgnoreCase(BotConfig.getBotOwner())) { + if (!commandEvent.isBotOwner()) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", "BE DEVELOPER"), 5); return; } @@ -41,15 +43,30 @@ public void onPerform(CommandEvent commandEvent) { switch (subcommand) { case "reload" -> { commandEvent.reply(commandEvent.getResource("message.addon.reloadAll")); - Main.getInstance().getAddonManager().reload(); + + List commands = Main.getInstance().getPluginManager().getExtensions(ICommand.class); + commands.forEach(command -> Main.getInstance().getCommandManager().removeCommand(command)); + Main.getInstance().getPluginManager().stopPlugins(); + Main.getInstance().getPluginManager().unloadPlugins(); + Main.getInstance().getPluginManager().loadPlugins(); + Main.getInstance().getPluginManager().startPlugins(); commandEvent.reply(commandEvent.getResource("message.addon.reloadedAll")); + + commands = Main.getInstance().getPluginManager().getExtensions(ICommand.class); + log.info("Found {} commands in all plugins.", commands.size()); + commands.forEach(command -> { + try { + Main.getInstance().getCommandManager().addCommand(command); + } catch (CommandInitializerException e) { + log.warn("Failed to initialize command: {}", command.getClass().getSimpleName(), e); + } + }); } case "list" -> { StringBuilder stringBuilder = new StringBuilder("```"); - for (de.presti.ree6.addons.Addon addon : Main.getInstance().getAddonManager().addons) { - stringBuilder.append(addon.getName()).append("v").append(addon.getVersion()) - .append(" ").append("for").append(" ").append("by").append(" ").append(addon.getAuthor()).append("\n"); + for (PluginWrapper addon : Main.getInstance().getPluginManager().getPlugins()) { + stringBuilder.append(addon.getPluginId()).append("v").append(addon.getDescriptor().getVersion()).append(" ").append("by").append(" ").append(addon.getDescriptor().getProvider()).append("\n"); } stringBuilder.append("```"); commandEvent.reply(commandEvent.getResource("message.addon.list") + " " + (stringBuilder.length() == 6 ? "None" : stringBuilder)); @@ -59,13 +76,10 @@ public void onPerform(CommandEvent commandEvent) { String addonName = commandEvent.getOption("addon").getAsString(); try { - de.presti.ree6.addons.Addon addon = AddonLoader.loadAddon(addonName); - if (addon == null) { - commandEvent.reply("Couldn't find a addon called " + addonName, 5); - return; - } - Main.getInstance().getAddonManager().loadAddon(addon); - Main.getInstance().getAddonManager().startAddon(addon); + String id = Main.getInstance().getPluginManager().loadPlugin(Path.of("plugins", addonName)); + PluginState state = Main.getInstance().getPluginManager().startPlugin(id); + + commandEvent.reply("Loading attempt for addon with the name " + addonName + " and id " + id + " resulted in: " + state); } catch (Exception exception) { commandEvent.reply("Couldn't load the addon called " + addonName, 5); Sentry.captureException(exception); @@ -73,13 +87,16 @@ public void onPerform(CommandEvent commandEvent) { } case "stop" -> { - de.presti.ree6.addons.Addon addon = Main.getInstance().getAddonManager().addons.stream() - .filter(a -> a.getName().equalsIgnoreCase(commandEvent.getOption("addon").getAsString())).findFirst().orElse(null); - - if (addon != null) { - Main.getInstance().getAddonManager().stopAddon(addon); - Main.getInstance().getAddonManager().addons.remove(addon); - commandEvent.reply("Stopped addon with the name " + addon.getName() + "!"); + String addonName = commandEvent.getOption("addon").getAsString(); + try { + if (Main.getInstance().getPluginManager().unloadPlugin(addonName)) { + commandEvent.reply("Unloaded addon with the name " + addonName + "!"); + } else { + commandEvent.reply("Couldn't unload the addon called " + addonName, 5); + } + } catch (Exception exception) { + commandEvent.reply("Couldn't unload the addon called " + addonName, 5); + Sentry.captureException(exception); } } diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java index fe6dd6d0e..242fa59f0 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java @@ -4,9 +4,7 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.news.AnnouncementManager; -import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.module.news.AnnouncementManager; import de.presti.ree6.utils.others.RandomUtils; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -26,7 +24,7 @@ public class Announcement implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { - if (!commandEvent.getMember().getUser().getId().equalsIgnoreCase(BotConfig.getBotOwner())) { + if (!commandEvent.isBotOwner()) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", "BE DEVELOPER"), 5); return; } @@ -41,8 +39,8 @@ public void onPerform(CommandEvent commandEvent) { OptionMapping toDeleteId = commandEvent.getOption("id"); if (title != null && content != null) { - de.presti.ree6.news.Announcement announcement = - new de.presti.ree6.news.Announcement(RandomUtils.randomString(16, false), title.getAsString(), + de.presti.ree6.module.news.Announcement announcement = + new de.presti.ree6.module.news.Announcement(RandomUtils.randomString(16, false), title.getAsString(), content.getAsString()); AnnouncementManager.addAnnouncement(announcement); @@ -62,7 +60,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("announcement", LanguageService.getDefault("command.description.announcement")) + return new CommandDataImpl("announcement","command.description.announcement") .addOptions(new OptionData(OptionType.STRING, "title", "The title of the announcement.", false), new OptionData(OptionType.STRING, "content", "The content of the announcement.", false), new OptionData(OptionType.STRING, "id", "The to delete announcement id.", false)); diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Debug.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Debug.java index 33e54b7ff..92c34ca97 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Debug.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Debug.java @@ -5,6 +5,7 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; +import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -13,6 +14,11 @@ public class Debug implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { + if (!commandEvent.isBotOwner()) { + commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", "BE DEVELOPER"), 5); + return; + } + StringBuilder debugInfo = new StringBuilder("```") .append("Build:").append(" ").append(BotWorker.getBuild()).append("\n") .append("Version:").append(" ").append(BotWorker.getVersion()).append("\n") @@ -27,6 +33,7 @@ public void onPerform(CommandEvent commandEvent) { .append("Java:").append(" ").append(System.getProperty("java.version")).append("\n") .append("OS:").append(" ").append(System.getProperty("os.name")).append("\n") .append("OS-Version:").append(" ").append(System.getProperty("os.version")).append("\n") + .append("Addons: ").append(" ").append(Main.getInstance().getPluginManager().getPlugins().size()).append("\n") .append("```"); commandEvent.reply(debugInfo.toString(), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java index f00405560..caf2517f1 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java @@ -5,7 +5,6 @@ import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.utils.data.ArrayUtil; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.interactions.commands.build.CommandData; /** @@ -19,7 +18,7 @@ public class Test implements ICommand { */ @Override public void onPerform(CommandEvent commandEvent) { - if (!commandEvent.getMember().getUser().getId().equalsIgnoreCase(BotConfig.getBotOwner())) { + if (!commandEvent.isBotOwner()) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", "BE DEVELOPER"), 5); return; } diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java b/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java index 5bdb8fb0b..7db17816a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java @@ -5,7 +5,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.utils.others.GuildUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.User; @@ -32,7 +31,7 @@ public void onPerform(CommandEvent commandEvent) { if (targetOption != null && targetOption.getAsMember() != null) { sendAvatar(targetOption.getAsUser(), commandEvent); } else { - sendAvatar(commandEvent.getMember().getUser(), commandEvent); + sendAvatar(commandEvent.getUser(), commandEvent); } } else { @@ -44,7 +43,7 @@ public void onPerform(CommandEvent commandEvent) { sendAvatar(commandEvent.getMessage().getMentions().getUsers().get(0), commandEvent); } } else { - sendAvatar(commandEvent.getMember().getUser(), commandEvent); + sendAvatar(commandEvent.getUser(), commandEvent); } } } @@ -54,7 +53,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("avatar", LanguageService.getDefault("command.description.avatar")) + return new CommandDataImpl("avatar", "command.description.avatar") .addOptions(new OptionData(OptionType.USER, "target", "The User whose profile you want.").setRequired(true)); } @@ -74,6 +73,7 @@ public String[] getAlias() { public void sendAvatar(User member, CommandEvent commandEvent) { EmbedBuilder em = new EmbedBuilder(); + em.setColor(BotConfig.getMainColor()); em.setTitle(commandEvent.getResource("label.avatar")); em.setAuthor(member.getEffectiveName() + (GuildUtil.isSupporter(member) ? " " : ""), member.getEffectiveAvatarUrl(), member.getEffectiveAvatarUrl()); em.setImage(member.getEffectiveAvatar().getUrl(1024)); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Help.java b/src/main/java/de/presti/ree6/commands/impl/info/Help.java index 91cf59e14..b5da63ece 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Help.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Help.java @@ -1,14 +1,12 @@ package de.presti.ree6.commands.impl.info; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.emoji.Emoji; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -61,43 +59,10 @@ public void sendHelpInformation(String categoryString, CommandEvent commandEvent EmbedBuilder em = new EmbedBuilder(); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); em.setTitle("Help Center"); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); - if (categoryString == null) { - String prefix = SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").getStringValue(); - for (Category cat : Category.values()) { - if (cat != Category.HIDDEN) { - if (!BotConfig.isModuleActive(cat.name().toLowerCase())) continue; - - String formattedName = cat.name().toUpperCase().charAt(0) + cat.name().substring(1).toLowerCase(); - em.addField("**" + formattedName + "**", prefix + "help " + cat.name().toLowerCase(), true); - } - } - } else { - if (isValid(categoryString)) { - StringBuilder end = new StringBuilder(); - - Category category = getCategoryFromString(categoryString); - - String prefix = SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").getStringValue(); - - for (ICommand cmd : Main.getInstance().getCommandManager().getCommands().stream().filter(command -> command.getClass().getAnnotation(Command.class).category() == category).toList()) { - end.append("``") - .append(prefix) - .append(cmd.getClass().getAnnotation(Command.class).name()) - .append("``\n") - .append(commandEvent.getResource(cmd.getClass().getAnnotation(Command.class).description())) - .append("\n\n"); - } - - em.setDescription(end.toString()); - } else { - sendHelpInformation(null, commandEvent); - return; - } - } messageCreateBuilder .addActionRow( @@ -111,7 +76,43 @@ public void sendHelpInformation(String categoryString, CommandEvent commandEvent Emoji.fromCustom("kiss", 1012765976951009361L, true)) ); - commandEvent.reply(messageCreateBuilder.setEmbeds(em.build()).build()); + if (categoryString == null) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").subscribe(setting -> { + for (Category cat : Category.values()) { + if (cat != Category.HIDDEN) { + if (!BotConfig.isModuleActive(cat.name().toLowerCase())) continue; + + String formattedName = cat.name().toUpperCase().charAt(0) + cat.name().substring(1).toLowerCase(); + em.addField("**" + formattedName + "**", setting.get().getStringValue() + "help " + cat.name().toLowerCase(), true); + } + } + + commandEvent.reply(messageCreateBuilder.setEmbeds(em.build()).build()); + }); + } else { + if (isValid(categoryString)) { + StringBuilder end = new StringBuilder(); + + Category category = getCategoryFromString(categoryString); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").subscribe(setting -> { + for (ICommand cmd : Main.getInstance().getCommandManager().getCommands().stream().filter(command -> command.getClass().getAnnotation(Command.class).category() == category).toList()) { + end.append("``") + .append(setting.get().getStringValue()) + .append(cmd.getClass().getAnnotation(Command.class).name()) + .append("``\n") + .append(commandEvent.getResource(cmd.getClass().getAnnotation(Command.class).description())) + .append("\n\n"); + } + + em.setDescription(end.toString()); + commandEvent.reply(messageCreateBuilder.setEmbeds(em.build()).build()); + }); + } else { + sendHelpInformation(null, commandEvent); + } + } + } /** @@ -127,7 +128,7 @@ public String[] getAlias() { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("help", LanguageService.getDefault("command.description.help")) + return new CommandDataImpl("help", "command.description.help") .addOptions(new OptionData(OptionType.STRING, "category", "Which Category you want to check out.")); } diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Info.java b/src/main/java/de/presti/ree6/commands/impl/info/Info.java index 2a42ea4b8..b6a2f6bf0 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Info.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Info.java @@ -1,11 +1,10 @@ package de.presti.ree6.commands.impl.info; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.GuildUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Member; @@ -57,7 +56,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("info", LanguageService.getDefault("command.description.info")) + return new CommandDataImpl("info", "command.description.info") .addOptions(new OptionData(OptionType.USER, "target", "The User whose profile Information you want.").setRequired(false)); } @@ -79,12 +78,9 @@ public void sendInfo(Member member, CommandEvent commandEvent) { em.setTitle(member.getEffectiveName() + (GuildUtil.isSupporter(member.getUser()) ? " " : "")); em.setThumbnail(member.getEffectiveAvatarUrl()); + em.setColor(BotConfig.getMainColor()); - if (member.getUser().getDiscriminator().equals("0000")) { - em.addField("**Username**", member.getUser().getName(), true); - } else { - em.addField("**UserTag**", member.getUser().getAsTag(), true); - } + em.addField("**Username**", member.getUser().getName(), true); em.addField("**Created Date**", member.getTimeCreated().toLocalDate().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")), true); em.addField("**Joined Date**", member.getTimeJoined().toLocalDate().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")), true); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java b/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java index 0d08efa67..43181f576 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java @@ -38,13 +38,13 @@ public void onPerform(CommandEvent commandEvent) { return; } - Warning warning = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())); - - if (warning != null) { - commandEvent.reply(commandEvent.getResource("message.infractions.success", member.getAsMention(), warning.getWarnings())); - } else { - commandEvent.reply(commandEvent.getResource("message.infractions.empty", member.getAsMention())); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())).subscribe(warning -> { + if (warning.isPresent()) { + commandEvent.reply(commandEvent.getResource("message.infractions.success", member.getAsMention(), warning.get().getWarnings())); + } else { + commandEvent.reply(commandEvent.getResource("message.infractions.empty", member.getAsMention())); + } + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Optout.java b/src/main/java/de/presti/ree6/commands/impl/info/Optout.java index 0d98e1ba6..54169f150 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Optout.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Optout.java @@ -18,13 +18,15 @@ public class Optout implements ICommand { */ @Override public void onPerform(CommandEvent commandEvent) { - if (SQLSession.getSqlConnector().getSqlWorker().isOptOut(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong())) { - SQLSession.getSqlConnector().getSqlWorker().optIn(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()); - commandEvent.reply(commandEvent.getResource("message.optout.optedIn")); - } else { - SQLSession.getSqlConnector().getSqlWorker().optOut(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()); - commandEvent.reply(commandEvent.getResource("message.optout.optedOut")); - } + SQLSession.getSqlConnector().getSqlWorker().isOptOut(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()).subscribe(value -> { + if (value) { + SQLSession.getSqlConnector().getSqlWorker().optIn(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()); + commandEvent.reply(commandEvent.getResource("message.optout.optedIn")); + } else { + SQLSession.getSqlConnector().getSqlWorker().optOut(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()); + commandEvent.reply(commandEvent.getResource("message.optout.optedOut")); + } + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Server.java b/src/main/java/de/presti/ree6/commands/impl/info/Server.java index f8e3cf267..8517d79c3 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Server.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Server.java @@ -1,11 +1,10 @@ package de.presti.ree6.commands.impl.info; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.GuildUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; @@ -29,7 +28,7 @@ public void onPerform(CommandEvent commandEvent) { if (commandEvent.getMember().hasPermission(Permission.ADMINISTRATOR)) { EmbedBuilder em = new EmbedBuilder(); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); Member owner = commandEvent.getGuild().getOwner(); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java index 80a1a3c4b..9493ec0fa 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java @@ -1,15 +1,14 @@ package de.presti.ree6.commands.impl.info; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.stats.CommandStats; import de.presti.ree6.sql.entities.stats.GuildCommandStats; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.TimeUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; @@ -32,28 +31,23 @@ public class Stats implements ICommand { */ @Override public void onPerform(CommandEvent commandEvent) { - - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); long start = System.currentTimeMillis(); - Message message = null; - if (commandEvent.isSlashCommand()) { - message = commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("label.loading")).complete(); - } else { - message = commandEvent.getChannel().sendMessage(commandEvent.getResource("label.loading")).complete(); - } + Message message = commandEvent.isSlashCommand() + ? commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("label.loading")).complete() + : commandEvent.getChannel().sendMessage(commandEvent.getResource("label.loading")).complete(); long ping = System.currentTimeMillis() - start; long computeTimeStart = System.currentTimeMillis(); - EmbedBuilder em = new EmbedBuilder(); em.setAuthor(commandEvent.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.statistics")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); long memberCount = firstBoot ? BotWorker.getShardManager().getUsers().size() : BotWorker.getShardManager().getUserCache().size(); firstBoot = true; @@ -63,13 +57,13 @@ public void onPerform(CommandEvent commandEvent) { em.addField("**" + commandEvent.getResource("label.users") + "**", String.valueOf(memberCount), true); em.addField("**" + commandEvent.getResource("label.botStats") + ":**", "", true); - em.addField("**" + commandEvent.getResource("label.version") + "**", BotWorker.getBuild() + "-" + BotWorker.getVersion().name().toUpperCase() + em.addField("**" + commandEvent.getResource("label.version") + "**", BotWorker.getBuild() + "-" + BotWorker.getVersion().getName().toUpperCase() + " [[" + BotWorker.getCommit() + "](" + BotWorker.getRepository().replace(".git", "") + "/commit/" + BotWorker.getCommit() + ")]", true); em.addField("**" + commandEvent.getResource("label.uptime") + "**", TimeUtil.getTime(BotWorker.getStartTime()), true); em.addField("**" + commandEvent.getResource("label.discordStats") + ":**", "", true); em.addField("**" + commandEvent.getResource("label.gatewayTime") + "**", BotWorker.getShardManager().getAverageGatewayPing() + "ms", true); - em.addField("**" + commandEvent.getResource("label.shardAmount") + "**", BotWorker.getShardManager().getShards().size() + " " + commandEvent.getResource("label.shards"), true); + em.addField("**" + commandEvent.getResource("label.shardAmount") + "**", BotWorker.getShardManager().getShards().size() + " " + commandEvent.getResource("label.shards"), true); em.addField("**" + commandEvent.getResource("label.networkStats") + ":**", "", true); em.addField("**" + commandEvent.getResource("label.responseTime") + "**", (Integer.parseInt((ping) + "")) + "ms", true); @@ -77,37 +71,41 @@ public void onPerform(CommandEvent commandEvent) { StringBuilder end = new StringBuilder(); - for (GuildCommandStats values : SQLSession.getSqlConnector().getSqlWorker().getStats(commandEvent.getGuild().getIdLong())) { - end.append(values.getCommand()).append(" - ").append(values.getUses()).append("\n"); - } + SQLSession.getSqlConnector().getSqlWorker().getStats(commandEvent.getGuild().getIdLong()).subscribe(stats -> { + for (GuildCommandStats values : stats) { + end.append(values.getCommand()).append(" - ").append(values.getUses()).append("\n"); + } - StringBuilder end2 = new StringBuilder(); + StringBuilder end2 = new StringBuilder(); - for (CommandStats values : SQLSession.getSqlConnector().getSqlWorker().getStatsGlobal()) { - end2.append(values.getCommand()).append(" - ").append(values.getUses()).append("\n"); - } + SQLSession.getSqlConnector().getSqlWorker().getStatsGlobal().subscribe(statsGlobal -> { + for (CommandStats values : statsGlobal) { + end2.append(values.getCommand()).append(" - ").append(values.getUses()).append("\n"); + } - em.addField("**" + commandEvent.getResource("label.commandStats") + ":**", "", true); - em.addField("**" + commandEvent.getResource("label.topCommands") + "**", end.toString(), true); - em.addField("**" + commandEvent.getResource("label.overallTopCommands") + "**", end2.toString(), true); + em.addField("**" + commandEvent.getResource("label.commandStats") + ":**", "", true); + em.addField("**" + commandEvent.getResource("label.topCommands") + "**", end.toString(), true); + em.addField("**" + commandEvent.getResource("label.overallTopCommands") + "**", end2.toString(), true); - em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); + em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); - MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); + MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); - messageEditBuilder.setContent(""); + messageEditBuilder.setContent(""); - long computeTime = System.currentTimeMillis() - computeTimeStart; + long computeTime = System.currentTimeMillis() - computeTimeStart; - if (BotConfig.isDebug()) { - em.addField("**DEV ONLY**", "", true); - em.addField("**Compute Time**", computeTime + "ms", true); - em.addField("**DEV ONLY*", "", true); - } + if (BotConfig.isDebug()) { + em.addField("**DEV ONLY**", "", true); + em.addField("**Compute Time**", computeTime + "ms", true); + em.addField("**App Installs**", "" + BotWorker.getShardManager().retrieveApplicationInfo().complete().getUserInstallCount(), true); + } - messageEditBuilder.setEmbeds(em.build()); + messageEditBuilder.setEmbeds(em.build()); - commandEvent.update(message, messageEditBuilder.build()); + commandEvent.update(message, messageEditBuilder.build()); + }); + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/level/Level.java b/src/main/java/de/presti/ree6/commands/impl/level/Level.java index 5fa3696c2..2ec08ff93 100644 --- a/src/main/java/de/presti/ree6/commands/impl/level/Level.java +++ b/src/main/java/de/presti/ree6/commands/impl/level/Level.java @@ -4,9 +4,7 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.level.UserLevel; import de.presti.ree6.utils.data.ImageCreationUtility; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -49,7 +47,7 @@ public void onPerform(CommandEvent commandEvent) { sendLevel(commandEvent.getMessage().getMentions().getMembers().get(0), commandEvent, typ); } } else { - commandEvent.reply(commandEvent.getResource("message.default.usage","level chat/voice [@user]")); + commandEvent.reply(commandEvent.getResource("message.default.usage", "level chat/voice [@user]")); } } } @@ -59,7 +57,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("level", LanguageService.getDefault("command.description.level")).addOptions(new OptionData(OptionType.STRING, "typ", "Do you want to see chat or voice level?")) + return new CommandDataImpl("level", "command.description.level") + .addOptions(new OptionData(OptionType.STRING, "typ", "Do you want to see chat or voice level?")) .addOptions(new OptionData(OptionType.USER, "target", "Show the Level of the User.")); } @@ -68,29 +67,30 @@ public CommandData getCommandData() { */ @Override public String[] getAlias() { - return new String[] {"lvl", "xp", "rank"}; + return new String[]{"lvl", "xp", "rank"}; } /** * Sends the Level of the User. - * @param member The Member to get the Level of. + * + * @param member The Member to get the Level of. * @param commandEvent The CommandEvent. - * @param type The Type of the Level. + * @param type The Type of the Level. */ public void sendLevel(Member member, CommandEvent commandEvent, String type) { - - UserLevel userLevel = type.equalsIgnoreCase("voice") ? + (type.equalsIgnoreCase("voice") ? SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong()) : - SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong()); - - try { - MessageCreateBuilder createBuilder = new MessageCreateBuilder(); - createBuilder.addFiles(FileUpload.fromData(ImageCreationUtility.createRankImage(userLevel), "rank.png")); + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong())).subscribe(userLevel -> + SQLSession.getSqlConnector().getSqlWorker().getUserRankCard(member.getIdLong()).subscribe(rankCard -> { + try { + MessageCreateBuilder createBuilder = new MessageCreateBuilder(); + createBuilder.addFiles(FileUpload.fromData(ImageCreationUtility.createRankImage(userLevel, rankCard), "rank.png")); - commandEvent.reply(createBuilder.build()); - } catch (Exception exception) { - commandEvent.reply(commandEvent.getResource("command.perform.error")); - log.error("Couldn't generated Rank Image!", exception); - } + commandEvent.reply(createBuilder.build()); + } catch (Exception exception) { + commandEvent.reply(commandEvent.getResource("command.perform.error")); + log.error("Couldn't generated Rank Image!", exception); + } + })); } } diff --git a/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java b/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java index f3d8df18f..19cee1c10 100644 --- a/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java +++ b/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Role; @@ -75,22 +74,23 @@ public void onPerform(CommandEvent commandEvent) { } commandEvent.reply(commandEvent.getResource("message.levelRole.removed", role.getName(), level)); } - case "list" -> { - MessageCreateBuilder createBuilder = new MessageCreateBuilder(); - StringBuilder voiceStringBuilder = new StringBuilder(); - StringBuilder chatStringBuilder = new StringBuilder(); - createBuilder.setContent(commandEvent.getResource("message.levelRole.list")); + case "list" -> + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(commandEvent.getGuild().getIdLong()).subscribe(level -> { + MessageCreateBuilder createBuilder = new MessageCreateBuilder(); + StringBuilder voiceStringBuilder = new StringBuilder(); + StringBuilder chatStringBuilder = new StringBuilder(); + createBuilder.setContent(commandEvent.getResource("message.levelRole.list")); - SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(commandEvent.getGuild().getIdLong()) - .forEach((level1, role1) -> voiceStringBuilder.append(level1).append(" -> ").append(role1)); - SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(commandEvent.getGuild().getIdLong()) - .forEach((level1, role1) -> chatStringBuilder.append(level1).append(" -> ").append(role1)); + level.forEach((level1, role1) -> voiceStringBuilder.append(level1).append(" -> ").append(role1)); - createBuilder.addFiles(FileUpload.fromData(voiceStringBuilder.toString().getBytes(StandardCharsets.UTF_8), "voice.txt"), - FileUpload.fromData(chatStringBuilder.toString().getBytes(StandardCharsets.UTF_8), "chat.txt")); + SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(commandEvent.getGuild().getIdLong()).block() + .forEach((level2, role2) -> chatStringBuilder.append(level2).append(" -> ").append(role2)); - commandEvent.reply(createBuilder.build()); - } + createBuilder.addFiles(FileUpload.fromData(voiceStringBuilder.toString().getBytes(StandardCharsets.UTF_8), "voice.txt"), + FileUpload.fromData(chatStringBuilder.toString().getBytes(StandardCharsets.UTF_8), "chat.txt")); + + commandEvent.reply(createBuilder.build()); + }); default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); } @@ -102,7 +102,7 @@ public void onPerform(CommandEvent commandEvent) { @Override public CommandData getCommandData() { return new CommandDataImpl("levelrole", - LanguageService.getDefault("command.description.levelrole")) + "command.description.levelrole") .addSubcommands(new SubcommandData("add", "Add a new Level-Role") .addOptions(new OptionData(OptionType.BOOLEAN, "voice", "True -> Voice-Level and False -> Text-Level").setRequired(true), new OptionData(OptionType.INTEGER, "level", "The level that needs to be reached to get the role.").setRequired(true).setMinValue(1), diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java b/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java index f9431b3ab..0147ba78b 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; @@ -74,7 +72,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.ADMINISTRATOR.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** @@ -82,7 +80,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("ban", LanguageService.getDefault("command.description.ban")) + return new CommandDataImpl("ban", "command.description.ban") .addOptions(new OptionData(OptionType.USER, "target", "Which User should be banned.", true)) .addOptions(new OptionData(OptionType.INTEGER, "del_days", "Delete messages from the past days.") .setRequiredRange(0, 7)) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java index c95c61283..d60d87e60 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.main.Main; import de.presti.ree6.utils.others.ModerationUtil; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -58,20 +57,22 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.blacklist.removed", word), 5); } - default -> { - if (ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong())) { - StringBuilder end = new StringBuilder(); + default -> ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { + if (aBoolean) { + ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong()).subscribe(blacklists -> { + StringBuilder end = new StringBuilder(); - for (String s : ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong())) { - end.append("\n").append(s); - } + for (String s : blacklists) { + end.append("\n").append(s); + } - commandEvent.reply("```" + end + "```"); + commandEvent.reply("```" + end + "```"); + }); } else { commandEvent.reply(commandEvent.getResource("message.blacklist.setupNeeded")); commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist add [WORD...]"), 5); } - } + }); } } else { @@ -84,18 +85,22 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.invalidQuery"), 5); commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist remove WORD"), 5); } else if (commandEvent.getArguments()[0].equalsIgnoreCase("list")) { - if (ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong())) { - StringBuilder end = new StringBuilder(); - - for (String s : ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong())) { - end.append("\n").append(s); + ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { + if (aBoolean) { + ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong()).subscribe(blacklists -> { + StringBuilder end = new StringBuilder(); + + for (String s : blacklists) { + end.append("\n").append(s); + } + + commandEvent.reply("```" + end + "```"); + }); + } else { + commandEvent.reply(commandEvent.getResource("message.blacklist.setupNeeded")); + commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist add [WORD...]"), 5); } - - commandEvent.reply("```" + end + "```"); - } else { - commandEvent.reply(commandEvent.getResource("message.blacklist.setupNeeded")); - commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist add [WORD...]"), 5); - } + }); } else { commandEvent.reply(commandEvent.getResource("message.blacklist.notFound", commandEvent.getArguments()[0]), 5); commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist add/remove/list"), 5); @@ -131,7 +136,7 @@ public void onPerform(CommandEvent commandEvent) { } else { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.ADMINISTRATOR.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java b/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java index a13728d44..26abda5e3 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -67,7 +65,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("clear", LanguageService.getDefault("command.description.clear")) + return new CommandDataImpl("clear", "command.description.clear") .addOptions(new OptionData(OptionType.INTEGER, "amount", "How many messages should be removed.") .setRequired(true) .setMinValue(2) @@ -92,7 +90,7 @@ public void deleteMessages(CommandEvent commandEvent, int amount) { if (amount <= 200 && amount >= 2) { try { - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); commandEvent.getChannel().getIterableHistory().takeAsync(amount).thenAccept(messages -> { commandEvent.getChannel().purgeMessages(messages); commandEvent.reply(commandEvent.getResource("message.clear.success", amount), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java b/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java index 5201a4446..68fc9b49e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; @@ -93,7 +92,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("embed", LanguageService.getDefault("command.description.embedSender")) + return new CommandDataImpl("embed", "command.description.embedSender") .addOption(OptionType.STRING, "title", "The title of the embed!", true) .addOption(OptionType.STRING, "description", "The description of the embed!", true) .addOption(OptionType.INTEGER, "color", "The color of the embed!", false) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java index 6239f6166..514a5f8f2 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java @@ -10,7 +10,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.level.ChatUserLevel; import de.presti.ree6.utils.apis.AmariAPI; @@ -71,19 +70,19 @@ public void importFromMee6(CommandEvent commandEvent) { JsonElement xp = player.getAsJsonObject().get("xp"); if (id.isJsonPrimitive() && xp.isJsonPrimitive()) { - ChatUserLevel chatUserLevel = SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), id.getAsLong()); - - if (chatUserLevel != null && chatUserLevel.getExperience() > xp.getAsLong()) { - return; - } - - if (chatUserLevel == null) { - chatUserLevel = new ChatUserLevel(commandEvent.getGuild().getIdLong(), id.getAsLong(), xp.getAsLong()); - } else { - chatUserLevel.setExperience(xp.getAsLong()); - } - - SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel); + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), id.getAsLong()).subscribe(chatUserLevel -> { + if (chatUserLevel != null && chatUserLevel.getExperience() > xp.getAsLong()) { + return; + } + + if (chatUserLevel == null) { + chatUserLevel = new ChatUserLevel(commandEvent.getGuild().getIdLong(), id.getAsLong(), xp.getAsLong()); + } else { + chatUserLevel.setExperience(xp.getAsLong()); + } + + SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel).block(); + }); } } }); @@ -121,9 +120,8 @@ public void importFromAmari(CommandEvent commandEvent) { try { Leaderboard leaderboard = AmariAPI.getAmari4J().getRawLeaderboard(commandEvent.getGuild().getId(), Integer.MAX_VALUE); - leaderboard.getMembers().forEach(member -> { - ChatUserLevel chatUserLevel = SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid())); - + leaderboard.getMembers().forEach(member -> + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid())).subscribe(chatUserLevel -> { if (chatUserLevel != null && chatUserLevel.getExperience() > member.getExperience()) { return; } @@ -134,8 +132,8 @@ public void importFromAmari(CommandEvent commandEvent) { chatUserLevel.setExperience(member.getExperience()); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel); - }); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel).block(); + })); commandEvent.reply(commandEvent.getResource("message.import.success", leaderboard.getCount()), 5); } catch (InvalidAPIKeyException | InvalidServerResponseException | RateLimitException e) { // TODO:: make some extra stuff for the rate-limit. @@ -151,7 +149,8 @@ public void importFromAmari(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("import", LanguageService.getDefault("command.description.import")).addOption(OptionType.STRING, "bot", "The Bot you want to import data from.", true); + return new CommandDataImpl("import", "command.description.import") + .addOption(OptionType.STRING, "bot", "The Bot you want to import data from.", true); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java b/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java index fead46c39..e0bb277b0 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; @@ -62,7 +60,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.KICK_MEMBERS.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** @@ -70,7 +68,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("kick", LanguageService.getDefault("command.description.kick")) + return new CommandDataImpl("kick", "command.description.kick") .addOptions(new OptionData(OptionType.USER, "target", "Which User should be kicked.").setRequired(true)) .addOptions(new OptionData(OptionType.STRING, "reason", "The Reason why the User should be kicked.").setRequired(false)) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.KICK_MEMBERS)); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java b/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java index 7232325e4..8d74cecb2 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; @@ -80,7 +78,7 @@ public void onPerform(CommandEvent commandEvent) { } else { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.MODERATE_MEMBERS.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** @@ -88,7 +86,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("mute", LanguageService.getDefault("command.description.mute")) + return new CommandDataImpl("mute", "command.description.mute") .addOptions(new OptionData(OptionType.USER, "target", "Which User should be muted.").setRequired(true)) .addOptions(new OptionData(OptionType.INTEGER, "time", "How long the User should be muted for. (in minutes)").setRequired(true)) .addOptions(new OptionData(OptionType.STRING, "reason", "The Reason why the User should be muted.").setRequired(false)) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/News.java b/src/main/java/de/presti/ree6/commands/impl/mod/News.java index b3a6fa630..454cc708e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/News.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/News.java @@ -25,23 +25,25 @@ public void onPerform(CommandEvent commandEvent) { return; } - Setting setting = SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news"); + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").subscribe(settingOptional -> { + if (settingOptional.isEmpty()) { + SQLSession.getSqlConnector().getSqlWorker().setSetting(commandEvent.getGuild().getIdLong(), "configuration_news", "Receive News", true); + commandEvent.reply(commandEvent.getResource("message.news.enabled"), 5); + return; + } - if (setting == null) { - SQLSession.getSqlConnector().getSqlWorker().setSetting(commandEvent.getGuild().getIdLong(), "configuration_news", "Receive News", true); - commandEvent.reply(commandEvent.getResource("message.news.enabled"), 5); - return; - } + Setting setting = settingOptional.get(); - if (setting.getBooleanValue()) { - setting.setValue(false); - commandEvent.reply(commandEvent.getResource("message.news.disabled"), 5); - } else { - setting.setValue(true); - commandEvent.reply(commandEvent.getResource("message.news.enabled"), 5); - } + if (setting.getBooleanValue()) { + setting.setValue(false); + commandEvent.reply(commandEvent.getResource("message.news.disabled"), 5); + } else { + setting.setValue(true); + commandEvent.reply(commandEvent.getResource("message.news.enabled"), 5); + } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(setting); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(setting).block(); + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java b/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java index 70e502924..cd4eb16cb 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; @@ -56,7 +55,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("prefix", LanguageService.getDefault("command.description.prefix")) + return new CommandDataImpl("prefix", "command.description.prefix") .addOptions(new OptionData(OptionType.STRING, "new-prefix", "What should the new Prefix be?").setRequired(true)) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.ADMINISTRATOR, Permission.MANAGE_SERVER)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index 98fda4648..8dbd66690 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -7,7 +7,6 @@ import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.sql.entities.TemporalVoicechannel; @@ -17,6 +16,7 @@ import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.channel.ChannelType; import net.dv8tion.jda.api.entities.channel.unions.GuildChannelUnion; @@ -32,6 +32,7 @@ import net.dv8tion.jda.api.interactions.components.selections.SelectOption; import net.dv8tion.jda.internal.interactions.CommandDataImpl; import net.dv8tion.jda.internal.interactions.component.StringSelectMenuImpl; +import reactor.core.publisher.Mono; import java.awt.*; import java.io.InputStream; @@ -90,7 +91,7 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(commandEvent.getResource("label.setup")) .setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) - .setColor(Color.cyan) + .setColor(BotConfig.getMainColor()) .setDescription(commandEvent.getResource("message.setup.setupMenu")); List optionList = new ArrayList<>(); @@ -113,15 +114,20 @@ public void onPerform(CommandEvent commandEvent) { .addActionRow(selectMenu).queue(); } } else if (commandEvent.getSubcommand().equalsIgnoreCase("autorole")) { - if (commandEvent.isSlashCommand()) { - commandEvent.getInteractionHook().sendMessageEmbeds(createAutoRoleSetupMessage(commandEvent.getGuild(), commandEvent.getInteractionHook()).build()) - .addActionRow(createAutoRoleSetupSelectMenu(commandEvent.getGuild(), commandEvent.getInteractionHook())) - .addActionRow(Button.link(BotConfig.getWebinterface(), "Webinterface")).queue(); - } else { - commandEvent.getChannel().sendMessageEmbeds(createAutoRoleSetupMessage(commandEvent.getGuild(), commandEvent.getInteractionHook()).build()) - .addActionRow(createAutoRoleSetupSelectMenu(commandEvent.getGuild(), commandEvent.getInteractionHook())) - .addActionRow(Button.link(BotConfig.getWebinterface(), "Webinterface")).queue(); - } + createAutoRoleSetupSelectMenu(commandEvent.getGuild(), commandEvent.getInteractionHook()).subscribe(menu -> { + MessageEmbed embed = createAutoRoleSetupMessage(commandEvent.getGuild(), commandEvent.getInteractionHook()).build(); + Button webinterface = Button.link(BotConfig.getWebinterface(), "Webinterface"); + + if (commandEvent.isSlashCommand()) { + commandEvent.getInteractionHook().sendMessageEmbeds(embed) + .addActionRow(menu) + .addActionRow(webinterface).queue(); + } else { + commandEvent.getChannel().sendMessageEmbeds(embed) + .addActionRow(menu) + .addActionRow(webinterface).queue(); + } + }); } } else { OptionMapping optionMapping = commandEvent.getOption("channel"); @@ -142,24 +148,28 @@ public void onPerform(CommandEvent commandEvent) { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.TEXT) { - guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Logs").queue(webhook -> { - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong())); + guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Logs").queue(webhook -> SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { + if (aBoolean) { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> webhookEntity.ifPresent(entity -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); } SQLSession.getSqlConnector().getSqlWorker().setLogWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); commandEvent.reply(commandEvent.getResource("message.auditLog.setupSuccess")); - }); + })); } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } } else { - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong())); - commandEvent.reply(commandEvent.getResource("message.auditLog.deleted")); - } else { - commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); - } + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { + if (aBoolean) { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> { + webhookEntity.ifPresent(entity -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity)); + commandEvent.reply(commandEvent.getResource("message.auditLog.deleted")); + }); + } else { + commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); + } + }); } } case "welcome" -> { @@ -170,42 +180,43 @@ public void onPerform(CommandEvent commandEvent) { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.TEXT) { - guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Welcome").queue(webhook -> { - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong())); + guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Welcome").queue(webhook -> SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { + if (aBoolean) { + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> webhookEntity.ifPresent(entity -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); } - SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); commandEvent.reply(commandEvent.getResource("message.welcome.setupSuccess")); - }); + })); } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } } else { - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong())); - commandEvent.reply(commandEvent.getResource("message.welcome.deleted")); - } else { + SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { + if (aBoolean) { + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> + webhookEntity.ifPresent(entity -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); + commandEvent.reply(commandEvent.getResource("message.welcome.deleted")); + } commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); - } + }); } } case "tempvoice" -> { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.VOICE) { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong())); - commandEvent.reply(commandEvent.getResource("message.temporalVoice.setupSuccess")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong())).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.temporalVoice.setupSuccess"))); } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } } else { - TemporalVoicechannel temporalVoicechannel = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())); - if (temporalVoicechannel != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel); - commandEvent.reply(commandEvent.getResource("message.temporalVoice.deleted")); - } else { - commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())).subscribe(temporalVoicechannel -> { + if (temporalVoicechannel.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel.get()).block(); + commandEvent.reply(commandEvent.getResource("message.temporalVoice.deleted")); + } else { + commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); + } + }); } } case "rewards" -> { @@ -241,7 +252,7 @@ public void onPerform(CommandEvent commandEvent) { for (Setting setting : SettingsManager.getSettings()) { if (!setting.getName().startsWith("configuration_rewards_")) continue; - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Setting(commandEvent.getGuild().getIdLong(), setting.getName(), setting.getDisplayName(), setting.getValue())); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Setting(commandEvent.getGuild().getIdLong(), setting.getName(), setting.getDisplayName(), setting.getValue())).block(); } commandEvent.reply(commandEvent.getResource("message.rewards.success")); @@ -252,38 +263,40 @@ public void onPerform(CommandEvent commandEvent) { } else { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.ADMINISTRATOR.name() + "/" + Permission.MANAGE_SERVER.name())); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } public static EmbedBuilder createAutoRoleSetupMessage(Guild guild, InteractionHook interactionHook) { - boolean hasRoles = !GuildUtil.getManagableRoles(guild).isEmpty(); + boolean hasRoles = !GuildUtil.getManageableRoles(guild).isEmpty(); return new EmbedBuilder() - .setTitle(LanguageService.getByGuildOrInteractionHook(guild, interactionHook,"label.setup")) + .setTitle(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, "label.setup").block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()) - .setColor(hasRoles ? Color.cyan : Color.red) - .setDescription(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, hasRoles ? "message.autoRole.setupDescription" : "message.default.needPermission", (hasRoles ? null : Permission.MANAGE_ROLES.name()))); + .setColor(hasRoles ? BotConfig.getMainColor() : Color.RED) + .setDescription(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, hasRoles ? "message.autoRole.setupDescription" : "message.default.needPermission", (hasRoles ? null : Permission.MANAGE_ROLES.name())).block()); } - public static SelectMenu createAutoRoleSetupSelectMenu(Guild guild, InteractionHook interactionHook) { + public static Mono createAutoRoleSetupSelectMenu(Guild guild, InteractionHook interactionHook) { List optionList = new ArrayList<>(); - for (Role role : GuildUtil.getManagableRoles(guild)) { + for (Role role : GuildUtil.getManageableRoles(guild)) { optionList.add(SelectOption.of(role.getName(), role.getId())); } - SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong()).forEach(autoRole -> { - SelectOption option = optionList.stream().filter(selectOption -> selectOption.getValue().equals(String.valueOf(autoRole.getRoleId()))).findFirst().orElse(null); - if (option != null) { - optionList.remove(option); - optionList.add(option.withDefault(true)); - } - }); + return SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong()).map(list -> { + list.forEach(autoRole -> { + SelectOption option = optionList.stream().filter(selectOption -> selectOption.getValue().equals(String.valueOf(autoRole.getRoleId()))).findFirst().orElse(null); + if (option != null) { + optionList.remove(option); + optionList.add(option.withDefault(true)); + } + }); - return new StringSelectMenuImpl("setupAutoRole", LanguageService.getByGuildOrInteractionHook(guild, interactionHook, - "message.autoRole.setupPlaceholder"), - 0, Math.min(10, Math.max(1, optionList.size())), optionList.isEmpty(), optionList); + return new StringSelectMenuImpl("setupAutoRole", LanguageService.getByGuildOrInteractionHook(guild, interactionHook, + "message.autoRole.setupPlaceholder").block(), + 0, Math.min(10, Math.max(1, optionList.size())), optionList.isEmpty(), optionList); + }); } /** @@ -297,15 +310,18 @@ public CommandData getCommandData() { .addSubcommandGroups( new SubcommandGroupData("auditlog", "Auditlog Setup") .addSubcommands(new SubcommandData("set", "Set the Auditlog channel.") - .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Welcome Channel.", true).setChannelTypes(ChannelType.TEXT))) + .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Welcome Channel.", true) + .setChannelTypes(ChannelType.TEXT))) .addSubcommands(new SubcommandData("remove", "Remove the Auditlog channel.")), new SubcommandGroupData("welcome", "Welcome Setup") .addSubcommands(new SubcommandData("set", "Set the Welcome channel.") - .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Auditlog Channel.", true).setChannelTypes(ChannelType.TEXT))) + .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Auditlog Channel.", true) + .setChannelTypes(ChannelType.TEXT))) .addSubcommands(new SubcommandData("remove", "Remove the Welcome channel.")), new SubcommandGroupData("tempvoice", "Temporal Voice Setup") .addSubcommands(new SubcommandData("set", "Set a Temporal Voice Channel.") - .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Temporal Voice Channel.", true).setChannelTypes(ChannelType.VOICE))) + .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Temporal Voice Channel.", true) + .setChannelTypes(ChannelType.VOICE))) .addSubcommands(new SubcommandData("remove", "Remove a Temporal Voice Channel.")), // TODO:: think about a better way to implement it. /*new SubcommandGroupData("statistics", "Statistics Setup") diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java index efa5f26f4..a66511cd9 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java @@ -1,14 +1,13 @@ package de.presti.ree6.commands.impl.mod; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Suggestions; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.channel.ChannelType; @@ -21,6 +20,7 @@ import net.dv8tion.jda.api.interactions.components.buttons.Button; import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.internal.interactions.CommandDataImpl; +import reactor.core.scheduler.Schedulers; import java.awt.*; import java.util.Map; @@ -68,35 +68,41 @@ public void onPerform(CommandEvent commandEvent) { /** * Create all the entries needed. - * @param commandEvent The CommandEvent. - * @param channel the Suggestion channel. + * + * @param commandEvent The CommandEvent. + * @param channel the Suggestion channel. * @param messageChannel the Channel for the Message. */ public void createSuggestions(CommandEvent commandEvent, MessageChannel channel, MessageChannel messageChannel) { - MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(commandEvent.getResource("label.suggestionMenu")); - embedBuilder.setColor(Color.ORANGE); - embedBuilder.setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_suggestion_menu").getStringValue()); - embedBuilder.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); - messageCreateBuilder.setEmbeds(embedBuilder.build()); - messageCreateBuilder.setActionRow(Button.primary("re_suggestion", commandEvent.getResource("message.suggestion.suggestionMenuPlaceholder"))); - - Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), messageChannel); - - Suggestions suggestions = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId = :id", Map.of("id", commandEvent.getGuild().getIdLong())); - if (suggestions != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(suggestions); - - suggestions.getGuildChannelId().setChannelId(channel.getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions); - } else { - suggestions = new Suggestions(commandEvent.getGuild().getIdLong(), channel.getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId = :id", Map.of("id", commandEvent.getGuild().getIdLong())) + .publishOn(Schedulers.boundedElastic()) + .mapNotNull(suggestionsOptional -> { + if (suggestionsOptional.isPresent()) { + Suggestions suggestions = suggestionsOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(suggestions).block(); + + suggestions.getGuildChannelId().setChannelId(channel.getIdLong()); + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions).block(); + } else { + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Suggestions(commandEvent.getGuild().getIdLong(), channel.getIdLong())).block(); + } + }).subscribe(suggestions -> SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_suggestion_menu").subscribe(setting -> { + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(BotConfig.getMainColor()); + embedBuilder.setTitle(commandEvent.getResource("label.suggestionMenu")); + embedBuilder.setColor(Color.ORANGE); + embedBuilder.setDescription(setting.get().getStringValue()); + embedBuilder.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); + messageCreateBuilder.setEmbeds(embedBuilder.build()); + messageCreateBuilder.setActionRow(Button.primary("re_suggestion", commandEvent.getResource("message.suggestion.suggestionMenuPlaceholder"))); + + Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), messageChannel); + + commandEvent.reply(commandEvent.getResource("message.suggestion.success"), 5); + })); - commandEvent.reply(commandEvent.getResource("message.suggestion.success"), 5); } /** @@ -104,7 +110,7 @@ public void createSuggestions(CommandEvent commandEvent, MessageChannel channel, */ @Override public CommandData getCommandData() { - return new CommandDataImpl("suggestion", LanguageService.getDefault("command.description.suggestion")) + return new CommandDataImpl("suggestion", "command.description.suggestion") .addOptions(new OptionData(OptionType.CHANNEL, "target", "The channel the suggestions should be shown in.").setChannelTypes(ChannelType.NEWS, ChannelType.TEXT).setRequired(true)) .addOptions(new OptionData(OptionType.CHANNEL, "messagetarget", "The channel the bot should send the suggestion message to.").setChannelTypes(ChannelType.NEWS, ChannelType.TEXT).setRequired(true)) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.ADMINISTRATOR)); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java b/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java index dda750c37..85299b2ad 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.UserSnowflake; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; @@ -62,7 +60,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.BAN_MEMBERS.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** @@ -70,7 +68,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("unban", LanguageService.getDefault("command.description.unban")) + return new CommandDataImpl("unban", "command.description.unban") .addOptions(new OptionData(OptionType.STRING, "id", "Which User should be unbanned.").setRequired(true)) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.BAN_MEMBERS)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java b/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java index f82aae89c..159d70869 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; @@ -60,7 +58,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.MODERATE_MEMBERS.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** @@ -68,7 +66,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("unmute", LanguageService.getDefault("command.description.unmute")) + return new CommandDataImpl("unmute", "command.description.unmute") .addOptions(new OptionData(OptionType.USER, "target", "Which User should be unmuted.").setRequired(true)) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.MODERATE_MEMBERS)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java index cb4223fc1..665ec01d6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java @@ -17,6 +17,7 @@ import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; import net.dv8tion.jda.api.interactions.commands.build.SubcommandGroupData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; +import reactor.core.scheduler.Schedulers; import java.time.Duration; import java.util.Map; @@ -71,8 +72,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(2); punishments.setRoleId(roleMapping.getAsRole().getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.warn.punishment.created"))); } case "roleremove" -> { @@ -81,8 +81,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(3); punishments.setRoleId(roleMapping.getAsRole().getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.warn.punishment.created"))); } case "timeout" -> { @@ -91,8 +90,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(1); punishments.setTimeoutTime(secondsMapping.getAsLong() * 1000); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.warn.punishment.created"))); } case "kick" -> { @@ -101,8 +99,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(4); if (reasonMapping != null) punishments.setReason(reasonMapping.getAsString()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.warn.punishment.created"))); } case "ban" -> { @@ -111,43 +108,44 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(5); if (reasonMapping != null) punishments.setReason(reasonMapping.getAsString()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.warn.punishment.created"))); } - case "list" -> { - StringBuilder stringBuilder = new StringBuilder(); - for (Punishments punishments : SQLSession.getSqlConnector().getSqlWorker().getEntityList(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong()))) { - int action = punishments.getAction(); - stringBuilder.append(punishments.getId()).append(" - ").append(punishments.getWarnings()).append(" -> "); - - switch (action) { - case 1 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.timeout", Duration.ofMillis(punishments.getTimeoutTime()).toSeconds())); - case 2 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleAdd", punishments.getRoleId())); - case 3 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleRemove", punishments.getRoleId())); - case 4 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.kick", punishments.getReason())); - case 5 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.ban", punishments.getReason())); - } - - stringBuilder.append("\n"); - } - commandEvent.reply(commandEvent.getResource("message.warn.punishment.list", stringBuilder.toString())); - } + case "list" -> + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).subscribe(punishmentsList -> { + StringBuilder stringBuilder = new StringBuilder(); + for (Punishments punishments : punishmentsList) { + int action = punishments.getAction(); + stringBuilder.append(punishments.getId()).append(" - ").append(punishments.getWarnings()).append(" -> "); + + switch (action) { + case 1 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.timeout", Duration.ofMillis(punishments.getTimeoutTime()).toSeconds())); + case 2 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleAdd", punishments.getRoleId())); + case 3 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleRemove", punishments.getRoleId())); + case 4 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.kick", punishments.getReason())); + case 5 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.ban", punishments.getReason())); + } + + stringBuilder.append("\n"); + } + commandEvent.reply(commandEvent.getResource("message.warn.punishment.list", stringBuilder.toString())); + }); case "delete" -> { int id = idMapping.getAsInt(); - Punishments punishment = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND guildAndId.id = :id", Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id)); - if (punishment != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.deleted", id)); - } else { - commandEvent.reply(commandEvent.getResource("message.warn.punishment.notFound", id)); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND guildAndId.id = :id", Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id)).subscribe(punishment -> { + if (punishment.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment.get()).block(); + commandEvent.reply(commandEvent.getResource("message.warn.punishment.deleted", id)); + } else { + commandEvent.reply(commandEvent.getResource("message.warn.punishment.notFound", id)); + } + }); } } } @@ -155,46 +153,51 @@ public void onPerform(CommandEvent commandEvent) { default -> { Member member = userMapping.getAsMember(); if (commandEvent.getGuild().getSelfMember().canInteract(member) && commandEvent.getMember().canInteract(member)) { - Warning warning = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())); - int warnings = warning != null ? warning.getWarnings() + 1 : 1; - if (warning == null) { - warning = new Warning(); - warning.setUserId(member.getIdLong()); - warning.setGuildId(commandEvent.getGuild().getIdLong()); - } - - warning.setWarnings(warnings); - - SQLSession.getSqlConnector().getSqlWorker().updateEntity(warning); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())).publishOn(Schedulers.boundedElastic()).mapNotNull(warningOptional -> { + Warning warning = warningOptional.orElse(new Warning()); + int warnings = warningOptional.isPresent() ? warning.getWarnings() + 1 : 1; + if (warningOptional.isEmpty()) { + warning.setUserId(member.getIdLong()); + warning.setGuildId(commandEvent.getGuild().getIdLong()); + } - commandEvent.reply(commandEvent.getResource("message.warn.success", userMapping.getAsMember().getAsMention(), warnings)); - Punishments punishment = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND warnings = :amount", Map.of("gid", commandEvent.getGuild().getIdLong(), "amount", warnings)); - if (punishment != null) { - switch (punishment.getAction()) { - case 1 -> member.timeoutFor(Duration.ofMillis(punishment.getTimeoutTime())).reason(commandEvent.getResource("message.warn.reachedWarnings", warnings)).queue(); - case 2 -> { - Role role = commandEvent.getGuild().getRoleById(punishment.getRoleId()); - if (role == null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); - return; + warning.setWarnings(warnings); + + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(warning).block(); + }).subscribe(warning -> { + commandEvent.reply(commandEvent.getResource("message.warn.success", member.getAsMention(), warning.getWarnings())); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND warnings = :amount", Map.of("gid", commandEvent.getGuild().getIdLong(), "amount", warning.getWarnings())).subscribe(punishmentOptional -> { + if (punishmentOptional.isPresent()) { + Punishments punishment = punishmentOptional.get(); + switch (punishment.getAction()) { + case 1 -> + member.timeoutFor(Duration.ofMillis(punishment.getTimeoutTime())).reason(commandEvent.getResource("message.warn.reachedWarnings", warning.getWarnings())).queue(); + case 2 -> { + Role role = commandEvent.getGuild().getRoleById(punishment.getRoleId()); + if (role == null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment).block(); + return; + } + + commandEvent.getGuild().addRoleToMember(member, role).reason(commandEvent.getResource("message.warn.reachedWarnings", warning.getWarnings())).queue(); + } + case 3 -> { + Role role = commandEvent.getGuild().getRoleById(punishment.getRoleId()); + if (role == null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment).block(); + return; + } + + commandEvent.getGuild().removeRoleFromMember(member, role).reason(commandEvent.getResource("message.warn.reachedWarnings", warning.getWarnings())).queue(); + } + case 4 -> member.kick().reason(punishment.getReason()).queue(); + case 5 -> member.ban(0, TimeUnit.DAYS).reason(punishment.getReason()).queue(); + default -> log.error("Unhandled action! {}", punishment.getAction()); } - - commandEvent.getGuild().addRoleToMember(member, role).reason(commandEvent.getResource("message.warn.reachedWarnings", warnings)).queue(); } - case 3 -> { - Role role = commandEvent.getGuild().getRoleById(punishment.getRoleId()); - if (role == null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); - return; - } + }); + }); - commandEvent.getGuild().removeRoleFromMember(member, role).reason(commandEvent.getResource("message.warn.reachedWarnings", warnings)).queue(); - } - case 4 -> member.kick().reason(punishment.getReason()).queue(); - case 5 -> member.ban(0, TimeUnit.DAYS).reason(punishment.getReason()).queue(); - default -> log.error("Unhandled action! {}", punishment.getAction()); - } - } } else { if (commandEvent.getGuild().getSelfMember().canInteract(member)) { commandEvent.reply(commandEvent.getResource("message.warn.hierarchySelfError"), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Clearqueue.java b/src/main/java/de/presti/ree6/commands/impl/music/Clearqueue.java index 689fdc630..924c61036 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Clearqueue.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Clearqueue.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Clears the Queue. */ @@ -33,7 +31,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.clearQueue")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Loop.java b/src/main/java/de/presti/ree6/commands/impl/music/Loop.java index 0f9e2ea32..04ea4cd8e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Loop.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Loop.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Set the Song onto Loop. */ @@ -37,7 +35,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(Main.getInstance().getMusicWorker().getGuildAudioPlayer(commandEvent.getGuild()).getScheduler().loop() ? commandEvent.getResource("message.music.loop.enabled") : commandEvent.getResource("message.music.loop.disabled")); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Lyrics.java b/src/main/java/de/presti/ree6/commands/impl/music/Lyrics.java index cfd10f4b8..f97113ce4 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Lyrics.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Lyrics.java @@ -2,12 +2,12 @@ import com.jagrosh.jlyrics.LyricsClient; import de.presti.ree6.audio.music.GuildMusicManager; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -56,7 +56,8 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder eb = new EmbedBuilder() .setAuthor(lyrics.getAuthor()) - .setTitle(lyrics.getTitle(), lyrics.getURL()); + .setTitle(lyrics.getTitle(), lyrics.getURL()) + .setColor(BotConfig.getMainColor()); if (lyrics.getContent().length() > 15000) { commandEvent.reply(commandEvent.getResource("message.music.lyrics.foundUnlikely", "`" + FormatUtil.filter(title) + "`", lyrics.getURL())); } else if (lyrics.getContent().length() > 2000) { diff --git a/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java b/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java index 4bd20d8cd..f7a772cfc 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java @@ -4,6 +4,7 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import de.presti.ree6.api.events.MusicPlayerStateChangeEvent; import de.presti.ree6.audio.music.GuildMusicManager; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; @@ -11,7 +12,6 @@ import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.data.ArrayUtil; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; @@ -22,8 +22,6 @@ import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.api.utils.messages.MessageEditBuilder; -import java.awt.*; - /** * Creates a small typeof UI to control music in a channel. */ @@ -65,11 +63,11 @@ public void onMusicPlayerStateChangeEvent(MusicPlayerStateChangeEvent event) { embedBuilder1 = embedBuilder1 .setImage(audioTrackInfo1 != null && (audioTrackInfo1.artworkUrl != null && !audioTrackInfo1.artworkUrl.isBlank()) ? audioTrackInfo1.artworkUrl : "https://images.unsplash.com/photo-1546977463-943d58b78c19") .setTitle("**" + (audioTrackInfo1 != null ? LanguageService.getByGuild(event.getGuild(), "message.music.songInfoSlim", audioTrackInfo1.title, audioTrackInfo1.author) - : LanguageService.getByGuild(event.getGuild(), "message.music.notPlaying")) + "**"); + : LanguageService.getByGuild(event.getGuild(), "message.music.notPlaying")).block() + "**"); } else if (event.getState() != MusicPlayerStateChangeEvent.State.QUEUE_ADD) { embedBuilder1 = embedBuilder1 .setImage("https://images.unsplash.com/photo-1546977463-943d58b78c19") - .setTitle("**" + LanguageService.getByGuild(event.getGuild(), "message.music.notPlaying") + "**"); + .setTitle("**" + LanguageService.getByGuild(event.getGuild(), "message.music.notPlaying").block() + "**"); } messageEditBuilder.setEmbeds(embedBuilder1.build()); @@ -95,7 +93,7 @@ public void onPerform(CommandEvent commandEvent) { guildMusicManager.getPlayer().getPlayingTrack().getInfo() : null; EmbedBuilder embedBuilder = new EmbedBuilder() - .setColor(Color.MAGENTA) + .setColor(BotConfig.getMainColor()) .setImage(audioTrackInfo != null && (audioTrackInfo.artworkUrl != null && !audioTrackInfo.artworkUrl.isBlank()) ? audioTrackInfo.artworkUrl : "https://images.unsplash.com/photo-1546977463-943d58b78c19") .setTitle("**" + (audioTrackInfo != null ? commandEvent.getResource("message.music.songInfoSlim", audioTrackInfo.title, audioTrackInfo.author) : commandEvent.getResource("message.music.notPlaying")) + "**") diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Pause.java b/src/main/java/de/presti/ree6/commands/impl/music/Pause.java index b29f2d54b..db44e9ab5 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Pause.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Pause.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Pauses the current Song. */ @@ -40,7 +38,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.pause")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); commandEvent.reply(em.build(), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Play.java b/src/main/java/de/presti/ree6/commands/impl/music/Play.java index ede205481..f0cf42491 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Play.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Play.java @@ -1,12 +1,11 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -14,8 +13,6 @@ import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; -import java.awt.*; - /** * Play a Song. */ @@ -44,7 +41,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.default.usage","play (Url)")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); commandEvent.reply(em.build(), 5); @@ -57,7 +54,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.default.usage","play (Url)")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); commandEvent.reply(em.build(), 5); @@ -73,7 +70,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("play", LanguageService.getDefault("command.description.play")).addOptions(new OptionData(OptionType.STRING, "name", "The YouTube URL, Song Name or the Spotify URL you want to play!").setRequired(true)); + return new CommandDataImpl("play", "command.description.play") + .addOptions(new OptionData(OptionType.STRING, "name", "The YouTube URL, Song Name or the Spotify URL you want to play!").setRequired(true)); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Resume.java b/src/main/java/de/presti/ree6/commands/impl/music/Resume.java index 9296e5756..9cbae8bcf 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Resume.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Resume.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Resume a Song. */ @@ -39,7 +37,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.resume")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Seek.java b/src/main/java/de/presti/ree6/commands/impl/music/Seek.java index e2fceb04d..990263d97 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Seek.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Seek.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -23,12 +22,12 @@ public class Seek implements ICommand { */ @Override public void onPerform(CommandEvent commandEvent) { - int seekAmountInSeconds = 1; + long seekAmountInSeconds = 1; if (commandEvent.isSlashCommand()) { OptionMapping optionMapping = commandEvent.getOption("seconds"); if (optionMapping != null) { - seekAmountInSeconds = optionMapping.getAsInt(); + seekAmountInSeconds = optionMapping.getAsLong(); } } else if (commandEvent.getArguments().length >= 1) { try { @@ -46,7 +45,7 @@ public void onPerform(CommandEvent commandEvent) { return; } - Main.getInstance().getMusicWorker().seekInTrack(commandEvent.getChannel(), seekAmountInSeconds); + Main.getInstance().getMusicWorker().seekInTrack(commandEvent.getChannel(), commandEvent.getInteractionHook(), seekAmountInSeconds); } /** @@ -54,7 +53,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("seek", LanguageService.getDefault("command.description.seek")).addOptions(new OptionData(OptionType.INTEGER, "seconds", "The seconds that should be seeked (negativ numbers work)").setRequired(true)); + return new CommandDataImpl("seek", "command.description.seek") + .addOptions(new OptionData(OptionType.INTEGER, "seconds", "The seconds that should be seeked (negativ numbers work)").setRequired(true)); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Shuffle.java b/src/main/java/de/presti/ree6/commands/impl/music/Shuffle.java index 312b1365a..4bc0f2d94 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Shuffle.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Shuffle.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Shuffle the current Playlist. */ @@ -40,7 +38,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.shuffle")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Skip.java b/src/main/java/de/presti/ree6/commands/impl/music/Skip.java index a6d7bb25f..e204e7ebd 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Skip.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Skip.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -54,7 +53,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("skip", LanguageService.getDefault("command.description.skip")).addOptions(new OptionData(OptionType.INTEGER, "amount", "The amount of songs that should be skipped!").setRequired(false)); + return new CommandDataImpl("skip", "command.description.skip") + .addOptions(new OptionData(OptionType.INTEGER, "amount", "The amount of songs that should be skipped!").setRequired(false)); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/music/SongInfo.java b/src/main/java/de/presti/ree6/commands/impl/music/SongInfo.java index 4c2989400..c01be9235 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/SongInfo.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/SongInfo.java @@ -2,17 +2,18 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import de.presti.ree6.audio.music.GuildMusicManager; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; - -import java.awt.*; +import net.dv8tion.jda.api.interactions.components.buttons.Button; +import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle; +import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; /** * Get information about the current Song. @@ -30,6 +31,7 @@ public void onPerform(CommandEvent commandEvent) { return; } + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder em = new EmbedBuilder(); GuildMusicManager guildMusicManager = Main.getInstance().getMusicWorker().getGuildAudioPlayer(commandEvent.getGuild()); @@ -39,14 +41,17 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + if (audioTrack != null && audioTrack.getInfo().artworkUrl != null) em.setImage(audioTrack.getInfo().artworkUrl); + em.setColor(BotConfig.getMainColor()); em.setDescription(audioTrack == null ? commandEvent.getResource("message.music.notPlaying") : commandEvent.getResource("message.music.songInfo", audioTrack.getInfo().title, audioTrack.getInfo().author, FormatUtil.getStatusEmoji(guildMusicManager.getPlayer()) + FormatUtil.progressBar((double)audioTrack.getPosition() / audioTrack.getDuration()), FormatUtil.formatTime(audioTrack.getPosition()), FormatUtil.formatTime(audioTrack.getDuration()), FormatUtil.volumeIcon(guildMusicManager.getPlayer().getVolume()))); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); + messageCreateBuilder.setEmbeds(em.build()); + if (audioTrack != null) messageCreateBuilder.addActionRow(Button.of(ButtonStyle.LINK, audioTrack.getInfo().uri, "Watch")); - commandEvent.reply(em.build(), 5); + commandEvent.reply(messageCreateBuilder.build(), 5); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/music/SongList.java b/src/main/java/de/presti/ree6/commands/impl/music/SongList.java index 26794e4a4..4dbf768b6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/SongList.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/SongList.java @@ -1,18 +1,16 @@ package de.presti.ree6.commands.impl.music; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Get the current list of songs. */ @@ -37,7 +35,7 @@ public void onPerform(CommandEvent commandEvent) { em.setAuthor(commandEvent.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(Main.getInstance().getMusicWorker().getGuildAudioPlayer(commandEvent.getGuild()).getScheduler().getQueue().isEmpty() ? commandEvent.getResource("message.music.songQueueEmpty") : (end.length() > 4096 ? commandEvent.getResource("command.perform.errorWithException","Error (M-SL-01)") : diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Stop.java b/src/main/java/de/presti/ree6/commands/impl/music/Stop.java index 4a31608ca..0d8b3058c 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Stop.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Stop.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Stop the Ree6 from playing Music. */ @@ -28,7 +26,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(new EmbedBuilder().setAuthor(commandEvent.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()).setTitle(commandEvent.getResource("label.musicPlayer")) .setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.RED) + .setColor(BotConfig.getMainColor()) .setDescription(commandEvent.getResource("message.music.notPlaying")).build(), 5); } } diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Volume.java b/src/main/java/de/presti/ree6/commands/impl/music/Volume.java index 501b6c5e0..35d61fd11 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Volume.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Volume.java @@ -1,12 +1,11 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import lavalink.client.player.IPlayer; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -15,8 +14,6 @@ import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; -import java.awt.*; - /** * Set the Volume of the AudioPlayer of Ree6. */ @@ -55,14 +52,14 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.volume.success", volume)); } else { em.setAuthor(commandEvent.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.RED); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.volume.default")); } @@ -83,14 +80,14 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.volume.success", vol)); } else { em.setAuthor(commandEvent.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.volume.default", player.getVolume())); } } @@ -105,7 +102,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("volume", LanguageService.getDefault("command.description.volume")).addOptions(new OptionData(OptionType.INTEGER, "amount", "The Volume that the Ree6 Music Player should be!").setRequired(true)); + return new CommandDataImpl("volume", "command.description.volume") + .addOptions(new OptionData(OptionType.INTEGER, "amount", "The Volume that the Ree6 Music Player should be!").setRequired(true)); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java b/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java index 367b66118..f413dbf6f 100644 --- a/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java +++ b/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java @@ -50,7 +50,7 @@ public void sendImage(CommandEvent commandEvent) { List images = new ArrayList<>(); try { - List request = Main.getInstance().getNotifier().getSubredditPosts("hentai", Sorting.HOT, 50); + List request = Main.getInstance().getNotifier().getRedditSonic().getSubredditPosts("hentai", Sorting.HOT, 50); request.forEach(x -> { String fileUrl = x.getUrl().toLowerCase(); @@ -73,6 +73,7 @@ public void sendImage(CommandEvent commandEvent) { String randomUrl = images.get(RandomUtils.secureRandom.nextInt(images.size() - 1)); EmbedBuilder em = new EmbedBuilder(); + em.setColor(BotConfig.getMainColor()); em.setImage(randomUrl); em.setFooter(commandEvent.getMember().getEffectiveName() + " - " + BotConfig.getAdvertisement(), commandEvent.getMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java b/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java index ec0029918..0343510b9 100644 --- a/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java +++ b/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java @@ -3,12 +3,11 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import de.presti.ree6.utils.others.RandomUtils; import net.dv8tion.jda.api.EmbedBuilder; @@ -108,6 +107,7 @@ public void sendImage(CommandEvent commandEvent, Message message, String tags) { if (object.has("sample_url")) { EmbedBuilder em = new EmbedBuilder(); + em.setColor(BotConfig.getMainColor()); em.setImage(object.get("sample_url").getAsString()); em.setFooter(commandEvent.getMember().getEffectiveName() + " - " + BotConfig.getAdvertisement(), commandEvent.getMember().getEffectiveAvatarUrl()); @@ -136,7 +136,7 @@ public void sendImage(CommandEvent commandEvent, Message message, String tags) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("nsfw34", LanguageService.getDefault("command.description.rule34_slash")) + return new CommandDataImpl("nsfw34", "command.description.rule34_slash") .addOptions(new OptionData(OptionType.STRING, "tags", "Tags for the image search")); } diff --git a/src/main/java/de/presti/ree6/commands/interfaces/Command.java b/src/main/java/de/presti/ree6/commands/interfaces/Command.java index ad2c37e6d..b6e52639e 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/Command.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/Command.java @@ -34,4 +34,10 @@ * @return retrieve the category of the Command. */ Category category(); + + /** + * Allow a command to be used as app command. + * @return if the command is allowed to be used via command. + */ + boolean allowAppInstall() default true; } diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index 94ae0e76d..978232bee 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -1,68 +1,75 @@ package de.presti.ree6.commands.interfaces; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import de.presti.ree6.news.AnnouncementManager; +import de.presti.ree6.module.news.AnnouncementManager; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.bot.BotConfig; -import de.presti.ree6.utils.others.ThreadUtil; +import de.presti.ree6.sql.entities.Setting; import io.sentry.Sentry; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; +import org.pf4j.ExtensionPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; -import java.util.concurrent.CompletableFuture; +import java.util.Optional; /** * An Interface class, used to make it easier for the creation of Commands. */ -public interface ICommand { +public interface ICommand extends ExtensionPoint { /** * The Logger for this class. */ Logger log = LoggerFactory.getLogger(ICommand.class); - /** - * Will be fired when the Command is called. - * - * @param commandEvent the Event, with every needed data. - */ - default void onASyncPerform(CommandEvent commandEvent) { - CompletableFuture.runAsync(() -> onPerform(commandEvent)).exceptionally(throwable -> { + default Mono onMonoPerform(CommandEvent commandEvent) { + if (BotConfig.isDebug()) + log.info("Command {} called by {} in {} ({}).", commandEvent.getCommand(), commandEvent.getUser().getName(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); + + return Mono.fromRunnable(() -> onPerformWithLog(commandEvent)).thenReturn(true).onErrorResume(throwable -> { if (!throwable.getMessage().contains("Unknown Message")) { commandEvent.reply(commandEvent.getResource("command.perform.internalError"), 5); log.error("An error occurred while executing the command!", throwable); Sentry.captureException(throwable); } - return null; - }); - ThreadUtil.createThread(y -> { + return Mono.just(false); + }).doOnSuccess(success -> { + if (commandEvent.getGuild().isDetached()) return; + if (BotConfig.isDebug()) + log.info("Updating Stats {} in {} ({}).", commandEvent.getCommand(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); // Update Stats. SQLSession.getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getIdLong(), commandEvent.getCommand()); - if (SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").getBooleanValue()) { - AnnouncementManager.getAnnouncementList().forEach(a -> { - if (!AnnouncementManager.hasReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id())) { - Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setTitle(a.title()) - .setAuthor(BotConfig.getBotName() + "-Info") - .setDescription(a.content().replace("\\n", "\n") + "\n\n" + LanguageService.getByGuild(commandEvent.getGuild(), "message.news.notice")) - .setFooter(BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) - .setColor(BotWorker.randomEmbedColor()), 15, commandEvent.getChannel()); + Optional setting = SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").block(); + if (setting == null || setting.isEmpty() || !setting.get().getBooleanValue()) return; + AnnouncementManager.getAnnouncementList().forEach(a -> { + if (!AnnouncementManager.hasReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id())) { + Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setTitle(a.title()) + .setAuthor(BotConfig.getBotName() + "-Info") + .setDescription(a.content().replace("\\n", "\n") + "\n\n" + LanguageService.getByGuild(commandEvent.getGuild(), "message.news.notice").block()) + .setFooter(BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) + .setColor(BotConfig.getMainColor()), 15, commandEvent.getChannel()); - AnnouncementManager.addReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id()); - } - }); - } + AnnouncementManager.addReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id()); + } + }); }); } + default void onPerformWithLog(CommandEvent commandEvent) { + onPerform(commandEvent); + if (BotConfig.isDebug()) + log.info("Command {} has ended, called by {} in {} ({}).", commandEvent.getCommand(), commandEvent.getUser().getName(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); + } + /** * Will be fired when the Command is called. * - * @param commandEvent the Event, with every needed data. + * @param commandEvent the Event, with every necessary data. */ void onPerform(CommandEvent commandEvent); diff --git a/src/main/java/de/presti/ree6/events/CustomEvents.java b/src/main/java/de/presti/ree6/events/CustomEvents.java index d7713b11d..c158ab225 100644 --- a/src/main/java/de/presti/ree6/events/CustomEvents.java +++ b/src/main/java/de/presti/ree6/events/CustomEvents.java @@ -1,11 +1,10 @@ package de.presti.ree6.events; -import de.presti.ree6.actions.customevents.container.CustomEventContainer; +import de.presti.ree6.module.actions.customevents.container.CustomEventContainer; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.custom.CustomEventAction; import de.presti.ree6.sql.entities.custom.CustomEventTyp; import de.presti.ree6.utils.data.CustomEventMapper; -import de.presti.ree6.utils.others.ThreadUtil; import net.dv8tion.jda.api.events.GenericEvent; import net.dv8tion.jda.api.events.guild.GenericGuildEvent; import net.dv8tion.jda.api.events.message.GenericMessageEvent; @@ -32,6 +31,7 @@ public class CustomEvents implements EventListener { /** * Listens for all events. + * * @param event The event. */ @Override @@ -54,7 +54,8 @@ public void onEvent(@NotNull GenericEvent event) { /** * Run the cache entry for the given event. - * @param clazz The event class. + * + * @param clazz The event class. * @param guildId The guild id. */ public void runCacheEntry(Class extends GenericEvent> clazz, long guildId) { @@ -67,29 +68,28 @@ public void runCacheEntry(Class extends GenericEvent> clazz, long guildId) { /** * Check for new CustomEvents. - * @param clazz The event class. + * + * @param clazz The event class. * @param guildId The guild id. */ public void checkForNew(Class extends GenericEvent> clazz, long guildId) { if (System.currentTimeMillis() - lastCheck < Duration.ofMinutes(1).toMillis()) return; lastCheck = System.currentTimeMillis(); - ThreadUtil.createThread(x -> { - List list = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new CustomEventAction(), - "FROM CustomEventAction WHERE guildId=:gid", - Map.of("gid", guildId)).stream().map(CustomEventContainer::new).toList(); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new CustomEventAction(), + "FROM CustomEventAction WHERE guildId=:gid", + Map.of("gid", guildId)).map(x -> x.stream().map(CustomEventContainer::new).toList()).subscribe(list -> { + CustomEventTyp typ = CustomEventMapper.getEventTyp(clazz); list.forEach(c -> { - - CustomEventTyp typ = CustomEventMapper.getEventTyp(clazz); - if (cache.containsKey(typ) && !cache.get(typ).contains(c)) { cache.get(typ).add(c); } else { cache.put(typ, List.of(c)); } - }); - cache.values().forEach(entries -> entries.removeIf(c -> !list.contains(c))); + cache.values().forEach(entries -> entries.removeIf(z -> !list.contains(z))); + }); }); + } } diff --git a/src/main/java/de/presti/ree6/events/GameEvents.java b/src/main/java/de/presti/ree6/events/GameEvents.java index 068a1bda0..e810113e0 100644 --- a/src/main/java/de/presti/ree6/events/GameEvents.java +++ b/src/main/java/de/presti/ree6/events/GameEvents.java @@ -1,9 +1,9 @@ package de.presti.ree6.events; -import de.presti.ree6.game.core.GameManager; -import de.presti.ree6.game.core.GameSession; -import de.presti.ree6.game.core.base.GamePlayer; -import de.presti.ree6.game.core.base.GameState; +import de.presti.ree6.module.game.core.GameManager; +import de.presti.ree6.module.game.core.GameSession; +import de.presti.ree6.module.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GameState; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent; diff --git a/src/main/java/de/presti/ree6/events/LoggingEvents.java b/src/main/java/de/presti/ree6/events/LoggingEvents.java index f1eb7f109..b6bb3903c 100644 --- a/src/main/java/de/presti/ree6/events/LoggingEvents.java +++ b/src/main/java/de/presti/ree6/events/LoggingEvents.java @@ -3,21 +3,20 @@ import club.minnced.discord.webhook.send.WebhookEmbed; import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.language.LanguageService; -import de.presti.ree6.logger.LogMessage; -import de.presti.ree6.logger.LogTyp; -import de.presti.ree6.logger.events.LogMessageMember; -import de.presti.ree6.logger.events.LogMessageRole; -import de.presti.ree6.logger.events.LogMessageUser; -import de.presti.ree6.logger.events.LogMessageVoice; -import de.presti.ree6.module.invite.InviteContainer; -import de.presti.ree6.module.invite.InviteContainerManager; +import de.presti.ree6.module.logger.LogMessage; +import de.presti.ree6.module.logger.LogTyp; +import de.presti.ree6.module.logger.events.LogMessageMember; +import de.presti.ree6.module.logger.events.LogMessageRole; +import de.presti.ree6.module.logger.events.LogMessageUser; +import de.presti.ree6.module.logger.events.LogMessageVoice; import de.presti.ree6.main.Main; +import de.presti.ree6.module.invite.InviteContainer; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Invite; -import de.presti.ree6.sql.entities.webhook.base.Webhook; +import de.presti.ree6.sql.entities.webhook.WebhookLog; import de.presti.ree6.utils.data.ArrayUtil; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.audit.ActionType; import net.dv8tion.jda.api.audit.AuditLogEntry; @@ -65,7 +64,7 @@ public class LoggingEvents extends ListenerAdapter { //region Guild /** - * @see ListenerAdapter#onGuildUpdateVanityCode(GuildUpdateVanityCodeEvent) + * @see ListenerAdapter#onGuildUpdateVanityCode(GuildUpdateVanityCodeEvent) */ @Override public void onGuildUpdateVanityCode(@NotNull GuildUpdateVanityCodeEvent event) { @@ -73,52 +72,57 @@ public void onGuildUpdateVanityCode(@NotNull GuildUpdateVanityCodeEvent event) { if (!event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_SERVER)) return; - Invite invite = event.getOldVanityCode() != null ? - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Invite(), "FROM Invite WHERE guildAndCode.guildId = :gid AND guildAndCode.code = :code", - Map.of("gid", event.getGuild().getIdLong(), "code", event.getOldVanityCode())) - : null; - - if (invite != null) { - invite.setCode(event.getNewVanityCode()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(invite); - } else { + if (event.getOldVanityCode() == null) { event.getGuild().retrieveVanityInvite().onErrorMap(throwable -> null).queue(vanityInvite -> - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Invite(event.getGuild().getIdLong(), event.getGuild().getOwnerIdLong(), vanityInvite.getUses(), event.getNewVanityCode()))); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Invite(event.getGuild().getIdLong(), event.getGuild().getOwnerIdLong(), vanityInvite.getUses(), event.getNewVanityCode())).block()); + } else { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Invite(), "FROM Invite WHERE guildAndCode.guildId = :gid AND guildAndCode.code = :code", + Map.of("gid", event.getGuild().getIdLong(), "code", event.getOldVanityCode())).subscribe(inviteOptional -> { + if (inviteOptional.isPresent()) { + Invite invite = inviteOptional.get(); + invite.setCode(event.getNewVanityCode()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(invite).block(); + } + }); } } /** - * @see ListenerAdapter#onGuildBan(GuildBanEvent) + * @see ListenerAdapter#onGuildBan(GuildBanEvent) */ @Override public void onGuildBan(@Nonnull GuildBanEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberban").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberban").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.banned", event.getUser().getAsMention())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.banned", event.getUser().getAsMention()).block()); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.BAN).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.BAN).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())); + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookOptional -> + webhookOptional.ifPresent(webhookLog -> Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhookLog.getWebhookId(), webhookLog.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())))); + }); + }); } /** @@ -127,32 +131,36 @@ public void onGuildBan(@Nonnull GuildBanEvent event) { @Override public void onGuildUnban(@Nonnull GuildUnbanEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberunban").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberunban").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.unbanned", event.getUser().getAsMention())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.unbanned", event.getUser().getAsMention()).block()); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.UNBAN).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.UNBAN).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.USER_UNBAN, event.getUser())); + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookOptional -> + webhookOptional.ifPresent(webhookLog -> Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhookLog.getWebhookId(), webhookLog.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())))); + }); + }); } //endregion @@ -165,72 +173,79 @@ public void onGuildUnban(@Nonnull GuildUnbanEvent event) { @Override public void onGuildMemberJoin(GuildMemberJoinEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong())) - return; - - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - - if (SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberjoin").getBooleanValue()) { - WebhookMessageBuilder wm = new WebhookMessageBuilder(); - - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); - - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.joined.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getUser().getTimeCreated()), TimeFormat.RELATIVE.format(event.getUser().getTimeCreated()))); - - wm.addEmbeds(we.build()); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.SERVER_JOIN, event.getUser())); - } - - if (event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_SERVER) && SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_invite").getBooleanValue()) { - - WebhookMessageBuilder wm2 = new WebhookMessageBuilder(); - - wm2.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm2.setUsername(BotConfig.getBotName() + "-InviteLogs"); - - if (event.getUser().isBot()) { - event.getGuild().retrieveAuditLogs().type(ActionType.BOT_ADD).limit(1).queue(auditLogEntries -> { - if (auditLogEntries.isEmpty()) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention())); - return; - } - AuditLogEntry entry = auditLogEntries.get(0); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberjoin").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; + WebhookMessageBuilder wm = new WebhookMessageBuilder(); + + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); + + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.joined.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getUser().getTimeCreated()), TimeFormat.RELATIVE.format(event.getUser().getTimeCreated())).block()); + + wm.addEmbeds(we.build()); + Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.SERVER_JOIN, event.getUser())); + }); - if (entry.getUser() == null) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention())); - return; - } + if (event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_SERVER)) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_invite").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; + WebhookMessageBuilder wm2 = new WebhookMessageBuilder(); + + wm2.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm2.setUsername(BotConfig.getBotName() + "-InviteLogs"); + + if (event.getUser().isBot()) { + event.getGuild().retrieveAuditLogs().type(ActionType.BOT_ADD).limit(1).queue(auditLogEntries -> { + if (auditLogEntries.isEmpty()) { + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).block()); + return; + } + AuditLogEntry entry = auditLogEntries.get(0); + + if (entry.getUser() == null) { + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).block()); + return; + } + + if (entry.getTargetId().equals(event.getUser().getId())) { + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.found", event.getUser().getAsMention(), entry.getUser().getAsMention()).block()); + } else { + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).block()); + } + }); + } else { + InviteContainer inviteContainer = Main.getInstance().getInviteContainerManager().getRightInvite(event.getGuild()); + if (inviteContainer != null) { + inviteContainer.setUses(inviteContainer.getUses() + 1); + if (inviteContainer.isVanity()) { + wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.vanity", event.getUser().getAsMention()).block()); + } else { + wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.default", event.getUser().getAsMention(), "<@" + inviteContainer.getCreatorId() + ">", inviteContainer.getCode(), inviteContainer.getUses()).block()); + } + Main.getInstance().getInviteContainerManager().add(inviteContainer); + } else { + wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.notFound", event.getMember().getAsMention()).block()); + } + } - if (entry.getTargetId().equals(event.getUser().getId())) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.found", event.getUser().getAsMention(), entry.getUser().getAsMention())); - } else { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention())); - } - }); - } else { - InviteContainer inviteContainer = Main.getInstance().getInviteContainerManager().getRightInvite(event.getGuild()); - if (inviteContainer != null) { - inviteContainer.setUses(inviteContainer.getUses() + 1); - if (inviteContainer.isVanity()) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.vanity", event.getUser().getAsMention())); - } else { - wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.default", event.getUser().getAsMention(), "<@" + inviteContainer.getCreatorId() + ">", inviteContainer.getCode(), inviteContainer.getUses())); - } - Main.getInstance().getInviteContainerManager().add(inviteContainer); - } else { - wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.notFound", event.getMember().getAsMention())); + Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm2.build(), event.getGuild(), LogTyp.SERVER_INVITE, event.getUser())); + }); } - } + }); + }); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm2.build(), event.getGuild(), LogTyp.SERVER_INVITE, event.getUser())); - } } /** @@ -239,37 +254,45 @@ public void onGuildMemberJoin(GuildMemberJoinEvent event) { @Override public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberleave").getBooleanValue()) - return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberleave").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - if (event.getMember() != null) { - we.setDescription(LanguageService.getByEvent(event, "logging.left.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getMember().getTimeJoined()))); - } else { - we.setDescription(LanguageService.getByEvent(event, "logging.left.slim", event.getUser().getAsMention())); - } + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.KICK).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); + if (event.getMember() != null) { + we.setDescription(LanguageService.getByEvent(event, "logging.left.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getMember().getTimeJoined())).block()); + } else { + we.setDescription(LanguageService.getByEvent(event, "logging.left.slim", event.getUser().getAsMention()).block()); + } + + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.KICK).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.SERVER_LEAVE, event.getUser())); + Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.SERVER_LEAVE, event.getUser())); + }); + }); + }); } /** @@ -279,46 +302,53 @@ public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { public void onGuildMemberUpdateTimeOut(@NotNull GuildMemberUpdateTimeOutEvent event) { super.onGuildMemberUpdateTimeOut(event); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_timeout").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; + + WebhookMessageBuilder wm = new WebhookMessageBuilder(); + + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); + + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + AuditLogPaginationAction paginationAction = event.getGuild().retrieveAuditLogs().user(event.getUser()).type(ActionType.MEMBER_UPDATE).limit(1); + if (event.getNewTimeOutEnd() != null) { + if (paginationAction.isEmpty()) { + we.setDescription(LanguageService.getByEvent(event, "logging.timeout.started", + event.getUser().getAsMention(), + TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd())).block()); + } else { + AuditLogEntry auditLogEntry = paginationAction.getFirst(); + we.setDescription(LanguageService.getByEvent(event, "logging.timeout.updated", + event.getUser().getAsMention(), + (auditLogEntry.getReason() == null ? "Couldn't find reason" : auditLogEntry.getReason()), + (auditLogEntry.getUser() != null ? auditLogEntry.getUser().getAsMention() : LanguageService.getByGuild(event.getGuild(), "label.unknown")), + TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd())).block()); + } + } else { + we.setDescription(LanguageService.getByEvent(event, "logging.timeout.ended", + event.getUser().getAsMention(), + TimeFormat.DATE_TIME_SHORT.format(event.getOldTimeOutEnd())).block()); + } - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_timeout").getBooleanValue()) - return; - - WebhookMessageBuilder wm = new WebhookMessageBuilder(); - - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); - - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - AuditLogPaginationAction paginationAction = event.getGuild().retrieveAuditLogs().user(event.getUser()).type(ActionType.MEMBER_UPDATE).limit(1); - if (event.getNewTimeOutEnd() != null) { - if (paginationAction.isEmpty()) { - we.setDescription(LanguageService.getByEvent(event, "logging.timeout.started", - event.getUser().getAsMention(), - TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd()))); - } else { - AuditLogEntry auditLogEntry = paginationAction.getFirst(); - we.setDescription(LanguageService.getByEvent(event, "logging.timeout.updated", - event.getUser().getAsMention(), - (auditLogEntry.getReason() == null ? "Couldn't find reason" : auditLogEntry.getReason()), - (auditLogEntry.getUser() != null ? auditLogEntry.getUser().getAsMention() : LanguageService.getByGuild(event.getGuild(), "label.unknown")), - TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd()))); - } - } else { - we.setDescription(LanguageService.getByEvent(event, "logging.timeout.ended", - event.getUser().getAsMention(), - TimeFormat.DATE_TIME_SHORT.format(event.getOldTimeOutEnd()))); - } - - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ELSE, event.getMember())); + Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ELSE, event.getMember())); + }); + }); + }); } /** @@ -327,38 +357,45 @@ public void onGuildMemberUpdateTimeOut(@NotNull GuildMemberUpdateTimeOutEvent ev @Override public void onGuildMemberUpdateNickname(@Nonnull GuildMemberUpdateNicknameEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_nickname").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + WebhookLog webhook = webhookLogOptional.get(); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_nickname").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); - if (event.getNewNickname() == null) { - we.setDescription(LanguageService.getByEvent(event, "logging.nickname.reset", event.getUser().getAsMention(), event.getOldNickname())); - } else { - we.setDescription(LanguageService.getByEvent(event, "logging.nickname.changed", event.getUser().getAsMention(), event.getNewNickname(), (event.getOldNickname() != null ? event.getOldNickname() : event.getUser().getName()))); - } + if (event.getNewNickname() == null) { + we.setDescription(LanguageService.getByEvent(event, "logging.nickname.reset", event.getUser().getAsMention(), event.getOldNickname()).block()); + } else { + we.setDescription(LanguageService.getByEvent(event, "logging.nickname.changed", event.getUser().getAsMention(), event.getNewNickname(), (event.getOldNickname() != null ? event.getOldNickname() : event.getUser().getName())).block()); + } - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.NICKNAME_CHANGE, event.getEntity(), event.getOldNickname(), event.getNewNickname())); + Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.NICKNAME_CHANGE, event.getEntity(), event.getOldNickname(), event.getNewNickname())); + }); + }); + }); } //endregion @@ -372,81 +409,88 @@ public void onGuildMemberUpdateNickname(@Nonnull GuildMemberUpdateNicknameEvent @Override public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { super.onGuildVoiceUpdate(event); - if (event.getChannelLeft() == null) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicejoin").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + WebhookLog webhook = webhookLogOptional.get(); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + if (event.getChannelLeft() == null) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicejoin").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.join", event.getEntity().getUser().getAsMention(), event.getChannelJoined().getAsMention())); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - wm.addEmbeds(we.build()); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.join", event.getEntity().getUser().getAsMention(), event.getChannelJoined().getAsMention()).block()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_JOIN, event.getEntity(), event.getChannelJoined())); - } else if (event.getChannelJoined() == null) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voiceleave").getBooleanValue()) - return; + wm.addEmbeds(we.build()); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_JOIN, event.getEntity(), event.getChannelJoined())); + }); + } else if (event.getChannelJoined() == null) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voiceleave").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.leave", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention())); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_KICK).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.leave", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention()).block()); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_KICK).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - wm.addEmbeds(we.build()); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_LEAVE, event.getEntity(), event.getChannelLeft())); - } else { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicemove").getBooleanValue()) - return; + wm.addEmbeds(we.build()); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_LEAVE, event.getEntity(), event.getChannelLeft())); + }); + } else { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicemove").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.move", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention(), event.getChannelJoined().getAsMention())); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_MOVE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.move", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention(), event.getChannelJoined().getAsMention()).block()); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_MOVE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - wm.addEmbeds(we.build()); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_MOVE, event.getEntity(), event.getChannelLeft(), event.getChannelJoined())); - } + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_MOVE, event.getEntity(), event.getChannelLeft(), event.getChannelJoined())); + }); + } + }); + }); } //endregion @@ -459,102 +503,110 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { @Override public void onGenericChannel(@Nonnull GenericChannelEvent event) { - if (event.getChannelType().isAudio()) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicechannel").getBooleanValue()) - return; - - WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); - - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.voice", event.getChannel().getAsMention())); - - AuditLogEntry entry; - - if (event instanceof ChannelCreateEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.voice", event.getChannel().getAsMention())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_CREATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else if (event instanceof ChannelDeleteEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.voice", event.getChannel().getName())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_DELETE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else if (event instanceof ChannelUpdateNameEvent channelUpdateNameEvent) { - we.addField(new WebhookEmbed.EmbedField(true, "**Old name**", channelUpdateNameEvent.getOldValue() != null - ? ((ChannelUpdateNameEvent) event).getOldValue() : event.getChannel().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**New name**", channelUpdateNameEvent.getNewValue() != null - ? ((ChannelUpdateNameEvent) event).getNewValue() : event.getChannel().getName())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else { - return; - } - - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); - - wm.addEmbeds(we.build()); - - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessage(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.CHANNELDATA_CHANGE)); - } else if (event.getChannelType().isMessage()) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_textchannel").getBooleanValue()) - return; - - WebhookMessageBuilder wm = new WebhookMessageBuilder(); - - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); - - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.chat", event.getChannel().getAsMention())); - we.setDescription(":house: **TextChannel updated:** " + event.getChannel().getAsMention()); - - AuditLogEntry entry; - - if (event instanceof ChannelCreateEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.chat", event.getChannel().getAsMention())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_CREATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else if (event instanceof ChannelDeleteEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.chat", event.getChannel().getName())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_DELETE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else if (event instanceof ChannelUpdateNameEvent channelUpdateNameEvent) { - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName") + "**", channelUpdateNameEvent.getOldValue() != null - ? ((ChannelUpdateNameEvent) event).getOldValue() : event.getChannel().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName") + "**", channelUpdateNameEvent.getNewValue() != null - ? ((ChannelUpdateNameEvent) event).getNewValue() : event.getChannel().getName())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else if (event instanceof ChannelUpdateNSFWEvent channelUpdateNSFWEvent) { - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.nsfw") + "**", channelUpdateNSFWEvent.getNewValue() + "")); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else { - return; - } - - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); - - wm.addEmbeds(we.build()); - - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessage(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.CHANNELDATA_CHANGE)); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + + if (event.getChannelType().isAudio()) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicechannel").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; + + WebhookMessageBuilder wm = new WebhookMessageBuilder(); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); + + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.voice", event.getChannel().getAsMention()).block()); + + AuditLogEntry entry; + + if (event instanceof ChannelCreateEvent) { + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.voice", event.getChannel().getAsMention()).block()); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_CREATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else if (event instanceof ChannelDeleteEvent) { + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.voice", event.getChannel().getName()).block()); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_DELETE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else if (event instanceof ChannelUpdateNameEvent channelUpdateNameEvent) { + we.addField(new WebhookEmbed.EmbedField(true, "**Old name**", channelUpdateNameEvent.getOldValue() != null + ? ((ChannelUpdateNameEvent) event).getOldValue() : event.getChannel().getName())); + we.addField(new WebhookEmbed.EmbedField(true, "**New name**", channelUpdateNameEvent.getNewValue() != null + ? ((ChannelUpdateNameEvent) event).getNewValue() : event.getChannel().getName())); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else { + return; + } + + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); - } + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessage(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.CHANNELDATA_CHANGE)); + }); + } else { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_textchannel").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; + + WebhookMessageBuilder wm = new WebhookMessageBuilder(); + + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); + + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.chat", event.getChannel().getAsMention()).block()); + we.setDescription(":house: **TextChannel updated:** " + event.getChannel().getAsMention()); + + AuditLogEntry entry; + + if (event instanceof ChannelCreateEvent) { + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.chat", event.getChannel().getAsMention()).block()); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_CREATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else if (event instanceof ChannelDeleteEvent) { + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.chat", event.getChannel().getName()).block()); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_DELETE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else if (event instanceof ChannelUpdateNameEvent channelUpdateNameEvent) { + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName").block() + "**", channelUpdateNameEvent.getOldValue() != null + ? ((ChannelUpdateNameEvent) event).getOldValue() : event.getChannel().getName())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName").block() + "**", channelUpdateNameEvent.getNewValue() != null + ? ((ChannelUpdateNameEvent) event).getNewValue() : event.getChannel().getName())); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else if (event instanceof ChannelUpdateNSFWEvent channelUpdateNSFWEvent) { + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.nsfw").block() + "**", channelUpdateNSFWEvent.getNewValue() + "")); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else { + return; + } + + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); + + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessage(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.CHANNELDATA_CHANGE)); + }); + } + }); + }); } //endregion @@ -567,40 +619,49 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { @Override public void onGuildMemberRoleAdd(@Nonnull GuildMemberRoleAddEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleadd").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookLog webhook = webhookLogOptional.get(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleadd").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - StringBuilder finalString = new StringBuilder(); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - for (Role r : event.getRoles()) { - finalString.append(":white_check_mark: ").append(r.getName()).append("\n"); - } + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(),"logging.member", event.getMember().getAsMention())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles") + ":**", finalString.toString())); + StringBuilder finalString = new StringBuilder(); + + for (Role r : event.getRoles()) { + finalString.append(":white_check_mark: ").append(r.getName()).append("\n"); + } - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles").block() + ":**", finalString.toString())); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - wm.addEmbeds(we.build()); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MEMBERROLE_CHANGE, event.getMember(), null, new ArrayList<>(event.getRoles()))); + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MEMBERROLE_CHANGE, event.getMember(), null, new ArrayList<>(event.getRoles()))); + }); + }); + }); } /** @@ -609,38 +670,50 @@ public void onGuildMemberRoleAdd(@Nonnull GuildMemberRoleAddEvent event) { @Override public void onGuildMemberRoleRemove(@Nonnull GuildMemberRoleRemoveEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleremove").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookLog webhook = webhookLogOptional.get(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleremove").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - StringBuilder finalString = new StringBuilder(); - for (Role r : event.getRoles()) { - finalString.append(":no_entry: ").append(r.getName()).append("\n"); - } + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - we.setDescription(LanguageService.getByGuild(event.getGuild(),"logging.member", event.getMember().getAsMention())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles") + ":**", finalString.toString())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); + StringBuilder finalString = new StringBuilder(); + for (Role r : event.getRoles()) { + finalString.append(":no_entry: ").append(r.getName()).append("\n"); + } + + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles").block() + ":**", finalString.toString())); + + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); + + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MEMBERROLE_CHANGE, event.getMember(), new ArrayList<>(event.getRoles()), null)); + }); + }); + }); - wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MEMBERROLE_CHANGE, event.getMember(), new ArrayList<>(event.getRoles()), null)); } /** @@ -648,31 +721,40 @@ public void onGuildMemberRoleRemove(@Nonnull GuildMemberRoleRemoveEvent event) { */ @Override public void onRoleCreate(@Nonnull RoleCreateEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecreate").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecreate").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.create", event.getRole().getName())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.create", event.getRole().getName()).block()); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_CREATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_CREATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), true, false, false, false)); + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), true, false, false, false)); + }); + }); + }); } /** @@ -680,31 +762,40 @@ public void onRoleCreate(@Nonnull RoleCreateEvent event) { */ @Override public void onRoleDelete(@Nonnull RoleDeleteEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roledelete").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roledelete").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.delete", event.getRole().getName())); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_DELETE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.delete", event.getRole().getName()).block()); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_DELETE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - wm.addEmbeds(we.build()); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, true, false, false)); + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, true, false, false)); + }); + }); + }); } /** @@ -712,33 +803,42 @@ public void onRoleDelete(@Nonnull RoleDeleteEvent event) { */ @Override public void onRoleUpdateName(@Nonnull RoleUpdateNameEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolename").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolename").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName") + "**", event.getOldName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName") + "**", event.getNewName())); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName").block() + "**", event.getOldName())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName").block() + "**", event.getNewName())); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - wm.addEmbeds(we.build()); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getOldName(), event.getNewName())); + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getOldName(), event.getNewName())); + }); + }); + }); } /** @@ -746,33 +846,41 @@ public void onRoleUpdateName(@Nonnull RoleUpdateNameEvent event) { */ @Override public void onRoleUpdateMentionable(@Nonnull RoleUpdateMentionableEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolemention").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolemention").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldMentionable") + "**", event.getOldValue().toString())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newMentionable") + "**", event.getNewValue().toString())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldMentionable").block() + "**", event.getOldValue().toString())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newMentionable").block() + "**", event.getNewValue().toString())); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, false, false, true)); + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, false, false, true)); + }); + }); + }); } /** @@ -780,33 +888,44 @@ public void onRoleUpdateMentionable(@Nonnull RoleUpdateMentionableEvent event) { */ @Override public void onRoleUpdateHoisted(@Nonnull RoleUpdateHoistedEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolehoisted").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolehoisted").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldHoist") + "**", event.getOldValue().toString())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newHoist") + "**", event.getNewValue().toString())); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldHoist").block() + "**", event.getOldValue().toString())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newHoist").block() + "**", event.getNewValue().toString())); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); + + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, false, true, false)); + }); + }); + }); - wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, false, true, false)); } /** @@ -814,58 +933,69 @@ public void onRoleUpdateHoisted(@Nonnull RoleUpdateHoistedEvent event) { */ @Override public void onRoleUpdatePermissions(@Nonnull RoleUpdatePermissionsEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolepermission").getBooleanValue()) - return; - - WebhookMessageBuilder wm = new WebhookMessageBuilder(); - - wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); - - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName())); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolepermission").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; + + WebhookMessageBuilder wm = new WebhookMessageBuilder(); + + wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); + + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).block()); + + StringBuilder finalString = new StringBuilder(); + + boolean b = false; + for (Permission r : event.getNewPermissions()) { + if (!event.getOldPermissions().contains(r)) { + if (b) { + finalString.append("\n:white_check_mark: ").append(r.getName()); + } else { + finalString.append(":white_check_mark: ").append(r.getName()); + b = true; + } + } + } - StringBuilder finalString = new StringBuilder(); + for (Permission r : event.getOldPermissions()) { + if (!event.getNewPermissions().contains(r)) { + if (b) { + finalString.append("\n:no_entry: ").append(r.getName()); + } else { + finalString.append(":no_entry: ").append(r.getName()); + b = true; + } + } + } - boolean b = false; - for (Permission r : event.getNewPermissions()) { - if (!event.getOldPermissions().contains(r)) { - if (b) { - finalString.append("\n:white_check_mark: ").append(r.getName()); - } else { - finalString.append(":white_check_mark: ").append(r.getName()); - b = true; - } - } - } + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newPermissions").block() + "**", finalString.toString())); - for (Permission r : event.getOldPermissions()) { - if (!event.getNewPermissions().contains(r)) { - if (b) { - finalString.append("\n:no_entry: ").append(r.getName()); - } else { - finalString.append(":no_entry: ").append(r.getName()); - b = true; - } - } - } + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newPermissions") + "**", finalString.toString())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + wm.addEmbeds(we.build()); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getOldPermissions(), event.getNewPermissions())); + }); + }); + }); - wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getOldPermissions(), event.getNewPermissions())); } /** @@ -873,34 +1003,44 @@ public void onRoleUpdatePermissions(@Nonnull RoleUpdatePermissionsEvent event) { */ @Override public void onRoleUpdateColor(@Nonnull RoleUpdateColorEvent event) { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecolor").getBooleanValue()) - return; + WebhookLog webhook = webhookLogOptional.get(); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecolor").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; + + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldColor").block() + "**", (event.getOldColor() != null ? event.getOldColor() : Color.gray).getRGB() + "")); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newColor").block() + "**", (event.getNewColor() != null ? event.getNewColor() : Color.gray).getRGB() + "")); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldColor") + "**", (event.getOldColor() != null ? event.getOldColor() : Color.gray).getRGB() + "")); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newColor") + "**", (event.getNewColor() != null ? event.getNewColor() : Color.gray).getRGB() + "")); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), (event.getOldColor() != null ? event.getOldColor() : Color.gray), (event.getNewColor() != null ? event.getNewColor() : Color.gray))); + }); + }); + }); - wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), (event.getOldColor() != null ? event.getOldColor() : Color.gray), (event.getNewColor() != null ? event.getNewColor() : Color.gray))); } //endregion @@ -912,60 +1052,67 @@ public void onRoleUpdateColor(@Nonnull RoleUpdateColorEvent event) { */ @Override public void onMessageDelete(@Nonnull MessageDeleteEvent event) { - - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_messagedelete").getBooleanValue()) - return; - - User user = ArrayUtil.getUserFromMessageList(event.getMessageId()); - - if (user != null) { - WebhookMessageBuilder wm = new WebhookMessageBuilder(); - - wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); - - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(user.getName(), user.getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - - Message message = ArrayUtil.getMessageFromMessageListAndRemove(event.getMessageId()); - - if (message != null && message.getActivity() != null) return; - - boolean isImageAdded = false; - - if (message != null && !message.getAttachments().isEmpty()) { - for (Message.Attachment attachment : message.getAttachments()) { - try { - if (!isImageAdded && attachment.isImage()) { - we.setImageUrl(attachment.getProxyUrl()); - isImageAdded = true; - } else { - wm.addFile(attachment.getFileName(), attachment.getProxy().download().get()); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_messagedelete").subscribe(shouldLog -> { + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; + + User user = ArrayUtil.getUserFromMessageList(event.getMessageId()); + + if (user != null) { + WebhookMessageBuilder wm = new WebhookMessageBuilder(); + + wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); + + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(user.getName(), user.getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + + Message message = ArrayUtil.getMessageFromMessageListAndRemove(event.getMessageId()); + + if (message != null && message.getActivity() != null) return; + + boolean isImageAdded = false; + + if (message != null && !message.getAttachments().isEmpty()) { + for (Message.Attachment attachment : message.getAttachments()) { + try { + if (!isImageAdded && attachment.isImage()) { + we.setImageUrl(attachment.getProxyUrl()); + isImageAdded = true; + } else { + wm.addFile(attachment.getFileName(), attachment.getProxy().download().get()); + } + } catch (Exception exception) { + wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentFailed", attachment.getFileName()).block() + "\n"); + } + } + wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentNotice").block() + "\n"); } - } catch (Exception exception) { - wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentFailed", attachment.getFileName()) + "\n"); - } - } - wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentNotice") + "\n"); - } - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.message.deleted", user.getAsMention(), event.getChannel().getAsMention(), - message != null ? message.getContentRaw().length() >= 650 ? - LanguageService.getByGuild(event.getGuild(), "logging.message.tooLong") : - message.getContentRaw() : "")); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.message.deleted", user.getAsMention(), event.getChannel().getAsMention(), + message != null ? message.getContentRaw().length() >= 650 ? + LanguageService.getByGuild(event.getGuild(), "logging.message.tooLong").block() : + message.getContentRaw() : "").block()); - if (message != null && message.getContentRaw().length() >= 650) - wm.addFile("message.txt", message.getContentRaw().getBytes(StandardCharsets.UTF_8)); + if (message != null && message.getContentRaw().length() >= 650) + wm.addFile("message.txt", message.getContentRaw().getBytes(StandardCharsets.UTF_8)); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MESSAGE_DELETE, user)); - } + Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MESSAGE_DELETE, user)); + } + }); + }); + }); } //endregion diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index 39b533c92..c42dc2f2a 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -4,6 +4,7 @@ import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; import de.presti.ree6.audio.music.GuildMusicManager; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.bot.util.WebhookUtil; import de.presti.ree6.commands.impl.mod.Setup; @@ -14,16 +15,14 @@ import de.presti.ree6.sql.entities.*; import de.presti.ree6.sql.entities.roles.AutoRole; import de.presti.ree6.sql.entities.stats.ChannelStats; -import de.presti.ree6.sql.entities.webhook.base.Webhook; import de.presti.ree6.utils.apis.YouTubeAPIHandler; -import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.utils.data.TranscriptUtil; import de.presti.wrapper.entities.channel.ChannelResult; import io.github.redouane59.twitter.dto.user.UserV2; import masecla.reddit4j.objects.subreddit.RedditSubreddit; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.channel.concrete.Category; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; @@ -54,8 +53,8 @@ import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; -import java.util.*; import java.util.List; +import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -75,135 +74,114 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { String[] split = event.getComponentId().split(":"); if (split.length == 2) { - Recording recording = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Recording(), "FROM Recording WHERE identifier = :id AND guildId = :gid", Map.of("id", split[1], "gid", event.getGuild().getIdLong())); - MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); - if (recording != null) { - messageEditBuilder.setEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.inChat")) - .setColor(Color.GREEN) - .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.recording.finished")) - .build()); - messageEditBuilder.setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav")); - messageEditBuilder.setComponents(List.of()); - } else { - messageEditBuilder.setEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.notFound")) - .setColor(Color.RED) - .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.error")) - .build()); - messageEditBuilder.setComponents(List.of()); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Recording(), "FROM Recording WHERE identifier = :id AND guildId = :gid", Map.of("id", split[1], "gid", event.getGuild().getIdLong())).subscribe(recording -> { + MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); + if (recording.isPresent()) { + messageEditBuilder.setEmbeds(new EmbedBuilder() + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.inChat").block()) + .setColor(BotConfig.getMainColor()) + .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.recording.finished").block()) + .build()); + messageEditBuilder.setFiles(FileUpload.fromData(recording.get().getRecording(), "recording.wav")); + messageEditBuilder.setComponents(List.of()); + } else { + messageEditBuilder.setEmbeds(new EmbedBuilder() + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.notFound").block()) + .setColor(Color.RED) + .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.error").block()) + .build()); + messageEditBuilder.setComponents(List.of()); + } - event.editMessage(messageEditBuilder.build()).queue(); + event.editMessage(messageEditBuilder.build()).queue(); + }); } } switch (event.getComponentId()) { - case "re_feedback" -> { - Modal.Builder builder = Modal.create("re_feedback_modal", LanguageService.getByGuild(event.getGuild(), "label.feedback")); - builder.addActionRow(TextInput.create("re_feedback_text", LanguageService.getByGuild(event.getGuild(), "label.feedback"), TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); - event.replyModal(builder.build()).queue(); - } + case "re_feedback" -> + LanguageService.getByGuild(event.getGuild(), "label.feedback").subscribe(modalString -> { + Modal.Builder builder = Modal.create("re_feedback_modal", modalString); + builder.addActionRow(TextInput.create("re_feedback_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); + event.replyModal(builder.build()).queue(); + }); - case "re_suggestion" -> { - Modal.Builder builder = Modal.create("re_suggestion_modal", LanguageService.getByGuild(event.getGuild(), "label.suggestion")); - builder.addActionRow(TextInput.create("re_suggestion_text", LanguageService.getByGuild(event.getGuild(), "label.suggestion"), TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); - event.replyModal(builder.build()).queue(); - } + case "re_suggestion" -> + LanguageService.getByGuild(event.getGuild(), "label.suggestion").subscribe(modalString -> { + Modal.Builder builder = Modal.create("re_suggestion_modal", modalString); + builder.addActionRow(TextInput.create("re_suggestion_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); + event.replyModal(builder.build()).queue(); + }); case "re_ticket_open" -> { event.deferReply(true).queue(); - Tickets tickets = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - - if (tickets != null) { - Category category = event.getGuild().getCategoryById(tickets.getTicketCategory()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { + if (tickets.isPresent()) { + Tickets ticketEntity = tickets.get(); + Category category = event.getGuild().getCategoryById(ticketEntity.getTicketCategory()); + + if (category != null) { + if (category.getTextChannels().stream().anyMatch(c -> c.getName().contains(event.getUser().getName()))) { + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.alreadyOpen").block()).queue(); + return; + } - if (category != null) { - if (category.getTextChannels().stream().anyMatch(c -> c.getName().contains(event.getUser().getName()))) { - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.alreadyOpen")).queue(); - return; + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_ticket_open").subscribe(ticketMessage -> { + category.createTextChannel("ticket-" + event.getUser().getName()) + .setTopic(event.getUser().getId()) + .syncPermissionOverrides() + .addPermissionOverride(event.getMember(), List.of(Permission.VIEW_CHANNEL, Permission.MESSAGE_SEND, Permission.MESSAGE_HISTORY, Permission.MESSAGE_ATTACH_FILES, Permission.MESSAGE_EMBED_LINKS), List.of()) + .queue(channel -> { + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setEmbeds(new EmbedBuilder().setTitle(LanguageService.getByGuild(event.getGuild(), "label.ticket").block()) + .setDescription(ticketMessage.get().getStringValue()) + .setColor(BotConfig.getMainColor()) + .setThumbnail(event.getMember().getEffectiveAvatarUrl()).setColor(BotConfig.getMainColor()).setTimestamp(Instant.now()).build()); + messageCreateBuilder.addActionRow(Button.primary("re_ticket_close", LanguageService.getByGuild(event.getGuild(), "label.closeTicket").block())); + Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), channel); + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.created", channel.getAsMention()).block()).queue(); + }); + ticketEntity.setTicketCount(ticketEntity.getTicketCount() + 1); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(ticketEntity).block(); + }); + } else { + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.categoryNotFound").block()).queue(); } - - category.createTextChannel("ticket-" + event.getUser().getName()) - .setTopic(event.getUser().getId()) - .syncPermissionOverrides() - .addPermissionOverride(event.getMember(), List.of(Permission.VIEW_CHANNEL, Permission.MESSAGE_SEND, Permission.MESSAGE_HISTORY, Permission.MESSAGE_ATTACH_FILES, Permission.MESSAGE_EMBED_LINKS), List.of()) - .queue(channel -> { - MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - messageCreateBuilder.setEmbeds(new EmbedBuilder().setTitle(LanguageService.getByGuild(event.getGuild(), "label.ticket")) - .setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_ticket_open").getStringValue()) - .setThumbnail(event.getMember().getEffectiveAvatarUrl()).setColor(Color.GREEN).setTimestamp(Instant.now()).build()); - messageCreateBuilder.addActionRow(Button.primary("re_ticket_close", LanguageService.getByGuild(event.getGuild(), "label.closeTicket"))); - Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), channel); - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.created", channel.getAsMention())).queue(); - }); - tickets.setTicketCount(tickets.getTicketCount() + 1); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(tickets); - } else { - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.categoryNotFound")).queue(); } - } + }); } case "re_ticket_close" -> { event.deferReply(true).queue(); - Tickets tickets = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - - if (tickets != null) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(BotConfig.getBotName() + " Ticket transcript") - .append(" ") - .append(ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG))) - .append("\n") - .append("\n"); - - - for (Message message : event.getChannel().asTextChannel().getIterableHistory().reverse()) { - stringBuilder - .append("[") - .append(message.getTimeCreated().toZonedDateTime().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))) - .append("]") - .append(" ") - .append(message.getAuthor().getName()) - .append(" ") - .append("->") - .append(" ") - .append(message.getContentRaw()); - - if (!message.getAttachments().isEmpty()) { - for (Message.Attachment attachment : message.getAttachments()) { - stringBuilder.append("\n").append(attachment.getUrl()); - } - } - - stringBuilder.append("\n"); - } - - // TODO:: translate and fix the date being shown as UTC+1 and instead use the current server region. - - stringBuilder.append("\n").append("Closed by").append(" ").append(event.getUser().getName()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { + if (tickets.isPresent()) { + Tickets ticketEntity = tickets.get(); - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - webhookMessageBuilder.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName() + "-Tickets"); + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + webhookMessageBuilder.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName() + "-Tickets"); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + tickets.getTicketCount() + "!"); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); + webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + ticketEntity.getTicketCount() + "!"); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + webhookEmbedBuilder.setColor(BotConfig.getMainColor().getRGB()); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhookMessageBuilder.addFile(tickets.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + webhookMessageBuilder.addFile(event.getGuild().getId() + "_" + ticketEntity.getTicketCount() + "_transcript.html", + TranscriptUtil.generateTranscript(event.getJDA(), event.getChannel().asTextChannel().getIterableHistory().reverse().stream().toList(), + event.getChannel().getTimeCreated().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " "), + ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " ")).getBytes(StandardCharsets.UTF_8)); - WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), tickets.getLogChannelWebhookId(), tickets.getLogChannelWebhookToken(), false); + WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), ticketEntity.getLogChannelWebhookId(), ticketEntity.getLogChannelWebhookToken(), WebhookUtil.WebhookTyp.TICKET); - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.close")).queue(); - event.getChannel().delete().delay(2, TimeUnit.SECONDS).queue(); - } + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.close").block()).queue(); + event.getChannel().delete().delay(2, TimeUnit.SECONDS).queue(); + } + }); } case "re_music_play" -> { @@ -216,20 +194,20 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { EmbedBuilder em = new EmbedBuilder() .setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.resume")) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.resume").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); } else { EmbedBuilder em = new EmbedBuilder() .setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause")) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); } @@ -248,10 +226,10 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { EmbedBuilder em = new EmbedBuilder() .setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause")) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); } else { @@ -281,12 +259,12 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { em.setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer")); + em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()); em.setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(Main.getInstance().getMusicWorker().getGuildAudioPlayer(event.getGuild()).getScheduler().loop() ? - LanguageService.getByGuild(event.getGuild(), "message.music.loop.enabled") : - LanguageService.getByGuild(event.getGuild(), "message.music.loop.disabled")); + LanguageService.getByGuild(event.getGuild(), "message.music.loop.enabled").block() : + LanguageService.getByGuild(event.getGuild(), "message.music.loop.disabled").block()); em.setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); @@ -307,10 +285,10 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { em.setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer")); + em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()); em.setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); - em.setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.shuffle")); + em.setColor(BotConfig.getMainColor()); + em.setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.shuffle").block()); em.setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); @@ -321,8 +299,8 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { } case "re_music_add" -> { - Modal.Builder builder = Modal.create("re_music_add_modal", LanguageService.getByGuild(event.getGuild(), "label.queueAdd")); - builder.addActionRow(TextInput.create("re_music_add_modal_song", LanguageService.getByGuild(event.getGuild(), "label.song"), TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(512).setMinLength(4).build()); + Modal.Builder builder = Modal.create("re_music_add_modal", LanguageService.getByGuild(event.getGuild(), "label.queueAdd").block()); + builder.addActionRow(TextInput.create("re_music_add_modal_song", LanguageService.getByGuild(event.getGuild(), "label.song").block(), TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(512).setMinLength(4).build()); event.replyModal(builder.build()).queue(); } } @@ -339,89 +317,93 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { switch (event.getModalId()) { case "re_rewards_modal" -> { event.deferReply(true).queue(); - String blackJackString = event.getValue("re_rewards_BlackJackWin").getAsString(); - String musicQuizWinString = event.getValue("re_rewards_MusicQuizWin").getAsString(); - String musicQuizFeatureString = event.getValue("re_rewards_MusicQuizFeature").getAsString(); - String musicQuizArtistString = event.getValue("re_rewards_MusicQuizArtist").getAsString(); - String musicQuizTitleString = event.getValue("re_rewards_MusicQuizTitle").getAsString(); - - double blackJackAmount = 0, musicWinAmount = 0, musicFeatureAmount = 0, musicArtistAmount = 0, musicTitleAmount = 0; - - try { - blackJackAmount = Double.parseDouble(blackJackString); - musicWinAmount = Double.parseDouble(musicQuizWinString); - musicFeatureAmount = Double.parseDouble(musicQuizFeatureString); - musicArtistAmount = Double.parseDouble(musicQuizArtistString); - musicTitleAmount = Double.parseDouble(musicQuizTitleString); - } catch (Exception exception) { - Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.rewards")) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.incorrectNumbers")) - .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); - } + LanguageService.getByGuild(event.getGuild(), "label.rewards").subscribe(title -> { + String blackJackString = event.getValue("re_rewards_BlackJackWin").getAsString(); + String musicQuizWinString = event.getValue("re_rewards_MusicQuizWin").getAsString(); + String musicQuizFeatureString = event.getValue("re_rewards_MusicQuizFeature").getAsString(); + String musicQuizArtistString = event.getValue("re_rewards_MusicQuizArtist").getAsString(); + String musicQuizTitleString = event.getValue("re_rewards_MusicQuizTitle").getAsString(); + + double blackJackAmount = 0, musicWinAmount = 0, musicFeatureAmount = 0, musicArtistAmount = 0, musicTitleAmount = 0; + + try { + blackJackAmount = Double.parseDouble(blackJackString); + musicWinAmount = Double.parseDouble(musicQuizWinString); + musicFeatureAmount = Double.parseDouble(musicQuizFeatureString); + musicArtistAmount = Double.parseDouble(musicQuizArtistString); + musicTitleAmount = Double.parseDouble(musicQuizTitleString); + } catch (Exception exception) { + Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() + .setTitle(title) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.incorrectNumbers").block()) + .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); + } - SQLSession.getSqlConnector().getSqlWorker() - .setSetting(event.getGuild().getIdLong(), "configuration_rewards_blackjack_win", "Payment Amount on BlackJack win", blackJackAmount); + SQLSession.getSqlConnector().getSqlWorker() + .setSetting(event.getGuild().getIdLong(), "configuration_rewards_blackjack_win", "Payment Amount on BlackJack win", blackJackAmount); - SQLSession.getSqlConnector().getSqlWorker() - .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_win", "Payment Amount on Music Quiz win", musicWinAmount); + SQLSession.getSqlConnector().getSqlWorker() + .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_win", "Payment Amount on Music Quiz win", musicWinAmount); - SQLSession.getSqlConnector().getSqlWorker() - .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_feature", "Payment Amount on Music Quiz Feature guess", musicFeatureAmount); + SQLSession.getSqlConnector().getSqlWorker() + .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_feature", "Payment Amount on Music Quiz Feature guess", musicFeatureAmount); - SQLSession.getSqlConnector().getSqlWorker() - .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_artist", "Payment Amount on Music Quiz Artist guess", musicArtistAmount); + SQLSession.getSqlConnector().getSqlWorker() + .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_artist", "Payment Amount on Music Quiz Artist guess", musicArtistAmount); - SQLSession.getSqlConnector().getSqlWorker() - .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_title", "Payment Amount on Music Quiz Title guess", musicTitleAmount); + SQLSession.getSqlConnector().getSqlWorker() + .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_title", "Payment Amount on Music Quiz Title guess", musicTitleAmount); + + Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() + .setTitle(title) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.rewards.success").block()) + .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); + }); - Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.rewards")) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.rewards.success")) - .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); } case "re_feedback_modal" -> { event.deferReply(true).queue(); - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.feedback")) - .setColor(Color.GREEN) - .setThumbnail(event.getUser().getEffectiveAvatarUrl()) - .setDescription("```" + event.getValue("re_feedback_text").getAsString() + "```") - .setFooter("By " + event.getUser().getEffectiveName() + " (" + event.getUser().getId() + ")", event.getUser().getEffectiveAvatarUrl()) - .setTimestamp(Instant.now()); + LanguageService.getByGuild(event.getGuild(), "label.feedback").subscribe(title -> { + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(title) + .setColor(BotConfig.getMainColor()) + .setThumbnail(event.getUser().getEffectiveAvatarUrl()) + .setDescription("```" + event.getValue("re_feedback_text").getAsString() + "```") + .setFooter("By " + event.getUser().getEffectiveName() + " (" + event.getUser().getId() + ")", event.getUser().getEffectiveAvatarUrl()) + .setTimestamp(Instant.now()); - Main.getInstance().getCommandManager().sendMessage(embedBuilder, BotWorker.getShardManager().getTextChannelById(BotConfig.getFeedbackChannel())); - Main.getInstance().getCommandManager().sendMessage("Thank you!", null, event.getInteraction().getHook()); + Main.getInstance().getCommandManager().sendMessage(embedBuilder, BotWorker.getShardManager().getTextChannelById(BotConfig.getFeedbackChannel())); + Main.getInstance().getCommandManager().sendMessage("Thank you!", null, event.getInteraction().getHook()); + }); } - case "re_suggestion_modal" -> { - Suggestions suggestions = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - - event.deferReply(true).queue(); + case "re_suggestion_modal" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(suggestions -> { + event.deferReply(true).queue(); - if (suggestions != null) { - MessageChannel messageChannel = (MessageChannel) event.getGuild().getGuildChannelById(suggestions.getGuildChannelId().getChannelId()); + if (suggestions.isPresent()) { + MessageChannel messageChannel = (MessageChannel) event.getGuild().getGuildChannelById(suggestions.get().getGuildChannelId().getChannelId()); - if (messageChannel == null) return; + if (messageChannel == null) return; - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.suggestion")) - .setColor(Color.ORANGE) - .setThumbnail(event.getMember().getEffectiveAvatarUrl()) - .setDescription("```" + event.getValue("re_suggestion_text").getAsString() + "```") - .setFooter(LanguageService.getByGuild(event.getGuild(), "message.suggestion.footer", event.getUser().getEffectiveName()), event.getMember().getEffectiveAvatarUrl()) - .setTimestamp(Instant.now()); + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.suggestion").block()) + .setColor(Color.ORANGE) + .setThumbnail(event.getMember().getEffectiveAvatarUrl()) + .setDescription("```" + event.getValue("re_suggestion_text").getAsString() + "```") + .setFooter(LanguageService.getByGuild(event.getGuild(), "message.suggestion.footer", event.getUser().getEffectiveName()).block(), event.getMember().getEffectiveAvatarUrl()) + .setTimestamp(Instant.now()); - Main.getInstance().getCommandManager().sendMessage(embedBuilder, messageChannel); - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.sent"), null, event.getInteraction().getHook()); - } else { - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.notSetup"), null, event.getInteraction().getHook()); - } - } + Main.getInstance().getCommandManager().sendMessage(embedBuilder, messageChannel); + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.sent"), null, event.getInteraction().getHook()); + } else { + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.notSetup"), null, event.getInteraction().getHook()); + } + }); case "re_music_add_modal" -> { event.deferReply(true).queue(); @@ -436,72 +418,75 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - String twitchUsername = modalMapping.getAsString(); + LanguageService.getByGuild(event.getGuild(), "label.statistics").subscribe(label -> { + String twitchUsername = modalMapping.getAsString(); - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); + java.util.List categories = event.getGuild().getCategoriesByName(label, true); - Category category; + Category category; - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); - } else { - category = categories.get(0); - } + if (categories.isEmpty()) { + category = event.getGuild().createCategory(label).complete(); + } else { + category = categories.get(0); + } - String channelId = Main.getInstance().getNotifier().getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(twitchUsername)).execute().getUsers().get(0).getId(); + String channelId = Main.getInstance().getNotifier().getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(twitchUsername)).execute().getUsers().get(0).getId(); - TwitchIntegration twitchIntegration = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE channelId=:twitchId", Map.of("twitchId", channelId)); - if (twitchIntegration == null) { - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.stream-action.noTwitch", BotConfig.getTwitchAuth())); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitchCountName", Main.getInstance().getNotifier().getTwitchClient().getHelix().getChannelFollowers(null, channelId, null, 1, null).execute().getTotal()), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { - - if (channelStats.getTwitchFollowerChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitchFollowerChannelId()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE channelId=:twitchId", Map.of("twitchId", channelId)).subscribe(twitchIntegration -> { + if (twitchIntegration.isPresent()) { + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.stream-action.noTwitch", BotConfig.getTwitchAuth()).block()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitchCountName", Main.getInstance().getNotifier().getTwitchClient().getHelix().getChannelFollowers(null, channelId, null, 1, null).execute().getTotal()).block(), category) + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { + if (channelStats.isPresent()) { + ChannelStats channelStatsEntity = channelStats.get(); + if (channelStatsEntity.getTwitchFollowerChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStatsEntity.getTwitchFollowerChannelId()); - channelStats.setTwitchFollowerChannelId(voiceChannel.getId()); - channelStats.setTwitchFollowerChannelUsername(twitchUsername); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - voiceChannel.getId(), - twitchUsername, - null, - null, - null, - null, - null, - null, - null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); - } - }); + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitchSuccess")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + channelStatsEntity.setTwitchFollowerChannelId(voiceChannel.getId()); + channelStatsEntity.setTwitchFollowerChannelUsername(twitchUsername); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStatsEntity).block(); + Main.getInstance().getNotifier().getTwitchSonic().add(twitchUsername); + } else { + ChannelStats channelStatsEntity = new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + voiceChannel.getId(), + twitchUsername, + null, + null, + null, + null, + null, + null, + null, + null); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStatsEntity).block(); + Main.getInstance().getNotifier().getTwitterSonic().add(twitchUsername); + } + })); + + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitchSuccess").block()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); + }); } case "statisticsSetupYouTubeModal" -> { @@ -511,93 +496,93 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - String youtubeChannelName = modalMapping.getAsString(); - - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); + LanguageService.getByGuild(event.getGuild(), "label.statistics").subscribe(label -> { + String youtubeChannelName = modalMapping.getAsString(); - Category category; + java.util.List categories = event.getGuild().getCategoriesByName(label, true); - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess")); + Category category; - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); - } else { - category = categories.get(0); - } + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess").block()); - ChannelResult youTubeChannel; - try { - if (YouTubeAPIHandler.getInstance().isValidChannelId(youtubeChannelName)) { - youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelById(youtubeChannelName); + if (categories.isEmpty()) { + category = event.getGuild().createCategory(label).complete(); } else { - youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelBySearch(youtubeChannelName); + category = categories.get(0); } - } catch (Exception e) { - embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } - if (youTubeChannel == null) { - embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeNotFound")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } + ChannelResult youTubeChannel; + try { + if (YouTubeAPIHandler.getInstance().isValidChannelId(youtubeChannelName)) { + youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelById(youtubeChannelName); + } else { + youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelBySearch(youtubeChannelName); + } + } catch (Exception e) { + embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").block()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { + if (youTubeChannel == null) { + embedBuilder = embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeNotFound").block()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - if (channelStats.getYoutubeSubscribersChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getYoutubeSubscribersChannelId()); + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).block(), category) + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); + if (channelStats.getYoutubeSubscribersChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getYoutubeSubscribersChannelId()); - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } - channelStats.setYoutubeSubscribersChannelId(voiceChannel.getId()); - channelStats.setYoutubeSubscribersChannelUsername(youTubeChannel.getId()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - null, - null, - null, - null, - null, - null, - voiceChannel.getId(), - youTubeChannel.getId(), - null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); - } - }); + channelStats.setYoutubeSubscribersChannelId(voiceChannel.getId()); + channelStats.setYoutubeSubscribersChannelUsername(youTubeChannel.getId()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + Main.getInstance().getNotifier().getYouTubeSonic().add(youTubeChannel.getId()); + } else { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + voiceChannel.getId(), + youTubeChannel.getId(), + null, + null)).block(); + Main.getInstance().getNotifier().getYouTubeSonic().add(youTubeChannel.getId()); + } + })); - embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + embedBuilder = embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess").block()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } case "statisticsSetupRedditModal" -> { @@ -607,79 +592,79 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - String subredditName = modalMapping.getAsString(); + LanguageService.getByGuild(event.getGuild(), "label.statistics").subscribe(label -> { + String subredditName = modalMapping.getAsString(); - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); + java.util.List categories = event.getGuild().getCategoriesByName(label, true); - Category category; + Category category; - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess")); + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess").block()); - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); - } else { - category = categories.get(0); - } + if (categories.isEmpty()) { + category = event.getGuild().createCategory(label).complete(); + } else { + category = categories.get(0); + } - RedditSubreddit subreddit; - try { - subreddit = Main.getInstance().getNotifier().getSubreddit(subredditName); - } catch (IOException | InterruptedException e) { - embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } + RedditSubreddit subreddit; + try { + subreddit = Main.getInstance().getNotifier().getRedditSonic().getSubreddit(subredditName); + } catch (IOException | InterruptedException e) { + embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").block()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.redditCountName", subreddit.getActiveUserCount()), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.redditCountName", subreddit.getActiveUserCount()).block(), category) + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); + if (channelStats.getSubredditMemberChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getSubredditMemberChannelId()); - if (channelStats.getSubredditMemberChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getSubredditMemberChannelId()); + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); + channelStats.setSubredditMemberChannelId(voiceChannel.getId()); + channelStats.setSubredditMemberChannelSubredditName(subredditName); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + Main.getInstance().getNotifier().getRedditSonic().add(subredditName); + } else { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + voiceChannel.getId(), + subredditName)).block(); + Main.getInstance().getNotifier().getRedditSonic().add(subredditName); } + })); - channelStats.setSubredditMemberChannelId(voiceChannel.getId()); - channelStats.setSubredditMemberChannelSubredditName(subredditName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerSubreddit(subredditName); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - voiceChannel.getId(), - subredditName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerSubreddit(subredditName); - } - }); - - embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + embedBuilder = embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess").block()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } case "statisticsSetupTwitterModal" -> { @@ -689,79 +674,79 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - String twitterName = modalMapping.getAsString(); + LanguageService.getByGuild(event.getGuild(), "label.statistics").subscribe(label -> { + String twitterName = modalMapping.getAsString(); - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); + java.util.List categories = event.getGuild().getCategoriesByName(label, true); - Category category; + Category category; - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess")); + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess").block()); - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); - } else { - category = categories.get(0); - } + if (categories.isEmpty()) { + category = event.getGuild().createCategory(label).complete(); + } else { + category = categories.get(0); + } - UserV2 twitterUser; - try { - twitterUser = Main.getInstance().getNotifier().getTwitterClient().getUserFromUserName(twitterName); - } catch (NoSuchElementException e) { - embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } + UserV2 twitterUser; + try { + twitterUser = Main.getInstance().getNotifier().getTwitterClient().getUserFromUserName(twitterName); + } catch (NoSuchElementException e) { + embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").block()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).block(), category) + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); + if (channelStats.getTwitterFollowerChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitterFollowerChannelId()); - if (channelStats.getTwitterFollowerChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitterFollowerChannelId()); + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); + channelStats.setTwitterFollowerChannelId(voiceChannel.getId()); + channelStats.setTwitterFollowerChannelUsername(twitterName); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + Main.getInstance().getNotifier().getTwitterSonic().add(twitterName); + } else { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + voiceChannel.getId(), + twitterName, + null, + null, + null, + null, + null, + null, + null, + null)).block(); + Main.getInstance().getNotifier().getTwitterSonic().add(twitterName); } + })); - channelStats.setTwitterFollowerChannelId(voiceChannel.getId()); - channelStats.setTwitterFollowerChannelUsername(twitterName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerTwitterUser(twitterName); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - voiceChannel.getId(), - twitterName, - null, - null, - null, - null, - null, - null, - null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerTwitterUser(twitterName); - } - }); - - embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + embedBuilder = embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess").block()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } case "statisticsSetupInstagramModal" -> { @@ -771,86 +756,86 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - String instagramName = modalMapping.getAsString(); + LanguageService.getByGuild(event.getGuild(), "label.statistics").subscribe(label -> { + String instagramName = modalMapping.getAsString(); - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); + java.util.List categories = event.getGuild().getCategoriesByName(label, true); - Category category; + Category category; - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess")); + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess").block()); - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); - } else { - category = categories.get(0); - } + if (categories.isEmpty()) { + category = event.getGuild().createCategory(label).complete(); + } else { + category = categories.get(0); + } - com.github.instagram4j.instagram4j.models.user.User instagramUser; - try { - instagramUser = Main.getInstance().getNotifier().getInstagramClient().getActions().users().findByUsername(instagramName).get().getUser(); - } catch (ExecutionException | InterruptedException e) { - embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } + com.github.instagram4j.instagram4j.models.user.User instagramUser; + try { + instagramUser = Main.getInstance().getNotifier().getInstagramClient().getActions().users().findByUsername(instagramName).get().getUser(); + } catch (ExecutionException | InterruptedException e) { + embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").block()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.instagramCountName", instagramUser.getFollower_count()), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.instagramCountName", instagramUser.getFollower_count()).block(), category) + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); + if (channelStats.getInstagramFollowerChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getInstagramFollowerChannelId()); - if (channelStats.getInstagramFollowerChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getInstagramFollowerChannelId()); + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); + channelStats.setInstagramFollowerChannelId(voiceChannel.getId()); + channelStats.setInstagramFollowerChannelUsername(instagramName); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + Main.getInstance().getNotifier().getInstagramSonic().add(instagramName); + } else { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + null, + null, + voiceChannel.getId(), + instagramName, + null, + null, + null, + null, + null, + null)).block(); + Main.getInstance().getNotifier().getInstagramSonic().add(instagramName); } + })); - channelStats.setInstagramFollowerChannelId(voiceChannel.getId()); - channelStats.setInstagramFollowerChannelUsername(instagramName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerInstagramUser(instagramName); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - null, - null, - voiceChannel.getId(), - instagramName, - null, - null, - null, - null, - null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerInstagramUser(instagramName); - } - }); - - embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + embedBuilder = embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(BotConfig.getMainColor()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess").block()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } default -> event.deferEdit().setEmbeds(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.unknownMenu")) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.unknownMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.unknownMenu")) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.unknownMenu").block()) .build()).setComponents(new ArrayList<>()).queue(); } } @@ -879,33 +864,35 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even return; } - // We are doing this because a normal List can't be modified. - ArrayList values = new ArrayList<>(event.getValues()); + SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(event.getGuild().getIdLong()).subscribe(roles -> { + // We are doing this because a normal List can't be modified. + ArrayList values = new ArrayList<>(event.getValues()); - EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); - if (event.getSelectedOptions().isEmpty()) { - SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(event.getGuild().getIdLong()).forEach(autoRole -> - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole)); - } else { - SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(event.getGuild().getIdLong()).forEach(autoRole -> { - String value = String.valueOf(autoRole.getRoleId()); + EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); + if (event.getSelectedOptions().isEmpty()) { + roles.forEach(autoRole -> + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole).block()); + } else { + roles.forEach(autoRole -> { + String value = String.valueOf(autoRole.getRoleId()); - if (!event.getValues().contains(value)) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole); - values.remove(value); - } - }); + if (!event.getValues().contains(value)) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole).block(); + values.remove(value); + } + }); - for (String roleId : values) { - Role role = event.getGuild().getRoleById(roleId); - if (role != null) { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new AutoRole(event.getGuild().getIdLong(), role.getIdLong())); + for (String roleId : values) { + Role role = event.getGuild().getRoleById(roleId); + if (role != null) { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new AutoRole(event.getGuild().getIdLong(), role.getIdLong())).block(); + } } } - } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.autoRole.setupSuccess")); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.autoRole.setupSuccess").block()); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } case "setupActionMenu" -> { @@ -920,106 +907,110 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even switch (event.getInteraction().getValues().get(0)) { - case "rewards" -> { - TextInput blackJackWin = TextInput.create("re_rewards_BlackJackWin", LanguageService.getByGuild(event.getGuild(), "label.blackJackWin"), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizWin = TextInput.create("re_rewards_MusicQuizWin", LanguageService.getByGuild(event.getGuild(), "label.musicQuizWin"), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizFeature = TextInput.create("re_rewards_MusicQuizFeature", LanguageService.getByGuild(event.getGuild(), "label.musicQuizFeatureGuess"), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizArtist = TextInput.create("re_rewards_MusicQuizArtist", LanguageService.getByGuild(event.getGuild(), "label.musicQuizArtistGuess"), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizTitle = TextInput.create("re_rewards_MusicQuizTitle", LanguageService.getByGuild(event.getGuild(), "label.musicQuizTitleGuess"), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - Modal modal = Modal.create("re_rewards_modal", LanguageService.getByGuild(event.getGuild(), "label.rewards")).addActionRow(blackJackWin).addActionRow(musicQuizWin).addActionRow(musicQuizFeature).addActionRow(musicQuizArtist).addActionRow(musicQuizTitle).build(); - event.replyModal(modal).queue(); - } + case "rewards" -> + LanguageService.getByGuild(event.getGuild(), "label.rewards").subscribe(rewardLabel -> { + TextInput blackJackWin = TextInput.create("re_rewards_BlackJackWin", LanguageService.getByGuild(event.getGuild(), "label.blackJackWin").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizWin = TextInput.create("re_rewards_MusicQuizWin", LanguageService.getByGuild(event.getGuild(), "label.musicQuizWin").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizFeature = TextInput.create("re_rewards_MusicQuizFeature", LanguageService.getByGuild(event.getGuild(), "label.musicQuizFeatureGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizArtist = TextInput.create("re_rewards_MusicQuizArtist", LanguageService.getByGuild(event.getGuild(), "label.musicQuizArtistGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizTitle = TextInput.create("re_rewards_MusicQuizTitle", LanguageService.getByGuild(event.getGuild(), "label.musicQuizTitleGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + Modal modal = Modal.create("re_rewards_modal", rewardLabel).addActionRow(blackJackWin).addActionRow(musicQuizWin).addActionRow(musicQuizFeature).addActionRow(musicQuizArtist).addActionRow(musicQuizTitle).build(); + event.replyModal(modal).queue(); + }); - case "lang" -> { + case "lang" -> + LanguageService.getByGuild(event.getGuild(), "message.setup.steps.lang").subscribe(description -> { + for (DiscordLocale locale : LanguageService.getSupported()) { + optionList.add(SelectOption.of(locale.getLanguageName(), locale.getLocale())); + } - for (DiscordLocale locale : LanguageService.getSupported()) { - optionList.add(SelectOption.of(locale.getLanguageName(), locale.getLocale())); - } + embedBuilder.setDescription(description); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.lang")); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLangMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLangMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); - } + case "log" -> LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { + optionList.add(SelectOption.of(label, "logSetup")); - case "log" -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setup"), "logSetup")); + if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).block()) + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "logDelete")); - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong())) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete"), "logDelete")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu"), "backToSetupMenu")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.auditLog").block()); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.auditLog")); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); - } + case "welcome" -> LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { + optionList.add(SelectOption.of(label, "welcomeSetup")); - case "welcome" -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setup"), "welcomeSetup")); + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).block().ifPresent(welcomeWebhook -> optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "welcomeDelete"))); - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong())) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete"), "welcomeDelete")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setImage").block(), "welcomeImage")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setImage"), "welcomeImage")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu"), "backToSetupMenu")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.welcome").block()); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.welcome")); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); - } + case "autorole" -> + Setup.createAutoRoleSetupSelectMenu(event.getGuild(), event.getHook()).subscribe(selectMenu -> + event.editMessageEmbeds(Setup.createAutoRoleSetupMessage(event.getGuild(), event.getHook()).build()) + .setComponents( + ActionRow.of(selectMenu), + ActionRow.of(Button.link(BotConfig.getWebinterface(), "Webinterface"))) + .queue()); - case "autorole" -> event.editMessageEmbeds(Setup.createAutoRoleSetupMessage(event.getGuild(), event.getHook()).build()) - .setComponents( - ActionRow.of(Setup.createAutoRoleSetupSelectMenu(event.getGuild(), event.getHook())), - ActionRow.of(Button.link(BotConfig.getWebinterface(), "Webinterface"))) - .queue(); + case "tempvoice" -> LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { + optionList.add(SelectOption.of(label, "tempVoiceSetup")); - case "tempvoice" -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setup"), "tempVoiceSetup")); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", + Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(temporalVoicechannel -> optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "tempVoiceDelete"))); - if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())) != null) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete"), "tempVoiceDelete")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu"), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.temporalVoice")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.temporalVoice").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoiceMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoiceMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); - case "statistics" -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupMemberStatistics"), "statisticsSetupMember")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics"), "statisticsSetupTwitch")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics"), "statisticsSetupYouTube")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics"), "statisticsSetupReddit")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics"), "statisticsSetupTwitter")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics"), "statisticsSetupInstagram")); + case "statistics" -> + LanguageService.getByGuild(event.getGuild(), "message.statistics.setup").subscribe(description -> { + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupMemberStatistics").block(), "statisticsSetupMember")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").block(), "statisticsSetupTwitch")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").block(), "statisticsSetupYouTube")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").block(), "statisticsSetupReddit")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").block(), "statisticsSetupTwitter")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").block(), "statisticsSetupInstagram")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu"), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.setup")); + embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupStatisticsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupStatisticsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); - case "tickets" -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setup"), "ticketsSetup")); + case "tickets" -> LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { + optionList.add(SelectOption.of(label, "ticketsSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())) != null) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete"), "ticketsDelete")); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(tickets -> optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "ticketsDelete"))); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu"), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.setup")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.setup").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTicketsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTicketsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); - default -> { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); - } + default -> + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } @@ -1035,118 +1026,128 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); - case "statisticsSetupMember" -> { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.memberSuccess")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); - - Category category; - - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); - } else { - category = categories.get(0); - } - - event.getGuild().loadMembers().onSuccess(members -> event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.overallMembersName", event.getGuild().getMemberCount()), category).queue(voiceChannel -> { - voiceChannel.getManager().setUserLimit(0).queue(); - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.realMembersName", members.stream().filter(member -> !member.getUser().isBot()).count()), category).queue(voiceChannel1 -> { - voiceChannel1.getManager().setUserLimit(0).queue(); - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.botMembersName", members.stream().filter(member -> member.getUser().isBot()).count()), category).queue(voiceChannel2 -> { - voiceChannel2.getManager().setUserLimit(0).queue(); - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { - if (channelStats.getMemberStatsChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getMemberStatsChannelId()); + case "statisticsSetupMember" -> + LanguageService.getByGuild(event.getGuild(), "message.statistics.memberSuccess").subscribe(description -> { + embedBuilder.setDescription(description); + embedBuilder.setColor(BotConfig.getMainColor()); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics").block(), true); - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - if (channelStats.getRealMemberStatsChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getRealMemberStatsChannelId()); + Category category; - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - if (channelStats.getBotMemberStatsChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getBotMemberStatsChannelId()); + if (categories.isEmpty()) { + category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics").block()).complete(); + } else { + category = categories.get(0); + } - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - channelStats.setMemberStatsChannelId(voiceChannel.getId()); - channelStats.setRealMemberStatsChannelId(voiceChannel1.getId()); - channelStats.setBotMemberStatsChannelId(voiceChannel2.getId()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - voiceChannel.getId(), - voiceChannel1.getId(), - voiceChannel2.getId(), - null, - null, - null, - null, - null, - null, - null, - null, - null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - } - }); + event.getGuild().loadMembers().onSuccess(members -> event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.overallMembersName", event.getGuild().getMemberCount()).block(), category).queue(voiceChannel -> { + voiceChannel.getManager().setUserLimit(0).queue(); + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.realMembersName", members.stream().filter(member -> !member.getUser().isBot()).count()).block(), category).queue(voiceChannel1 -> { + voiceChannel1.getManager().setUserLimit(0).queue(); + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.botMembersName", members.stream().filter(member -> member.getUser().isBot()).count()).block(), category).queue(voiceChannel2 -> { + voiceChannel2.getManager().setUserLimit(0).queue(); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); + if (channelStats.getMemberStatsChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getMemberStatsChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } + if (channelStats.getRealMemberStatsChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getRealMemberStatsChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } + if (channelStats.getBotMemberStatsChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getBotMemberStatsChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } + channelStats.setMemberStatsChannelId(voiceChannel.getId()); + channelStats.setRealMemberStatsChannelId(voiceChannel1.getId()); + channelStats.setBotMemberStatsChannelId(voiceChannel2.getId()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + } else { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), + voiceChannel.getId(), + voiceChannel1.getId(), + voiceChannel2.getId(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null)).block(); + } + }); + + }); + }); + })); }); - })); - } - case "statisticsSetupTwitch" -> { - TextInput input = TextInput.create("twitchChannelName", LanguageService.getByGuild(event.getGuild(), "label.channelName"), TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitch Channel name here!").build(); + case "statisticsSetupTwitch" -> + LanguageService.getByGuild(event.getGuild(), "label.channelName").subscribe(label -> { + TextInput input = TextInput.create("twitchChannelName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitch Channel name here!").build(); - Modal modal = Modal.create("statisticsSetupTwitchModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics")).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupTwitchModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").block()).addActionRow(input).build(); - event.replyModal(modal).queue(); - } + event.replyModal(modal).queue(); + }); - case "statisticsSetupYouTube" -> { - TextInput input = TextInput.create("youtubeChannelName", LanguageService.getByGuild(event.getGuild(), "label.channelName"), TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the YouTube Channel name here!").build(); + case "statisticsSetupYouTube" -> + LanguageService.getByGuild(event.getGuild(), "label.channelName").subscribe(label -> { + TextInput input = TextInput.create("youtubeChannelName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the YouTube Channel name here!").build(); - Modal modal = Modal.create("statisticsSetupYouTubeModal", LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics")).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupYouTubeModal", LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").block()).addActionRow(input).build(); - event.replyModal(modal).queue(); - } + event.replyModal(modal).queue(); + }); - case "statisticsSetupReddit" -> { - TextInput input = TextInput.create("subredditName", LanguageService.getByGuild(event.getGuild(), "label.subreddit"), TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Subreddit name here!").build(); + case "statisticsSetupReddit" -> + LanguageService.getByGuild(event.getGuild(), "label.subreddit").subscribe(label -> { + TextInput input = TextInput.create("subredditName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Subreddit name here!").build(); - Modal modal = Modal.create("statisticsSetupRedditModal", LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics")).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupRedditModal", LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").block()).addActionRow(input).build(); - event.replyModal(modal).queue(); - } + event.replyModal(modal).queue(); + }); - case "statisticsSetupTwitter" -> { - TextInput input = TextInput.create("twitterName", LanguageService.getByGuild(event.getGuild(), "label.name"), TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitter name here!").build(); + case "statisticsSetupTwitter" -> + LanguageService.getByGuild(event.getGuild(), "label.name").subscribe(label -> { + TextInput input = TextInput.create("twitterName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitter name here!").build(); - Modal modal = Modal.create("statisticsSetupTwitterModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics")).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupTwitterModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").block()).addActionRow(input).build(); - event.replyModal(modal).queue(); - } + event.replyModal(modal).queue(); + }); - case "statisticsSetupInstagram" -> { - TextInput input = TextInput.create("instagramName", LanguageService.getByGuild(event.getGuild(), "label.name"), TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Instagram name here!").build(); + case "statisticsSetupInstagram" -> + LanguageService.getByGuild(event.getGuild(), "label.name").subscribe(label -> { + TextInput input = TextInput.create("instagramName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Instagram name here!").build(); - Modal modal = Modal.create("statisticsSetupInstagramModal", LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics")).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupInstagramModal", LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").block()).addActionRow(input).build(); - event.replyModal(modal).queue(); - } + event.replyModal(modal).queue(); + }); default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } } @@ -1162,29 +1163,30 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); - case "ticketsSetup" -> { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.setupDescription")); - - event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); - } - - case "ticketsDelete" -> { - Tickets tickets = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); + case "ticketsSetup" -> + LanguageService.getByGuild(event.getGuild(), "message.ticket.setupDescription").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); + }); - if (tickets != null) { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.deleted")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets); - } - } + case "ticketsDelete" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { + if (tickets.isPresent()) { + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.deleted").block()); + embedBuilder.setColor(BotConfig.getMainColor()); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets.get()).block(); + } + }); default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } } @@ -1199,28 +1201,34 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); if (value.equalsIgnoreCase("more")) { - java.util.List optionList = new ArrayList<>(); + LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription").subscribe(description -> { + java.util.List optionList = new ArrayList<>(); - for (VoiceChannel channel : event.getGuild().getVoiceChannels().stream().skip(24).toList()) { - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + for (VoiceChannel channel : event.getGuild().getVoiceChannels().stream().skip(24).toList()) { + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription")); + embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); + }); return; } VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(value); if (voiceChannel != null) { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(event.getGuild().getIdLong(), voiceChannel.getIdLong())); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupSuccess")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupSuccess").subscribe(description -> { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(event.getGuild().getIdLong(), voiceChannel.getIdLong())).block(); + embedBuilder.setDescription(description); + embedBuilder.setColor(BotConfig.getMainColor()); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } else { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } @@ -1238,38 +1246,40 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); - case "tempVoiceSetup" -> { - for (VoiceChannel channel : event.getGuild().getVoiceChannels()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.more"), "more")); - break; - } - - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + case "tempVoiceSetup" -> + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { + for (VoiceChannel channel : event.getGuild().getVoiceChannels()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(labelMore, "more")); + break; + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription")); + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); - } + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription").block()); - case "tempVoiceDelete" -> { - TemporalVoicechannel temporalVoicechannel = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); + }); - if (temporalVoicechannel != null) { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.deleted")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel); - } - } + case "tempVoiceDelete" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(temporalVoicechannel -> { + if (temporalVoicechannel.isPresent()) { + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.deleted").block()); + embedBuilder.setColor(BotConfig.getMainColor()); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel.get()).block(); + } + }); default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } } @@ -1285,13 +1295,17 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (selectedLocale != DiscordLocale.UNKNOWN && LanguageService.getSupported().contains(selectedLocale)) { Language language = LanguageService.languageResources.get(selectedLocale); - SQLSession.getSqlConnector().getSqlWorker().setSetting(event.getGuild().getIdLong(), "configuration_language", "Language", selectedLocale.getLocale()); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.lang.setupSuccess", language.getName() + " by " + language.getAuthor())); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.lang.setupSuccess", language.getName() + " by " + language.getAuthor()).subscribe(description -> { + SQLSession.getSqlConnector().getSqlWorker().setSetting(event.getGuild().getIdLong(), "configuration_language", "Language", selectedLocale.getLocale()); + embedBuilder.setDescription(description); + embedBuilder.setColor(BotConfig.getMainColor()); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } else { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } @@ -1309,41 +1323,40 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); - case "logSetup" -> { - for (TextChannel channel : event.getGuild().getTextChannels()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.more"), "more")); - break; - } - - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } - - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription")); + case "logSetup" -> + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { + for (TextChannel channel : event.getGuild().getTextChannels()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(labelMore, "more")); + break; + } - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - case "logDelete" -> { - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").block()); - if (webhook != null) { - event.getJDA().retrieveWebhookById(webhook.getChannelId()).queue(webhook1 -> { - webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhook); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); }); - } - } + + case "logDelete" -> + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> + webhook.ifPresent(webhookLog -> event.getJDA().retrieveWebhookById(webhookLog.getChannelId()).queue(webhook1 -> { + webhook1.delete().queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted").block()); + embedBuilder.setColor(BotConfig.getMainColor()); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookLog).block(); + }))); default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } } @@ -1359,20 +1372,22 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); if (value.equals("more")) { - java.util.List optionList = new ArrayList<>(); + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { + java.util.List optionList = new ArrayList<>(); - for (TextChannel channel : event.getGuild().getTextChannels().stream().skip(24).toList()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.more"), "more")); - break; - } + for (TextChannel channel : event.getGuild().getTextChannels().stream().skip(24).toList()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(labelMore, "more")); + break; + } - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); + }); return; } @@ -1381,17 +1396,15 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (textChannel != null) { textChannel.createWebhook(BotConfig.getBotName() + "-Logs").queue(webhook -> { - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong())); - } - + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).block().ifPresent(webhookEntity -> + WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), webhookEntity)); SQLSession.getSqlConnector().getSqlWorker().setLogWebhook(event.getGuild().getIdLong(), textChannel.getIdLong(), webhook.getIdLong(), webhook.getToken()); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupSuccess")); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupSuccess").block()); + embedBuilder.setColor(BotConfig.getMainColor()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").block()); event.editMessageEmbeds(embedBuilder.build()).queue(); } @@ -1411,46 +1424,46 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); - case "welcomeSetup" -> { - for (TextChannel channel : event.getGuild().getTextChannels()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.more"), "more")); - break; - } - - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } - - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription")); + case "welcomeSetup" -> + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(moreLabel -> { + for (TextChannel channel : event.getGuild().getTextChannels()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(moreLabel, "more")); + break; + } - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - case "welcomeImage" -> { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.imageRequired")); - event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); - } + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription").block()); - case "welcomeDelete" -> { - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); + }); - if (webhook != null) { - event.getJDA().retrieveWebhookById(webhook.getChannelId()).queue(webhook1 -> { - webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhook); + case "welcomeImage" -> + LanguageService.getByGuild(event.getGuild(), "message.welcome.imageRequired").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); }); - } - } + + case "welcomeDelete" -> + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> + webhook.ifPresent(webhookWelcome -> event.getJDA().retrieveWebhookById(webhookWelcome.getChannelId()).queue(webhook1 -> { + webhook1.delete().queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted").block()); + embedBuilder.setColor(BotConfig.getMainColor()); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookWelcome).block(); + }))); default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } } @@ -1466,20 +1479,22 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even String value = event.getInteraction().getValues().get(0); if (value.equals("more")) { - java.util.List optionList = new ArrayList<>(); + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { + java.util.List optionList = new ArrayList<>(); - for (TextChannel channel : event.getGuild().getTextChannels().stream().skip(24).toList()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.more"), "more")); - break; - } + for (TextChannel channel : event.getGuild().getTextChannels().stream().skip(24).toList()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(labelMore, "more")); + break; + } - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); + }); return; } @@ -1487,18 +1502,20 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (textChannel != null) { textChannel.createWebhook(BotConfig.getBotName() + "-Welcome").queue(webhook -> { - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong())); - } + // .block() can be called here because its being queued. + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).block().ifPresent(webhookEntity -> + WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), webhookEntity)); SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(event.getGuild().getIdLong(), textChannel.getIdLong(), webhook.getIdLong(), webhook.getToken()); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupSuccess")); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupSuccess").block()); + embedBuilder.setColor(BotConfig.getMainColor()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } @@ -1506,10 +1523,13 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { + EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); + + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); } } } @@ -1520,20 +1540,22 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even * @param event The InteractionEvent of the SelectMenu. */ public void sendDefaultChoice(StringSelectInteractionEvent event) { - EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); - - List optionList = new ArrayList<>(); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.language"), "lang")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.auditLog"), "log")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.welcomeChannel"), "welcome")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.autoRole"), "autorole")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.temporalVoice"), "tempvoice")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.statistics"), "statistics")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.ticketSystem"), "tickets")); - - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenu")); - - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupActionMenu", LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenuPlaceholder"), 1, 1, false, optionList)).queue(); + LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenu").subscribe(description -> { + EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); + + List optionList = new ArrayList<>(); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.language").block(), "lang")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.auditLog").block(), "log")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.welcomeChannel").block(), "welcome")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.autoRole").block(), "autorole")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.temporalVoice").block(), "tempvoice")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.statistics").block(), "statistics")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.ticketSystem").block(), "tickets")); + + embedBuilder.setDescription(description); + + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupActionMenu", LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenuPlaceholder").block(), 1, 1, false, optionList)).queue(); + }); } /** @@ -1545,12 +1567,12 @@ public void sendDefaultChoice(StringSelectInteractionEvent event) { */ private boolean checkPerms(Member member, MessageChannel channel) { if (member == null || !member.hasPermission(Permission.ADMINISTRATOR)) { - channel.sendMessage(LanguageService.getByGuild((member == null ? null : member.getGuild()), "message.default.insufficientPermission", Permission.ADMINISTRATOR.name())).queue(); + channel.sendMessage(LanguageService.getByGuild((member == null ? null : member.getGuild()), "message.default.insufficientPermission", Permission.ADMINISTRATOR.name()).block()).queue(); return true; } if (!member.getGuild().getSelfMember().hasPermission(Permission.MANAGE_WEBHOOKS)) { - channel.sendMessage(LanguageService.getByGuild(member.getGuild(), "message.default.needPermission", Permission.MANAGE_WEBHOOKS.name())).queue(); + channel.sendMessage(LanguageService.getByGuild(member.getGuild(), "message.default.needPermission", Permission.MANAGE_WEBHOOKS.name()).block()).queue(); return true; } diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index 966848aef..bced6b12d 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -14,12 +14,11 @@ import de.presti.ree6.sql.entities.ReactionRole; import de.presti.ree6.sql.entities.TemporalVoicechannel; import de.presti.ree6.sql.entities.Tickets; -import de.presti.ree6.sql.entities.level.ChatUserLevel; -import de.presti.ree6.sql.entities.level.VoiceUserLevel; import de.presti.ree6.sql.entities.stats.ChannelStats; import de.presti.ree6.utils.apis.ChatGPTAPI; import de.presti.ree6.utils.data.ArrayUtil; import de.presti.ree6.utils.data.ImageCreationUtility; +import de.presti.ree6.utils.data.TranscriptUtil; import de.presti.ree6.utils.others.*; import io.sentry.Sentry; import lombok.extern.slf4j.Slf4j; @@ -47,8 +46,11 @@ import net.dv8tion.jda.api.events.session.ReadyEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.managers.AudioManager; +import net.dv8tion.jda.api.requests.restaction.MessageEditAction; import net.dv8tion.jda.internal.utils.PermissionUtil; import org.jetbrains.annotations.NotNull; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; import javax.annotation.Nonnull; import java.io.IOException; @@ -87,7 +89,7 @@ public void onReady(@Nonnull ReadyEvent event) { */ @Override public void onGuildJoin(@NotNull GuildJoinEvent event) { - SQLSession.getSqlConnector().getSqlWorker().createSettings(event.getGuild().getIdLong()); + SQLSession.getSqlConnector().getSqlWorker().createCommandSettings(event.getGuild().getIdLong()); } /** @@ -104,63 +106,72 @@ public void onGuildLeave(@Nonnull GuildLeaveEvent event) { @Override public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { - ThreadUtil.createThread(x -> { - - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())); - if (channelStats != null) { - if (channelStats.getMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getMemberStatsChannelId()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())).subscribe(channelStats -> { + if (channelStats.isPresent()) { + ChannelStats channelStatsEntity = channelStats.get(); + if (channelStatsEntity.getMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.overallMembers") + ": " + event.getGuild().getMemberCount()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.overallMembers").block() + ": " + event.getGuild().getMemberCount()).queue(); } } event.getGuild().loadMembers().onSuccess(members -> { - if (channelStats.getRealMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getRealMemberStatsChannelId()); + if (channelStatsEntity.getRealMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getRealMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.realMembers") + ": " + members.stream().filter(member -> !member.getUser().isBot()).count()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.realMembers").block() + ": " + members.stream().filter(member -> !member.getUser().isBot()).count()).queue(); } } - if (channelStats.getBotMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getBotMemberStatsChannelId()); + if (channelStatsEntity.getBotMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getBotMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.botMembers") + ": " + members.stream().filter(member -> member.getUser().isBot()).count()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.botMembers").block() + ": " + members.stream().filter(member -> member.getUser().isBot()).count()).queue(); } } }); } + }); - GuildUtil.handleMemberJoin(event.getGuild(), event.getMember()); - - if (!SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong())) return; - - WebhookMessageBuilder wmb = new WebhookMessageBuilder(); + GuildUtil.handleMemberJoin(event.getGuild(), event.getMember()); + + SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).subscribe(x -> { + if (x) { + WebhookMessageBuilder wmb = new WebhookMessageBuilder(); + + wmb.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wmb.setUsername("Welcome!"); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join").subscribe(messageSetting -> { + if (messageSetting.isPresent()) { + final String messageContent = messageSetting.get().getStringValue() + .replace("%user_name%", event.getMember().getUser().getName()) + .replace("%guild_name%", event.getGuild().getName()) + .replace("%guild_member_count%", String.valueOf(event.getGuild().getMemberCount())); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join_image").subscribe(joinImage -> { + if (joinImage.isPresent() && !joinImage.get().getStringValue().isBlank()) { + try { + wmb.addFile("welcome.png", ImageCreationUtility.createJoinImage(event.getUser(), joinImage.get().getStringValue(), + messageContent.replace("%user_mention%", event.getMember().getUser().getName()))); + } catch (IOException e) { + wmb.setContent(messageContent); + log.error("Error while creating join image!", e); + } + } else { + wmb.setContent(messageContent.replace("%user_mention%", event.getMember().getUser().getAsMention())); + } - wmb.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wmb.setUsername("Welcome!"); + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + if (webhook.isEmpty()) return; - String messageContent = SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join") - .getStringValue() - .replace("%user_name%", event.getMember().getUser().getName()) - .replace("%guild_name%", event.getGuild().getName()) - .replace("%guild_member_count%", String.valueOf(event.getGuild().getMemberCount())); - if (!SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join_image").getStringValue().isBlank()) { - try { - messageContent = messageContent.replace("%user_mention%", event.getMember().getUser().getName()); - wmb.addFile("welcome.png", ImageCreationUtility.createJoinImage(event.getUser(), - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join_image").getStringValue(), messageContent)); - } catch (IOException e) { - wmb.setContent(messageContent); - log.error("Error while creating join image!", e); - } - } else { - messageContent = messageContent.replace("%user_mention%", event.getMember().getUser().getAsMention()); - wmb.setContent(messageContent); + WebhookUtil.sendWebhook(wmb.build(), webhook.get(), WebhookUtil.WebhookTyp.WELCOME); + }); + }); + } + }); } - - WebhookUtil.sendWebhook(wmb.build(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong())); }); } @@ -171,28 +182,28 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { super.onGuildMemberRemove(event); - ThreadUtil.createThread(x -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())); - if (channelStats != null) { - if (channelStats.getMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getMemberStatsChannelId()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())).subscribe(channelStats -> { + if (channelStats.isPresent()) { + ChannelStats channelStatsEntity = channelStats.get(); + if (channelStatsEntity.getMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.overallMembers") + ": " + event.getGuild().getMemberCount()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.overallMembers").block() + ": " + event.getGuild().getMemberCount()).queue(); } } event.getGuild().loadMembers().onSuccess(members -> { - if (channelStats.getRealMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getRealMemberStatsChannelId()); + if (channelStatsEntity.getRealMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getRealMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.realMembers") + ": " + members.stream().filter(member -> !member.getUser().isBot()).count()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.realMembers").block() + ": " + members.stream().filter(member -> !member.getUser().isBot()).count()).queue(); } } - if (channelStats.getBotMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getBotMemberStatsChannelId()); + if (channelStatsEntity.getBotMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getBotMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.botMembers") + ": " + members.stream().filter(member -> member.getUser().isBot()).count()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.botMembers").block() + ": " + members.stream().filter(member -> member.getUser().isBot()).count()).queue(); } } }); @@ -200,64 +211,38 @@ public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { }); if (BotConfig.isModuleActive("tickets")) { - Tickets tickets = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (tickets != null) { - Category category = event.getGuild().getCategoryById(tickets.getTicketCategory()); - - if (category != null) { - List channels = category.getTextChannels().stream().filter(c -> c.getTopic() != null && c.getTopic().equalsIgnoreCase(event.getUser().getId())).toList(); - if (!channels.isEmpty()) { - TextChannel channel = channels.get(0); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(BotConfig.getBotName()) - .append(" Ticket transcript") - .append(" ") - .append(ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG))) - .append("\n") - .append("\n"); - - - for (Message message : channel.getIterableHistory().reverse()) { - stringBuilder - .append("[") - .append(message.getTimeCreated().toZonedDateTime().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))) - .append("]") - .append(" ") - .append(message.getAuthor().getAsTag()) - .append(" ") - .append("->") - .append(" ") - .append(message.getContentRaw()); - - if (!message.getAttachments().isEmpty()) { - for (Message.Attachment attachment : message.getAttachments()) { - stringBuilder.append("\n").append(attachment.getUrl()); - } - } - - stringBuilder.append("\n"); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { + if (tickets.isPresent()) { + Tickets ticketsEntity = tickets.get(); + Category category = event.getGuild().getCategoryById(ticketsEntity.getTicketCategory()); + + if (category != null) { + List channels = category.getTextChannels().stream().filter(c -> c.getTopic() != null && c.getTopic().equalsIgnoreCase(event.getUser().getId())).toList(); + if (!channels.isEmpty()) { + TextChannel channel = channels.get(0); + + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + webhookMessageBuilder.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName() + "-Tickets"); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + ticketsEntity.getTicketCount() + "!"); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + webhookEmbedBuilder.setColor(BotConfig.getMainColor().getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + webhookMessageBuilder.addFile(event.getGuild().getId() + "_" + ticketsEntity.getTicketCount() + "_transcript.html", + TranscriptUtil.generateTranscript(event.getJDA(), channel.getIterableHistory().reverse().stream().toList(), + channel.getTimeCreated().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " "), + ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " ")).getBytes(StandardCharsets.UTF_8)); + + WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), ticketsEntity.getLogChannelId(), ticketsEntity.getLogChannelWebhookToken(), WebhookUtil.WebhookTyp.TICKET); + channel.delete().queue(); } - - stringBuilder.append("\n").append("Closed by").append(" ").append(event.getUser().getEffectiveName()); - - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - webhookMessageBuilder.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName() + "-Tickets"); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + tickets.getTicketCount() + "!"); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); - - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhookMessageBuilder.addFile(tickets.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); - - WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), tickets.getLogChannelId(), tickets.getLogChannelWebhookToken(), false); - channel.delete().queue(); } } - } + }); } } @@ -285,30 +270,7 @@ public void onGuildVoiceUpdate(@Nonnull GuildVoiceUpdateEvent event) { } if (BotConfig.isModuleActive("temporalvoice")) { - TemporalVoicechannel temporalVoicechannel = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getId())); - - if (temporalVoicechannel != null) { - VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(event.getChannelJoined().getId()); - - if (voiceChannel == null) - return; - - if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { - return; - } - - if (voiceChannel.getParentCategory() != null) { - String preName = LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", "SPLIT"); - preName = preName.split("SPLIT")[0]; - - String finalPreName = preName; - voiceChannel.getParentCategory().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", - event.getGuild().getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1)).queue(channel -> { - event.getGuild().moveVoiceMember(event.getMember(), channel).queue(); - ArrayUtil.temporalVoicechannel.add(channel.getId()); - }); - } - } + checkCreationChannel(event.getGuild(), event.getMember(), event.getChannelJoined().getIdLong()); } } else if (event.getChannelJoined() == null) { doVoiceXPStuff(event.getMember()); @@ -334,32 +296,40 @@ public void onGuildVoiceUpdate(@Nonnull GuildVoiceUpdateEvent event) { if (BotConfig.isModuleActive("temporalvoice")) { if (checkChannel(event.getChannelLeft(), event.getJDA())) return; - TemporalVoicechannel temporalVoicechannel = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getId())); - - if (temporalVoicechannel != null) { - VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(event.getChannelJoined().getId()); + checkCreationChannel(event.getGuild(), event.getMember(), event.getChannelJoined().getIdLong()); + } + } + } - if (voiceChannel == null) - return; + private void checkCreationChannel(Guild guild, Member member, long channelId) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", guild.getId())) + .subscribe(temporalVoicechannel -> { + if (temporalVoicechannel.isPresent()) { + TemporalVoicechannel temporalVoicechannelEntity = temporalVoicechannel.get(); + VoiceChannel voiceChannel = guild.getVoiceChannelById(channelId); - if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { - return; - } + if (voiceChannel == null) + return; - if (voiceChannel.getParentCategory() != null) { - String preName = LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", "SPLIT"); - preName = preName.split("SPLIT")[0]; + if (temporalVoicechannelEntity.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { + return; + } - String finalPreName = preName; - voiceChannel.getParentCategory().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", - event.getGuild().getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1)).queue(channel -> { - event.getGuild().moveVoiceMember(event.getMember(), channel).queue(); - ArrayUtil.temporalVoicechannel.add(channel.getId()); - }); + if (voiceChannel.getParentCategory() != null) { + LanguageService.getByGuild(guild, "label.temporalVoiceName", "SPLIT").subscribe(preName -> { + preName = preName.split("SPLIT")[0]; + String finalPreName = preName; + LanguageService.getByGuild(guild, "label.temporalVoiceName", + guild.getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1) + .subscribe(name -> voiceChannel.getParentCategory().createVoiceChannel(name) + .queue(channel -> { + guild.moveVoiceMember(member, channel).queue(); + ArrayUtil.temporalVoicechannel.add(channel.getId()); + })); + }); + } } - } - } - } + }); } private boolean checkChannel(AudioChannelUnion channel, JDA instance) { @@ -413,6 +383,7 @@ public void onGenericGuildVoice(@NotNull GenericGuildVoiceEvent event) { /** * Method used to do all the calculations for the Voice XP. + * * @param member the Member that should be checked. */ public void doVoiceXPStuff(Member member) { @@ -421,12 +392,10 @@ public void doVoiceXPStuff(Member member) { int addXP = IntStream.rangeClosed(1, min).map(i -> RandomUtils.random.nextInt(5, 11)).sum(); - // TODO:: await database future system. - ThreadUtil.createThread(x -> { - VoiceUserLevel newUserLevel = SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(member.getGuild().getIdLong(), member.getIdLong()); - newUserLevel.addExperience(addXP); + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(member.getGuild().getIdLong(), member.getIdLong()).subscribe(x -> { + x.addExperience(addXP); - SQLSession.getSqlConnector().getSqlWorker().addVoiceLevelData(member.getGuild().getIdLong(), newUserLevel); + SQLSession.getSqlConnector().getSqlWorker().addVoiceLevelData(member.getGuild().getIdLong(), x); GuildUtil.handleVoiceLevelReward(member.getGuild(), member); }); @@ -458,9 +427,11 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { super.onMessageReceived(event); if (event.isFromType(ChannelType.NEWS) && - BotConfig.isModuleActive("autopublish") && - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "configuration_autopublish").getBooleanValue()) { - event.getMessage().crosspost().queue(c -> c.addReaction(Emoji.fromUnicode("U+1F4E2")).queue()); + BotConfig.isModuleActive("autopublish")) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "configuration_autopublish").subscribe(x -> { + if (x.isPresent() && x.get().getBooleanValue()) + event.getMessage().crosspost().queue(c -> c.addReaction(Emoji.fromUnicode("U+1F4E2")).queue()); + }); } if (event.isFromGuild() && (event.isFromType(ChannelType.TEXT) || event.isFromType(ChannelType.VOICE)) && event.getMember() != null) { @@ -475,19 +446,28 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { ArrayUtil.messageIDwithUser.put(event.getMessageId(), event.getAuthor()); } - // TODO:: start working with futureComplete instead of creating a thread here. - ThreadUtil.createThread(x -> { + ModerationUtil.shouldModerate(event.getGuild().getIdLong()).publishOn(Schedulers.boundedElastic()).map(x -> { + + if (BotConfig.isDebug()) + log.info("Message received from {} in {} with content: {}", event.getAuthor().getGlobalName(), event.getChannel().getName(), event.getMessage().getContentRaw()); + + boolean moderated = false; + if (x) { + moderated = Boolean.TRUE.equals(ModerationUtil.checkMessage(event.getGuild().getIdLong(), event.getMessage().getContentRaw()).block()); + + if (moderated) { + Main.getInstance().getCommandManager().deleteMessageWithoutException(event.getMessage(), null); - if (ModerationUtil.shouldModerate(event.getGuild().getIdLong())) { - if (ModerationUtil.checkMessage(event.getGuild().getIdLong(), event.getMessage().getContentRaw())) { - Main.getInstance().getCommandManager().deleteMessage(event.getMessage(), null); Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.blacklisted"), event.getChannel(), null); - return; } } - if (!Main.getInstance().getCommandManager().perform(event.getMember(), event.getGuild(), event.getMessage().getContentRaw(), event.getMessage(), event.getGuildChannel(), null)) { + if (BotConfig.isDebug()) + log.info("Message was moderated: {}", moderated); + return moderated; + }).flatMap(aBoolean -> handleCommand(aBoolean, event)).doOnNext(handled -> { + if (!handled) { if (!event.getMessage().getMentions().getUsers().isEmpty() && event.getMessage().getMentions().getUsers().contains(event.getJDA().getSelfUser())) { if (event.getMessage().getMessageReference() != null) return; @@ -505,28 +485,39 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { if (BotConfig.isModuleActive("level")) { if (!ArrayUtil.timeout.contains(event.getMember())) { - ChatUserLevel userLevel = SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(event.getGuild().getIdLong(), event.getMember().getIdLong()); - - if (userLevel.addExperience(RandomUtils.random.nextInt(15, 26)) && SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "level_message").getBooleanValue()) { - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), - "message.levelUp", userLevel.getLevel(), LanguageService.getByGuild(event.getGuild(), "label.chat") - , event.getMember().getAsMention()), event.getChannel()); - } + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(event.getGuild().getIdLong(), event.getMember().getIdLong()).subscribe(userLevel -> { + if (userLevel.addExperience(RandomUtils.random.nextInt(15, 26))) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "level_message").subscribe(z -> { + if (z.isPresent() && z.get().getBooleanValue()) { + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), + "message.levelUp", userLevel.getLevel(), LanguageService.getByGuild(event.getGuild(), "label.chat") + , event.getMember().getAsMention()), event.getChannel()); + } + }); + } - SQLSession.getSqlConnector().getSqlWorker().addChatLevelData(event.getGuild().getIdLong(), userLevel); + SQLSession.getSqlConnector().getSqlWorker().addChatLevelData(event.getGuild().getIdLong(), userLevel); - ArrayUtil.timeout.add(event.getMember()); + ArrayUtil.timeout.add(event.getMember()); - ThreadUtil.createThread(y -> ArrayUtil.timeout.remove(event.getMember()), Duration.ofSeconds(30), false, false); + ThreadUtil.createThread(y -> ArrayUtil.timeout.remove(event.getMember()), Duration.ofSeconds(30), false, false); + }); } GuildUtil.handleChatLevelReward(event.getGuild(), event.getMember()); } + } else { + Main.getInstance().getCommandManager().timeoutUser(event.getAuthor()); } - }); + }).subscribe(); } } + private Mono handleCommand(boolean moderated, MessageReceivedEvent event) { + if (moderated) return Mono.just(true); + return Main.getInstance().getCommandManager().perform(event.getMember(), event.getGuild(), event.getMessage().getContentRaw(), event.getMessage(), event.getGuildChannel(), null); + } + /** * @inheritDoc */ @@ -554,56 +545,61 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) { if (message.getAuthor().getId().equalsIgnoreCase(event.getJDA().getSelfUser().getId())) { String messageContent = message.getContentRaw(); - if (messageContent.startsWith(LanguageService.getByGuild(event.getGuild(), "message.reactions.reactionNeeded", "SPLIT_HERE").split("SPLIT_HERE")[0])) { - if (event.getMember().hasPermission(Permission.ADMINISTRATOR) && message.getMessageReference() != null) { - if (message.getMentions().getRoles().isEmpty()) { - message.editMessage(LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound")).queue(); - return; - } + LanguageService.getByGuild(event.getGuild(), "message.reactions.reactionNeeded", "SPLIT_HERE").subscribe(translation -> { + if (messageContent.startsWith(translation.split("SPLIT_HERE")[0])) { + if (event.getMember().hasPermission(Permission.ADMINISTRATOR) && message.getMessageReference() != null) { + if (message.getMentions().getRoles().isEmpty()) { + LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound").map(message::editMessage).subscribe(MessageEditAction::queue); + return; + } - Role role = message.getMentions().getRoles().get(0); + Role role = message.getMentions().getRoles().get(0); - if (role == null) { - message.editMessage(LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound")).queue(); - return; - } + if (role == null) { + LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound").map(message::editMessage).subscribe(MessageEditAction::queue); + return; + } - ReactionRole reactionRole = new ReactionRole(event.getGuild().getIdLong(), emojiId, emojiUnion.getFormatted(), role.getIdLong(), message.getMessageReference().getMessageIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole); + ReactionRole reactionRole = new ReactionRole(event.getGuild().getIdLong(), emojiId, emojiUnion.getFormatted(), role.getIdLong(), message.getMessageReference().getMessageIdLong()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole).block(); - if (message.getMessageReference().getMessage() != null) { - message.getMessageReference().getMessage().addReaction(event.getEmoji()).queue(); - } + if (message.getMessageReference().getMessage() != null) { + message.getMessageReference().getMessage().addReaction(event.getEmoji()).queue(); + } - message.editMessage(LanguageService.getByGuild(event.getGuild(), "message.reactions.roleAssign", role.getAsMention())) - .delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); + LanguageService.getByGuild(event.getGuild(), "message.reactions.roleAssign", role.getAsMention()) + .subscribe(x -> message.editMessage(x).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue()); + } } - } + }); } else { - ReactionRole reactionRole = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", message.getIdLong())); - - if (reactionRole != null) { - Role role = event.getGuild().getRoleById(reactionRole.getId()); - - if (role != null) { - event.getGuild().addRoleToMember(event.getMember(), role).queue(); - } + SQLSession.getSqlConnector().getSqlWorker() + .getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", + Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", message.getIdLong())).subscribe(reactionRole -> { + if (reactionRole.isPresent()) { + ReactionRole reactionRoleEntity = reactionRole.get(); + Role role = event.getGuild().getRoleById(reactionRoleEntity.getId()); + + if (role != null) { + event.getGuild().addRoleToMember(event.getMember(), role).queue(); + } - boolean changes = false; + boolean changes = false; - if (reactionRole.getChannelId() == 0) { - reactionRole.setChannelId(event.getChannel().getIdLong()); - changes = true; - } + if (reactionRoleEntity.getChannelId() == 0) { + reactionRoleEntity.setChannelId(event.getChannel().getIdLong()); + changes = true; + } - if (reactionRole.getFormattedEmote().isBlank()) { - reactionRole.setFormattedEmote(emojiUnion.getFormatted()); - changes = true; - } + if (reactionRoleEntity.getFormattedEmote().isBlank()) { + reactionRoleEntity.setFormattedEmote(emojiUnion.getFormatted()); + changes = true; + } - if (changes) - SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole); - } + if (changes) + SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRoleEntity).block(); + } + }); } }); } @@ -625,17 +621,18 @@ public void onMessageReactionRemove(@NotNull MessageReactionRemoveEvent event) { emojiId = reactionCode.replace(":", "").hashCode(); } - ReactionRole reactionRole = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", - Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", event.getMessageIdLong())); - - if (reactionRole != null) { - Role role = event.getGuild().getRoleById(reactionRole.getId()); + Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", event.getMessageIdLong())).subscribe(reactionRole -> { + if (reactionRole.isPresent()) { + ReactionRole reactionRoleEntity = reactionRole.get(); + Role role = event.getGuild().getRoleById(reactionRoleEntity.getId()); - if (role != null) { - event.getGuild().removeRoleFromMember(event.getMember(), role).queue(); + if (role != null) { + event.getGuild().removeRoleFromMember(event.getMember(), role).queue(); + } } - } + }); } /** @@ -650,6 +647,10 @@ public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent even event.deferReply(true).queue(); - Main.getInstance().getCommandManager().perform(Objects.requireNonNull(event.getMember()), event.getGuild(), null, null, event.getGuildChannel(), event); + Main.getInstance().getCommandManager().perform(Objects.requireNonNull(event.getMember()), event.getGuild(), null, null, event.getGuildChannel(), event).subscribe(x -> { + if (x != null) { + Main.getInstance().getCommandManager().timeoutUser(event.getUser()); + } + }); } } diff --git a/src/main/java/de/presti/ree6/language/Language.java b/src/main/java/de/presti/ree6/language/Language.java index b8b904258..4d5a6c7f3 100644 --- a/src/main/java/de/presti/ree6/language/Language.java +++ b/src/main/java/de/presti/ree6/language/Language.java @@ -4,6 +4,7 @@ import io.sentry.SentryEvent; import io.sentry.SentryLevel; import io.sentry.protocol.Message; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.interactions.DiscordLocale; import org.jetbrains.annotations.NotNull; @@ -21,26 +22,31 @@ public class Language { /** * The Locale-Tag of the Language. */ + @Getter private final String locale; /** * The Name of the Language. */ + @Getter private final String name; /** * The Author of the Language-File. */ + @Getter private final String author; /** * The corresponding Ree6 Version. */ + @Getter private final String version; /** * The DiscordLocale of the Language. */ + @Getter private final DiscordLocale discordLocale; /** @@ -84,46 +90,6 @@ public Language(@NotNull String locale, @NotNull String name, @NotNull String au discordLocale = DiscordLocale.from(locale); } - /** - * Called to get the Locale-Tag of the Language. - * @return The Locale-Tag. - */ - public String getLocale() { - return locale; - } - - /** - * Called to get the Name of the Language. - * @return The Name. - */ - public String getName() { - return name; - } - - /** - * Called to get the Author of the Language-File. - * @return The Author. - */ - public String getAuthor() { - return author; - } - - /** - * Called to get the corresponding Ree6 Version. - * @return The Version. - */ - public String getVersion() { - return version; - } - - /** - * Called to get the DiscordLocale of the Language. - * @return The DiscordLocale. - */ - public DiscordLocale getDiscordLocale() { - return discordLocale; - } - /** * Called to get the entry of the Language. * @param key The key of the entry. diff --git a/src/main/java/de/presti/ree6/language/LanguageService.java b/src/main/java/de/presti/ree6/language/LanguageService.java index 6ce03ecc0..3d792e3a2 100644 --- a/src/main/java/de/presti/ree6/language/LanguageService.java +++ b/src/main/java/de/presti/ree6/language/LanguageService.java @@ -3,6 +3,7 @@ import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.utils.external.RequestUtility; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.entities.Guild; @@ -14,6 +15,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.simpleyaml.configuration.file.YamlConfiguration; +import reactor.core.publisher.Mono; import java.io.File; import java.io.IOException; @@ -25,6 +27,7 @@ import java.util.HashMap; import java.util.Objects; import java.util.Set; +import java.util.concurrent.CompletableFuture; /** * Utility used to work with Languages. @@ -33,7 +36,7 @@ public class LanguageService { /** - * A Hashmap containing the locale as key and the YamlConfiguration as value. + * A Hashmap containing the locale as a key and the YamlConfiguration as value. */ public static final HashMap languageResources = new HashMap<>(); @@ -76,7 +79,7 @@ public static void downloadLanguages() { } try { - RequestUtility.requestJson(RequestUtility.Request.builder().url("https://api.github.com/repos/Ree6-Applications/Ree6/contents/languages").build()).getAsJsonArray().forEach(jsonElement -> { + RequestUtility.requestJson(RequestUtility.Request.builder().url("https://api.github.com/repos/Ree6-Applications/Language/contents/languages").build()).getAsJsonArray().forEach(jsonElement -> { String language = jsonElement.getAsJsonObject().get("name").getAsString().replace(".yml", ""); String download = jsonElement.getAsJsonObject().get("download_url").getAsString(); @@ -163,7 +166,7 @@ public static void downloadLanguages() { * @param parameter the parameter to replace. * @return the String. */ - public static @NotNull String getByEvent(@NotNull CommandEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getByEvent(@NotNull CommandEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { if (commandEvent.isSlashCommand()) { return getByInteraction(commandEvent.getInteractionHook().getInteraction(), key, parameter); } else { @@ -179,7 +182,7 @@ public static void downloadLanguages() { * @param parameter the parameter to replace. * @return the String. */ - public static @NotNull String getByEvent(@NotNull GenericGuildEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getByEvent(@NotNull GenericGuildEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { return getByGuild(commandEvent.getGuild(), key, parameter); } @@ -192,8 +195,8 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByGuildOrInteractionHook(Guild guild, InteractionHook interaction, @NotNull String key, @Nullable Object... parameter) { - return getByGuildOrInteraction(guild, interaction != null ? interaction.getInteraction() : null, key, parameter); + public static @NotNull Mono getByGuildOrInteractionHook(Guild guild, InteractionHook interaction, @NotNull String key, @Nullable Object... parameter) { + return getByGuildOrInteraction(guild, interaction != null ? interaction.getInteraction() : null, key, parameter); } @@ -206,7 +209,7 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByGuildOrInteraction(Guild guild, Interaction interaction, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getByGuildOrInteraction(Guild guild, Interaction interaction, @NotNull String key, @Nullable Object... parameter) { if (interaction != null) { return getByInteraction(interaction, key, parameter); } else { @@ -222,8 +225,8 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByGuild(Guild guild, @NotNull String key, @Nullable Object... parameter) { - return getByGuild(guild != null ? guild.getIdLong() : -1, key, parameter); + public static @NotNull Mono getByGuild(Guild guild, @NotNull String key, @Nullable Object... parameter) { + return getByGuild(guild != null && !guild.isDetached() ? guild.getIdLong() : -1, key, parameter); } /** @@ -234,20 +237,16 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByGuild(long guildId, @NotNull String key, @Nullable Object... parameter) { - String resource; + public static @NotNull Mono getByGuild(long guildId, @NotNull String key, @Nullable Object... parameter) { if (guildId == -1) { - resource = getDefault(key, parameter); - } else { - resource = getByLocale(SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "configuration_language").getStringValue(), key, parameter); - } - - if (guildId != -1 && resource.contains("{guild_prefix}")) { - resource = resource - .replace("{guild_prefix}", SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "chatprefix").getStringValue()); + return getDefault(key, parameter); } - return resource; + return SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "configuration_language") + .mapNotNull(setting -> getByLocale(setting.get().getStringValue(), key, parameter).block()) + .mapNotNull(resource -> SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "chatprefix"). + map(prefix -> resource.replace("{guild_prefix}", prefix.orElse(new Setting(-1, "chatprefix", "chatprefix", BotConfig.getDefaultPrefix())) + .getStringValue())).block()); } /** @@ -258,14 +257,20 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByInteraction(Interaction interaction, @NotNull String key, @Nullable Object... parameter) { - String resource = getByLocale(interaction.getUserLocale(), key, parameter); + public static @NotNull Mono getByInteraction(Interaction interaction, @NotNull String key, @Nullable Object... parameter) { + if (!interaction.isFromGuild()) { + return getByLocale(interaction.getUserLocale(), key, parameter); + } - if (interaction.getGuild() != null && resource.contains("{guild_prefix}")) - resource = resource - .replace("{guild_prefix}", SQLSession.getSqlConnector().getSqlWorker().getSetting(interaction.getGuild().getIdLong(), "chatprefix").getStringValue()); + return getByLocale(interaction.getUserLocale(), key, parameter).mapNotNull(resource -> { + if (resource.contains("{guild_prefix}")) { + return SQLSession.getSqlConnector().getSqlWorker().getSetting(interaction.getGuild().getIdLong(), "chatprefix") + .map(prefix -> resource.replace("{guild_prefix}", prefix.orElse(new Setting(-1, "chatprefix", "chatprefix", BotConfig.getDefaultPrefix())) + .getStringValue())).block(); + } - return resource; + return resource; + }); } /** @@ -275,7 +280,7 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getDefault(@NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getDefault(@NotNull String key, @Nullable Object... parameter) { return getByLocale(DiscordLocale.from(BotConfig.getDefaultLanguage()), key, parameter); } @@ -287,7 +292,7 @@ public static void downloadLanguages() { * @param parameters The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByLocale(@NotNull String locale, @NotNull String key, @Nullable Object... parameters) { + public static @NotNull Mono getByLocale(@NotNull String locale, @NotNull String key, @Nullable Object... parameters) { return getByLocale(DiscordLocale.from(locale), key, parameters); } @@ -299,13 +304,41 @@ public static void downloadLanguages() { * @param parameters The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByLocale(@NotNull DiscordLocale discordLocale, @NotNull String key, @Nullable Object... parameters) { - if (discordLocale == DiscordLocale.UNKNOWN) return getDefault(key, parameters); + public static @NotNull Mono getByLocale(@NotNull DiscordLocale discordLocale, @NotNull String key, @Nullable Object... parameters) { + return Mono.fromFuture(CompletableFuture.supplyAsync(() -> { + if (discordLocale == DiscordLocale.UNKNOWN) return getDefault(key, parameters).block(); + + Language language = languageResources.containsKey(discordLocale) ? languageResources.get(discordLocale) : + languageResources.get(DiscordLocale.from(BotConfig.getDefaultLanguage())); + + return language != null ? language.getResource(key, parameters) : "Missing language resource!"; + })); + } + + /** + * Check if given Locale has a translation for the key + * + * @param discordLocale The locale of the Language file. + * @param key The key of the String. + * @return true, if the key is translated. + */ + public static @NotNull Mono hasTranslation(@NotNull DiscordLocale discordLocale, @NotNull String key) { + return Mono.fromFuture(CompletableFuture.supplyAsync(() -> { + if (discordLocale == DiscordLocale.UNKNOWN) return false; - Language language = languageResources.containsKey(discordLocale) ? languageResources.get(discordLocale) : - languageResources.get(DiscordLocale.from(BotConfig.getDefaultLanguage())); + return languageResources.containsKey(discordLocale) && languageResources.get(discordLocale).resources.containsKey(key); + })); + } - return language != null ? language.getResource(key, parameters) : "Missing language resource!"; + /** + * Check if the default Locale has a translation for the key + * + * @param key The key of the String. + * @return true, if the key is translated. + */ + public static @NotNull Mono hasDefaultTranslation(@NotNull String key) { + DiscordLocale discordLocale = DiscordLocale.from(BotConfig.getDefaultLanguage()); + return hasTranslation(discordLocale, key); } /** diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 65a06e21a..bb65bb420 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -5,9 +5,7 @@ import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; import com.github.twitch4j.pubsub.PubSubSubscription; import com.google.gson.JsonObject; -import de.presti.ree6.actions.streamtools.container.StreamActionContainerCreator; -import de.presti.ree6.addons.AddonLoader; -import de.presti.ree6.addons.AddonManager; +import de.presti.ree6.addons.ReePluginManager; import de.presti.ree6.audio.music.MusicWorker; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; @@ -15,13 +13,16 @@ import de.presti.ree6.bot.version.BotState; import de.presti.ree6.bot.version.BotVersion; import de.presti.ree6.commands.CommandManager; +import de.presti.ree6.commands.exceptions.CommandInitializerException; +import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.events.*; -import de.presti.ree6.game.core.GameManager; -import de.presti.ree6.game.impl.musicquiz.util.MusicQuizUtil; import de.presti.ree6.language.LanguageService; -import de.presti.ree6.logger.LoggerQueue; +import de.presti.ree6.module.actions.streamtools.container.StreamActionContainerCreator; +import de.presti.ree6.module.game.core.GameManager; +import de.presti.ree6.module.game.impl.musicquiz.util.MusicQuizUtil; import de.presti.ree6.module.giveaway.GiveawayManager; import de.presti.ree6.module.invite.InviteContainerManager; +import de.presti.ree6.module.logger.LoggerQueue; import de.presti.ree6.sql.DatabaseTyp; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Giveaway; @@ -29,14 +30,16 @@ import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.sql.entities.TwitchIntegration; import de.presti.ree6.sql.entities.stats.ChannelStats; -import de.presti.ree6.sql.entities.stats.Statistics; import de.presti.ree6.sql.util.SQLConfig; import de.presti.ree6.sql.util.SettingsManager; import de.presti.ree6.utils.apis.ChatGPTAPI; import de.presti.ree6.utils.apis.Notifier; import de.presti.ree6.utils.apis.SpotifyAPIHandler; -import de.presti.ree6.utils.data.*; +import de.presti.ree6.utils.config.Config; +import de.presti.ree6.utils.data.ArrayUtil; import de.presti.ree6.utils.external.RequestUtility; +import de.presti.ree6.utils.oauth.CustomOAuth2Credential; +import de.presti.ree6.utils.oauth.CustomOAuth2Util; import de.presti.ree6.utils.others.ThreadUtil; import io.sentry.Sentry; import lavalink.client.io.jda.JdaLavalink; @@ -52,6 +55,7 @@ import net.dv8tion.jda.api.entities.channel.unions.GuildMessageChannelUnion; import net.dv8tion.jda.api.entities.emoji.Emoji; import net.dv8tion.jda.api.utils.messages.MessageEditBuilder; +import org.pf4j.PluginManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -98,9 +102,9 @@ public class Main { CommandManager commandManager; /** - * Addon Manager, used to manage the Addons. + * Instance of the PluginManager, used to manage the Plugins. */ - AddonManager addonManager; + PluginManager pluginManager; /** * Instance of the GiveawayManager, used to manage the Giveaways. @@ -344,71 +348,15 @@ public static void main(String[] args) { if (BotConfig.isModuleActive("notifier")) { ThreadUtil.createThread(x -> { log.info("Loading Notifier data."); - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), "FROM ChannelStats", null); - - try { - // Register all Twitch Channels. - getInstance().getNotifier().registerTwitchChannel(SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames()); - getInstance().getNotifier().registerTwitchChannel(channelStats.stream().map(ChannelStats::getTwitchFollowerChannelUsername).filter(Objects::nonNull).toList()); - - // Register the Event-handler. - getInstance().getNotifier().registerTwitchEventHandler(); - } catch (Exception exception) { - log.error("Error while loading Twitch data: " + exception.getMessage()); - Sentry.captureException(exception); - } - - try { - // Register all Twitter Users. - getInstance().getNotifier().registerTwitterUser(SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames()); - getInstance().getNotifier().registerTwitterUser(channelStats.stream().map(ChannelStats::getTwitterFollowerChannelUsername).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading Twitter data: " + exception.getMessage()); - Sentry.captureException(exception); - } - - try { - // Register all YouTube channels. - getInstance().getNotifier().registerYouTubeChannel(SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels()); - getInstance().getNotifier().registerYouTubeChannel(channelStats.stream().map(ChannelStats::getYoutubeSubscribersChannelUsername).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading YouTube data: " + exception.getMessage()); - Sentry.captureException(exception); - } - - try { - // Register all Reddit Subreddits. - getInstance().getNotifier().registerSubreddit(SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits()); - getInstance().getNotifier().registerSubreddit(channelStats.stream().map(ChannelStats::getSubredditMemberChannelSubredditName).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading Reddit data: " + exception.getMessage()); - Sentry.captureException(exception); - } - - try { - // Register all Instagram Users. - getInstance().getNotifier().registerInstagramUser(SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers()); - getInstance().getNotifier().registerInstagramUser(channelStats.stream().map(ChannelStats::getInstagramFollowerChannelUsername).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading Instagram data: " + exception.getMessage()); - Sentry.captureException(exception); - } - - try { - // Register all TikTok Users. - getInstance().getNotifier().registerTikTokUser(SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames().stream().map(Long::parseLong).toList()); - } catch (Exception exception) { - log.error("Error while loading TikTok data: " + exception.getMessage()); - Sentry.captureException(exception); - } - - try { - // Register all RSS-Feeds. - getInstance().getNotifier().registerRSS(SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls()); - } catch (Exception exception) { - log.error("Error while loading RSS data: " + exception.getMessage()); - Sentry.captureException(exception); - } + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), "FROM ChannelStats", null).subscribe(channelStats -> { + getInstance().getNotifier().getSpotifySonic().load(channelStats); + getInstance().getNotifier().getYouTubeSonic().load(channelStats); + getInstance().getNotifier().getTwitchSonic().load(channelStats); + getInstance().getNotifier().getInstagramSonic().load(channelStats); + getInstance().getNotifier().getTwitterSonic().load(channelStats); + getInstance().getNotifier().getTikTokSonic().load(channelStats); + getInstance().getNotifier().getRssSonic().load(channelStats); + }); }, t -> Sentry.captureException(t.getCause())); } @@ -418,16 +366,27 @@ public static void main(String[] args) { // Set the start Time for stats. BotWorker.setStartTime(System.currentTimeMillis()); - log.info("Loading AddonManager"); - // Initialize the Addon-Manager. - getInstance().setAddonManager(new AddonManager()); + log.info("Loading PluginManager"); + // Initialize the Plugin-Manager. + getInstance().setPluginManager(new ReePluginManager()); if (BotConfig.isModuleActive("addons")) { - // Initialize the Addon-Loader. - AddonLoader.loadAllAddons(); + log.info("Loading all Plugins."); + getInstance().getPluginManager().loadPlugins(); - // Start all Addons. - getInstance().getAddonManager().startAddons(); + log.info("Starting all Plugins."); + getInstance().getPluginManager().startPlugins(); + + log.info("Registering all Commands of plugins."); + List commands = getInstance().getPluginManager().getExtensions(ICommand.class); + log.info("Found {} commands in all plugins.", commands.size()); + commands.forEach(command -> { + try { + getInstance().getCommandManager().addCommand(command); + } catch (CommandInitializerException e) { + log.warn("Failed to initialize command: {}", command.getClass().getSimpleName(), e); + } + }); } // Create checker Thread. @@ -439,10 +398,10 @@ public static void main(String[] args) { log.info("Any previous messages about \"Error executing DDL\" can be most likely ignored."); log.info("Initialization finished."); log.info("Bot is ready to use."); - log.info("You are running on: v" + BotWorker.getBuild()); - log.info("You are running on: " + BotWorker.getShardManager().getShardsTotal() + " Shards."); - log.info("You are running on: " + BotWorker.getShardManager().getGuilds().size() + " Guilds."); - log.info("You are running on: " + BotWorker.getShardManager().getUsers().size() + " Users."); + log.info("You are running on: v{}", BotWorker.getBuild()); + log.info("You are running on: {} Shards.", BotWorker.getShardManager().getShardsTotal()); + log.info("You are running on: {} Guilds.", BotWorker.getShardManager().getGuilds().size()); + log.info("You are running on: {} Users.", BotWorker.getShardManager().getUsers().size()); log.info("Have fun!"); } @@ -493,7 +452,7 @@ private void shutdown() { if (BotConfig.isModuleActive("addons")) { // Shutdown every Addon. log.info("[Main] Disabling every Addon!"); - getAddonManager().stopAddons(); + getPluginManager().unloadPlugins(); log.info("[Main] Every Addon has been disabled!"); } @@ -586,30 +545,33 @@ public void createCheckerThread() { log.info("[Stats] "); LocalDate yesterday = LocalDate.now().minusDays(1); - Statistics statistics = SQLSession.getSqlConnector().getSqlWorker().getStatistics(yesterday.getDayOfMonth(), yesterday.getMonthValue(), yesterday.getYear()); - JsonObject jsonObject = statistics != null ? statistics.getStatsObject() : new JsonObject(); - JsonObject guildStats = statistics != null && jsonObject.has("guild") ? jsonObject.getAsJsonObject("guild") : new JsonObject(); - - guildStats.addProperty("amount", guildSize); - guildStats.addProperty("users", userSize); + SQLSession.getSqlConnector().getSqlWorker().getStatistics(yesterday.getDayOfMonth(), yesterday.getMonthValue(), yesterday.getYear()).subscribe(statistics -> { + JsonObject jsonObject = statistics.isPresent() ? statistics.get().getStatsObject() : new JsonObject(); + JsonObject guildStats = statistics.isPresent() && jsonObject.has("guild") ? jsonObject.getAsJsonObject("guild") : new JsonObject(); - jsonObject.add("guild", guildStats); + guildStats.addProperty("amount", guildSize); + guildStats.addProperty("users", userSize); - SQLSession.getSqlConnector().getSqlWorker().updateStatistic(jsonObject); + jsonObject.add("guild", guildStats); - Calendar currentCalendar = Calendar.getInstance(); + SQLSession.getSqlConnector().getSqlWorker().updateStatistic(jsonObject); + }); SQLSession.getSqlConnector().getSqlWorker() - .getBirthdays().stream().filter(birthday -> { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(birthday.getBirthdate()); - return calendar.get(Calendar.MONTH) == currentCalendar.get(Calendar.MONTH) && - calendar.get(Calendar.DAY_OF_MONTH) == currentCalendar.get(Calendar.DAY_OF_MONTH); - }).forEach(birthday -> { - TextChannel textChannel = BotWorker.getShardManager().getTextChannelById(birthday.getChannelId()); - - if (textChannel != null && textChannel.canTalk()) - textChannel.sendMessage(LanguageService.getByGuild(textChannel.getGuild(), "message.birthday.wish", birthday.getUserId())).queue(); + .getBirthdays().subscribe(birthdayWishes -> { + Calendar currentCalendar = Calendar.getInstance(); + + birthdayWishes.stream().filter(birthday -> { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(birthday.getBirthdate()); + return calendar.get(Calendar.MONTH) == currentCalendar.get(Calendar.MONTH) && + calendar.get(Calendar.DAY_OF_MONTH) == currentCalendar.get(Calendar.DAY_OF_MONTH); + }).forEach(birthday -> { + TextChannel textChannel = BotWorker.getShardManager().getTextChannelById(birthday.getChannelId()); + + if (textChannel != null && textChannel.canTalk()) + textChannel.sendMessage(LanguageService.getByGuild(textChannel.getGuild(), "message.birthday.wish", birthday.getUserId()).block()).queue(); + }); }); lastDay = new SimpleDateFormat("dd").format(new Date()); @@ -641,47 +603,49 @@ public void createCheckerThread() { //region Schedules Message sending. try { - for (ScheduledMessage scheduledMessage : SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ScheduledMessage(), "FROM ScheduledMessage", null)) { - if (!scheduledMessage.isRepeated()) { - if (scheduledMessage.getLastExecute() == null) { - if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getCreated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { - - WebhookUtil.sendWebhook(new WebhookMessageBuilder() - .setUsername(BotConfig.getBotName() + "-Scheduler") - .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) - .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); - - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ScheduledMessage(), "FROM ScheduledMessage", null).subscribe(messages -> { + for (ScheduledMessage scheduledMessage : messages) { + if (!scheduledMessage.isRepeated()) { + if (scheduledMessage.getLastExecute() == null) { + if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getCreated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { + + WebhookUtil.sendWebhook(new WebhookMessageBuilder() + .setUsername(BotConfig.getBotName() + "-Scheduler") + .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) + .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook(), WebhookUtil.WebhookTyp.SCHEDULE); + + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage).block(); + } + } else { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage).block(); } } else { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); - } - } else { - if (scheduledMessage.getLastUpdated() == null) { - if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getCreated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { + if (scheduledMessage.getLastUpdated() == null) { + if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getCreated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { - WebhookUtil.sendWebhook(new WebhookMessageBuilder() - .setUsername(BotConfig.getBotName() + "-Scheduler") - .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) - .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); + WebhookUtil.sendWebhook(new WebhookMessageBuilder() + .setUsername(BotConfig.getBotName() + "-Scheduler") + .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) + .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook(), WebhookUtil.WebhookTyp.SCHEDULE); - scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage); - } - } else { - if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getLastUpdated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { + scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).block(); + } + } else { + if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getLastUpdated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { - WebhookUtil.sendWebhook(new WebhookMessageBuilder() - .setUsername(BotConfig.getBotName() + "-Scheduler") - .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) - .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); + WebhookUtil.sendWebhook(new WebhookMessageBuilder() + .setUsername(BotConfig.getBotName() + "-Scheduler") + .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) + .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook(), WebhookUtil.WebhookTyp.SCHEDULE); - scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage); + scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).block(); + } } } } - } + }); } catch (Exception exception) { log.error("Failed to run scheduled Messages.", exception); Sentry.captureException(exception); @@ -733,13 +697,13 @@ public void createCheckerThread() { MessageEditBuilder messageEditBuilder = MessageEditBuilder.fromMessage(message); reaction.retrieveUsers().mapToResult().onErrorMap(throwable -> { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.error")); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.error").block()); message.editMessage(messageEditBuilder.build()).queue(); toDelete.add(giveaway); return null; }).queue(users -> { if (users == null) { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less")); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less").block()); message.editMessage(messageEditBuilder.build()).queue(); return; } @@ -747,13 +711,13 @@ public void createCheckerThread() { users.onSuccess(userList -> { if (userList.isEmpty()) { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.none")); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.none").block()); message.editMessage(messageEditBuilder.build()).queue(); return; } if (userList.stream().filter(user -> !user.isBot()).count() < giveaway.getWinners()) { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less")); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less").block()); message.editMessage(messageEditBuilder.build()).queue(); return; } @@ -782,22 +746,23 @@ public void createCheckerThread() { if (BotConfig.isModuleActive("notifier")) Main.getInstance().getNotifier().getCredentialManager().load(); - for (TwitchIntegration twitchIntegrations : - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null)) { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null).subscribe(integrations -> { + for (TwitchIntegration twitchIntegrations : integrations) { - CustomOAuth2Credential credential = CustomOAuth2Util.convert(twitchIntegrations); + CustomOAuth2Credential credential = CustomOAuth2Util.convert(twitchIntegrations); - OAuth2Credential originalCredential = new OAuth2Credential("twitch", credential.getAccessToken(), credential.getRefreshToken(), credential.getUserId(), credential.getUserName(), credential.getExpiresIn(), credential.getScopes()); + OAuth2Credential originalCredential = new OAuth2Credential("twitch", credential.getAccessToken(), credential.getRefreshToken(), credential.getUserId(), credential.getUserName(), credential.getExpiresIn(), credential.getScopes()); - if (!Main.getInstance().getNotifier().getTwitchSubscription().containsKey(credential.getUserId())) { - PubSubSubscription[] subscriptions = new PubSubSubscription[3]; - subscriptions[0] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForChannelPointsRedemptionEvents(originalCredential, twitchIntegrations.getChannelId()); - subscriptions[1] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForSubscriptionEvents(originalCredential, twitchIntegrations.getChannelId()); - subscriptions[2] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForFollowingEvents(originalCredential, twitchIntegrations.getChannelId()); + if (!Main.getInstance().getNotifier().getTwitchSubscription().containsKey(credential.getUserId())) { + PubSubSubscription[] subscriptions = new PubSubSubscription[3]; + subscriptions[0] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForChannelPointsRedemptionEvents(originalCredential, twitchIntegrations.getChannelId()); + subscriptions[1] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForSubscriptionEvents(originalCredential, twitchIntegrations.getChannelId()); + subscriptions[2] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForFollowingEvents(originalCredential, twitchIntegrations.getChannelId()); - Main.getInstance().getNotifier().getTwitchSubscription().put(credential.getUserId(), subscriptions); + Main.getInstance().getNotifier().getTwitchSubscription().put(credential.getUserId(), subscriptions); + } } - } + }); } catch (Exception exception) { log.error("Failed to load Twitch Credentials.", exception); Sentry.captureException(exception); diff --git a/src/main/java/de/presti/ree6/actions/ActionEvent.java b/src/main/java/de/presti/ree6/module/actions/ActionEvent.java similarity index 91% rename from src/main/java/de/presti/ree6/actions/ActionEvent.java rename to src/main/java/de/presti/ree6/module/actions/ActionEvent.java index de018c9de..2ca8ace5b 100644 --- a/src/main/java/de/presti/ree6/actions/ActionEvent.java +++ b/src/main/java/de/presti/ree6/module/actions/ActionEvent.java @@ -1,4 +1,4 @@ -package de.presti.ree6.actions; +package de.presti.ree6.module.actions; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/de/presti/ree6/actions/ActionInfo.java b/src/main/java/de/presti/ree6/module/actions/ActionInfo.java similarity index 95% rename from src/main/java/de/presti/ree6/actions/ActionInfo.java rename to src/main/java/de/presti/ree6/module/actions/ActionInfo.java index ee24945ed..cf2812d4c 100644 --- a/src/main/java/de/presti/ree6/actions/ActionInfo.java +++ b/src/main/java/de/presti/ree6/module/actions/ActionInfo.java @@ -1,4 +1,4 @@ -package de.presti.ree6.actions; +package de.presti.ree6.module.actions; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/de/presti/ree6/actions/ActionRunContainer.java b/src/main/java/de/presti/ree6/module/actions/ActionRunContainer.java similarity index 91% rename from src/main/java/de/presti/ree6/actions/ActionRunContainer.java rename to src/main/java/de/presti/ree6/module/actions/ActionRunContainer.java index 01698f1ce..6f0477d5b 100644 --- a/src/main/java/de/presti/ree6/actions/ActionRunContainer.java +++ b/src/main/java/de/presti/ree6/module/actions/ActionRunContainer.java @@ -1,4 +1,4 @@ -package de.presti.ree6.actions; +package de.presti.ree6.module.actions; import lombok.AccessLevel; import lombok.AllArgsConstructor; diff --git a/src/main/java/de/presti/ree6/actions/IAction.java b/src/main/java/de/presti/ree6/module/actions/IAction.java similarity index 89% rename from src/main/java/de/presti/ree6/actions/IAction.java rename to src/main/java/de/presti/ree6/module/actions/IAction.java index 423258deb..f6f70c5b0 100644 --- a/src/main/java/de/presti/ree6/actions/IAction.java +++ b/src/main/java/de/presti/ree6/module/actions/IAction.java @@ -1,4 +1,4 @@ -package de.presti.ree6.actions; +package de.presti.ree6.module.actions; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/de/presti/ree6/actions/customevents/CustomEventActionEvent.java b/src/main/java/de/presti/ree6/module/actions/customevents/CustomEventActionEvent.java similarity index 84% rename from src/main/java/de/presti/ree6/actions/customevents/CustomEventActionEvent.java rename to src/main/java/de/presti/ree6/module/actions/customevents/CustomEventActionEvent.java index 659d1fb67..d8322de5c 100644 --- a/src/main/java/de/presti/ree6/actions/customevents/CustomEventActionEvent.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/CustomEventActionEvent.java @@ -1,6 +1,6 @@ -package de.presti.ree6.actions.customevents; +package de.presti.ree6.module.actions.customevents; -import de.presti.ree6.actions.ActionEvent; +import de.presti.ree6.module.actions.ActionEvent; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -8,8 +8,6 @@ import net.dv8tion.jda.api.entities.Guild; import org.jetbrains.annotations.Nullable; -// TODO:: gotta think about a better naming schema. - /** * A Container class containing the needed Information to run a CustomEventAction. */ diff --git a/src/main/java/de/presti/ree6/actions/customevents/IEventAction.java b/src/main/java/de/presti/ree6/module/actions/customevents/IEventAction.java similarity index 81% rename from src/main/java/de/presti/ree6/actions/customevents/IEventAction.java rename to src/main/java/de/presti/ree6/module/actions/customevents/IEventAction.java index 0b092117e..fe9968c0c 100644 --- a/src/main/java/de/presti/ree6/actions/customevents/IEventAction.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/IEventAction.java @@ -1,7 +1,7 @@ -package de.presti.ree6.actions.customevents; +package de.presti.ree6.module.actions.customevents; -import de.presti.ree6.actions.ActionEvent; -import de.presti.ree6.actions.IAction; +import de.presti.ree6.module.actions.ActionEvent; +import de.presti.ree6.module.actions.IAction; import org.jetbrains.annotations.NotNull; /** diff --git a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainer.java b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainer.java similarity index 91% rename from src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainer.java rename to src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainer.java index cc29d8df2..b2c3cd5f0 100644 --- a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainer.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainer.java @@ -1,11 +1,11 @@ -package de.presti.ree6.actions.customevents.container; +package de.presti.ree6.module.actions.customevents.container; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import de.presti.ree6.actions.ActionRunContainer; -import de.presti.ree6.actions.customevents.CustomEventActionEvent; -import de.presti.ree6.actions.customevents.IEventAction; +import de.presti.ree6.module.actions.ActionRunContainer; +import de.presti.ree6.module.actions.customevents.CustomEventActionEvent; +import de.presti.ree6.module.actions.customevents.IEventAction; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.sql.entities.custom.CustomEventAction; import lombok.AccessLevel; diff --git a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java similarity index 66% rename from src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java rename to src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java index e9265f891..e49c4f707 100644 --- a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java @@ -1,13 +1,14 @@ -package de.presti.ree6.actions.customevents.container; +package de.presti.ree6.module.actions.customevents.container; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.customevents.IEventAction; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.customevents.IEventAction; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.custom.CustomEventAction; import de.presti.ree6.sql.entities.custom.CustomEventTyp; import org.reflections.Reflections; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; +import reactor.core.publisher.Mono; import java.util.HashMap; import java.util.List; @@ -27,7 +28,7 @@ public class CustomEventContainerCreator { /** * Constructor should not be called, since it is a utility class that doesn't need an instance. */ - public CustomEventContainerCreator() { + private CustomEventContainerCreator() { throw new IllegalStateException("Utility class"); } @@ -35,6 +36,17 @@ public CustomEventContainerCreator() { * Load all actions. */ public static void loadAll() { + ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); + configurationBuilder.addClassLoaders(ClasspathHelper.staticClassLoader()); + Reflections reflections = new Reflections(configurationBuilder); + Set> classes = reflections.getSubTypesOf(IEventAction.class); + + for (Class extends IEventAction> aClass : classes) { + if (aClass.isAnnotationPresent(ActionInfo.class)) { + String actionName = aClass.getAnnotation(ActionInfo.class).name(); + cachedActions.computeIfAbsent(actionName, s -> aClass); + } + } } /** @@ -55,9 +67,7 @@ public static Class extends IEventAction> getAction(String action) { for (Class extends IEventAction> aClass : classes) { if (aClass.isAnnotationPresent(ActionInfo.class) && aClass.getAnnotation(ActionInfo.class).name().trim().equalsIgnoreCase(action)) { - if (!cachedActions.containsKey(action)) { - cachedActions.put(action, aClass); - } + cachedActions.computeIfAbsent(action, s -> aClass); return aClass; } @@ -72,10 +82,10 @@ public static Class extends IEventAction> getAction(String action) { * @param typ The typ of the CustomEventAction. * @return A List of CustomEventContainer. */ - public static List getContainers(CustomEventTyp typ) { + public static Mono> getContainers(CustomEventTyp typ) { return SQLSession.getSqlConnector().getSqlWorker() .getEntityList(new CustomEventAction(), "FROM CustomEventAction WHERE event = :typ", Map.of("typ", typ.name())) - .stream().map(CustomEventContainer::new).toList(); + .map(list -> list.stream().map(CustomEventContainer::new).toList()); } /** @@ -85,10 +95,10 @@ public static List getContainers(CustomEventTyp typ) { * @param typ The typ of the CustomEventAction. * @return A List of CustomEventContainer. */ - public static List getContainers(String guildId, CustomEventTyp typ) { + public static Mono> getContainers(String guildId, CustomEventTyp typ) { return SQLSession.getSqlConnector().getSqlWorker() .getEntityList(new CustomEventAction(), "FROM CustomEventAction WHERE guildId = :guild AND event = :typ", Map.of("guild", guildId, "typ", typ.name())) - .stream().map(CustomEventContainer::new).toList(); + .map(list -> list.stream().map(CustomEventContainer::new).toList()); } } diff --git a/src/main/java/de/presti/ree6/actions/streamtools/IStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/IStreamAction.java similarity index 88% rename from src/main/java/de/presti/ree6/actions/streamtools/IStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/IStreamAction.java index 52f3c8907..d5fcd2cfe 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/IStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/IStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools; +package de.presti.ree6.module.actions.streamtools; import com.github.twitch4j.common.events.TwitchEvent; -import de.presti.ree6.actions.ActionEvent; -import de.presti.ree6.actions.IAction; +import de.presti.ree6.module.actions.ActionEvent; +import de.presti.ree6.module.actions.IAction; import net.dv8tion.jda.api.entities.Guild; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/StreamActionEvent.java b/src/main/java/de/presti/ree6/module/actions/streamtools/StreamActionEvent.java similarity index 88% rename from src/main/java/de/presti/ree6/actions/streamtools/StreamActionEvent.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/StreamActionEvent.java index c0619c821..4aed81384 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/StreamActionEvent.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/StreamActionEvent.java @@ -1,8 +1,7 @@ -package de.presti.ree6.actions.streamtools; +package de.presti.ree6.module.actions.streamtools; import com.github.philippheuer.events4j.core.domain.Event; -import com.github.twitch4j.common.events.TwitchEvent; -import de.presti.ree6.actions.ActionEvent; +import de.presti.ree6.module.actions.ActionEvent; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayBlerpStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayBlerpStreamAction.java similarity index 89% rename from src/main/java/de/presti/ree6/actions/streamtools/action/PlayBlerpStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayBlerpStreamAction.java index 05167b7c7..1e5e5b81b 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayBlerpStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayBlerpStreamAction.java @@ -1,9 +1,9 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; import com.github.twitch4j.pubsub.events.RewardRedeemedEvent; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import de.presti.ree6.utils.data.RegExUtil; import de.presti.ree6.utils.external.RequestUtility; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayTTSStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayTTSStreamAction.java similarity index 86% rename from src/main/java/de/presti/ree6/actions/streamtools/action/PlayTTSStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayTTSStreamAction.java index 9f1c279da..53bd66ccb 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayTTSStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayTTSStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import lombok.NoArgsConstructor; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayUrlStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayUrlStreamAction.java similarity index 78% rename from src/main/java/de/presti/ree6/actions/streamtools/action/PlayUrlStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayUrlStreamAction.java index 8f0c7a5a0..1d54bee31 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayUrlStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayUrlStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import lombok.NoArgsConstructor; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/SayStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/SayStreamAction.java similarity index 83% rename from src/main/java/de/presti/ree6/actions/streamtools/action/SayStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/SayStreamAction.java index 04313aecc..4bae87958 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/SayStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/SayStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import lombok.NoArgsConstructor; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/VoiceJoinStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceJoinStreamAction.java similarity index 87% rename from src/main/java/de/presti/ree6/actions/streamtools/action/VoiceJoinStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceJoinStreamAction.java index 5b8ba08da..544ca90d2 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/VoiceJoinStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceJoinStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import io.sentry.Sentry; import lombok.NoArgsConstructor; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/VoiceLeaveStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceLeaveStreamAction.java similarity index 76% rename from src/main/java/de/presti/ree6/actions/streamtools/action/VoiceLeaveStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceLeaveStreamAction.java index f4cfa6569..5b606a769 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/VoiceLeaveStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceLeaveStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import lombok.NoArgsConstructor; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainer.java b/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainer.java similarity index 93% rename from src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainer.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainer.java index 89d0a6c19..db4c9dba4 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainer.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainer.java @@ -1,12 +1,12 @@ -package de.presti.ree6.actions.streamtools.container; +package de.presti.ree6.module.actions.streamtools.container; import com.github.philippheuer.events4j.core.domain.Event; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import de.presti.ree6.actions.ActionRunContainer; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionRunContainer; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.sql.entities.StreamAction; import de.presti.ree6.utils.others.ThreadUtil; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java b/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainerCreator.java similarity index 84% rename from src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainerCreator.java index e3d317cc5..a50e13160 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainerCreator.java @@ -1,13 +1,14 @@ -package de.presti.ree6.actions.streamtools.container; +package de.presti.ree6.module.actions.streamtools.container; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.action.*; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.action.*; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.StreamAction; import org.reflections.Reflections; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; +import reactor.core.publisher.Mono; import java.util.HashMap; import java.util.List; @@ -27,7 +28,7 @@ public class StreamActionContainerCreator { /** * Constructor should not be called, since it is a utility class that doesn't need an instance. */ - public StreamActionContainerCreator() { + private StreamActionContainerCreator() { throw new IllegalStateException("Utility class"); } @@ -77,10 +78,10 @@ public static Class extends IStreamAction> getAction(String action) { * @param listenerId The Listener to get the Containers for. * @return A List of StreamActionContainers. */ - public static List getContainers(int listenerId) { + public static Mono> getContainers(int listenerId) { return SQLSession.getSqlConnector().getSqlWorker() .getEntityList(new StreamAction(), "FROM StreamAction WHERE listener = :listener", Map.of("listener", listenerId)) - .stream().map(StreamActionContainer::new).toList(); + .map(list -> list.stream().map(StreamActionContainer::new).toList()); } } diff --git a/src/main/java/de/presti/ree6/game/core/GameManager.java b/src/main/java/de/presti/ree6/module/game/core/GameManager.java similarity index 92% rename from src/main/java/de/presti/ree6/game/core/GameManager.java rename to src/main/java/de/presti/ree6/module/game/core/GameManager.java index c6725847f..0a857e0ac 100644 --- a/src/main/java/de/presti/ree6/game/core/GameManager.java +++ b/src/main/java/de/presti/ree6/module/game/core/GameManager.java @@ -1,7 +1,7 @@ -package de.presti.ree6.game.core; +package de.presti.ree6.module.game.core; -import de.presti.ree6.game.core.base.GameInfo; -import de.presti.ree6.game.core.base.IGame; +import de.presti.ree6.module.game.core.base.GameInfo; +import de.presti.ree6.module.game.core.base.IGame; import de.presti.ree6.utils.others.RandomUtils; import lombok.Getter; import lombok.extern.slf4j.Slf4j; @@ -20,24 +20,31 @@ @Slf4j public class GameManager { + /** + * Constructor to prevent instance creation of the GameManager. + */ + private GameManager() { + throw new UnsupportedOperationException("Do not instance this."); + } + /** * A HashMap used to cache the Games. * The Key is the Name of the Game. */ @Getter - private final static HashMap> gameCache = new HashMap<>(); + private static final HashMap> gameCache = new HashMap<>(); /** * A HashMap used to cache the GameSessions. * The Key is the ID of the Channel. */ - private final static HashMap gameSessions = new HashMap<>(); + private static final HashMap gameSessions = new HashMap<>(); /** * Should be called to load all Games into the cache. */ public static void loadAllGames() { - Reflections reflections = new Reflections("de.presti.ree6.game.impl"); + Reflections reflections = new Reflections("de.presti.ree6.module.game.impl"); Set> classes = reflections.getSubTypesOf(IGame.class); for (Class extends IGame> aClass : classes) { @@ -99,7 +106,7 @@ public static IGame getGame(String gameName, GameSession gameSession) { } } - Reflections reflections = new Reflections("de.presti.ree6.game.impl"); + Reflections reflections = new Reflections("de.presti.ree6.module.game.impl"); Set> classes = reflections.getSubTypesOf(IGame.class); for (Class extends IGame> aClass : classes) { diff --git a/src/main/java/de/presti/ree6/game/core/GameSession.java b/src/main/java/de/presti/ree6/module/game/core/GameSession.java similarity index 95% rename from src/main/java/de/presti/ree6/game/core/GameSession.java rename to src/main/java/de/presti/ree6/module/game/core/GameSession.java index ae7a6522b..353991e89 100644 --- a/src/main/java/de/presti/ree6/game/core/GameSession.java +++ b/src/main/java/de/presti/ree6/module/game/core/GameSession.java @@ -1,13 +1,12 @@ -package de.presti.ree6.game.core; +package de.presti.ree6.module.game.core; -import de.presti.ree6.game.core.base.GameState; -import de.presti.ree6.game.core.base.IGame; +import de.presti.ree6.module.game.core.base.GameState; +import de.presti.ree6.module.game.core.base.IGame; import lombok.Getter; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.channel.unions.GuildMessageChannelUnion; -import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion; import java.util.ArrayList; diff --git a/src/main/java/de/presti/ree6/game/core/base/GameInfo.java b/src/main/java/de/presti/ree6/module/game/core/base/GameInfo.java similarity index 93% rename from src/main/java/de/presti/ree6/game/core/base/GameInfo.java rename to src/main/java/de/presti/ree6/module/game/core/base/GameInfo.java index e233316ca..29dd09f79 100644 --- a/src/main/java/de/presti/ree6/game/core/base/GameInfo.java +++ b/src/main/java/de/presti/ree6/module/game/core/base/GameInfo.java @@ -1,4 +1,4 @@ -package de.presti.ree6.game.core.base; +package de.presti.ree6.module.game.core.base; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/src/main/java/de/presti/ree6/game/core/base/GamePlayer.java b/src/main/java/de/presti/ree6/module/game/core/base/GamePlayer.java similarity index 91% rename from src/main/java/de/presti/ree6/game/core/base/GamePlayer.java rename to src/main/java/de/presti/ree6/module/game/core/base/GamePlayer.java index bbd924d9a..4b96c3c8b 100644 --- a/src/main/java/de/presti/ree6/game/core/base/GamePlayer.java +++ b/src/main/java/de/presti/ree6/module/game/core/base/GamePlayer.java @@ -1,4 +1,4 @@ -package de.presti.ree6.game.core.base; +package de.presti.ree6.module.game.core.base; import de.presti.ree6.bot.BotWorker; import lombok.Getter; @@ -50,7 +50,7 @@ public GamePlayer(long relatedUserId) { */ public User getRelatedUser() { if (relatedUser == null) - return relatedUser = BotWorker.getShardManager().getUserById(relatedUserId); + relatedUser = BotWorker.getShardManager().getUserById(relatedUserId); return relatedUser; } diff --git a/src/main/java/de/presti/ree6/game/core/base/GameState.java b/src/main/java/de/presti/ree6/module/game/core/base/GameState.java similarity index 82% rename from src/main/java/de/presti/ree6/game/core/base/GameState.java rename to src/main/java/de/presti/ree6/module/game/core/base/GameState.java index 087e3f84e..32b16e387 100644 --- a/src/main/java/de/presti/ree6/game/core/base/GameState.java +++ b/src/main/java/de/presti/ree6/module/game/core/base/GameState.java @@ -1,4 +1,4 @@ -package de.presti.ree6.game.core.base; +package de.presti.ree6.module.game.core.base; /** * Enum used to store the current Game State. diff --git a/src/main/java/de/presti/ree6/game/core/base/IGame.java b/src/main/java/de/presti/ree6/module/game/core/base/IGame.java similarity index 78% rename from src/main/java/de/presti/ree6/game/core/base/IGame.java rename to src/main/java/de/presti/ree6/module/game/core/base/IGame.java index 627915bf2..ed5758247 100644 --- a/src/main/java/de/presti/ree6/game/core/base/IGame.java +++ b/src/main/java/de/presti/ree6/module/game/core/base/IGame.java @@ -1,15 +1,11 @@ -package de.presti.ree6.game.core.base; +package de.presti.ree6.module.game.core.base; -import de.presti.ree6.game.core.GameSession; -import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.economy.MoneyHolder; +import de.presti.ree6.module.game.core.GameSession; import de.presti.ree6.utils.data.EconomyUtil; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent; -import java.util.Map; - /** * Interface for Games to implement. */ @@ -27,12 +23,14 @@ public interface IGame { /** * Called when a User wants to join the Game. + * * @param user The User who wants to join. */ void joinGame(GamePlayer user); /** * Called when a User wants to leave the Game. + * * @param user The User who wants to leave. */ void leaveGame(GamePlayer user); @@ -66,19 +64,24 @@ default void onButtonInteractionReceive(ButtonInteractionEvent buttonInteraction /** * Called when a User should be rewarded. + * * @param gameSession The current Session. - * @param player The Player who should be rewarded. - * @param parameter Any additional Parameter. + * @param player The Player who should be rewarded. + * @param parameter Any additional Parameter. */ default void rewardPlayer(GameSession gameSession, GamePlayer player, Object parameter) { if (parameter instanceof String parameterString) { try { parameter = Double.parseDouble(parameterString.replace(",", ".")); - } catch (Exception ignore) {} + } catch (Exception ignore) { + // Parsing failed. + } } if (parameter instanceof Double money) { - EconomyUtil.pay(null, EconomyUtil.getMoneyHolder(gameSession.getGuild().getIdLong(), player.getRelatedUserId(), true), - money, false, false, true); + EconomyUtil.getMoneyHolder(gameSession.getGuild().getIdLong(), player.getRelatedUserId(), true).subscribe(moneyHolder -> { + if (moneyHolder == null) return; + EconomyUtil.pay(null, moneyHolder, money, false, false, true); + }); } } diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java b/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java similarity index 80% rename from src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java rename to src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java index 4b6ba6a39..346b45b71 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java +++ b/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java @@ -1,19 +1,18 @@ -package de.presti.ree6.game.impl.blackjack; - -import de.presti.ree6.bot.BotWorker; -import de.presti.ree6.game.core.GameManager; -import de.presti.ree6.game.core.GameSession; -import de.presti.ree6.game.core.base.GameInfo; -import de.presti.ree6.game.core.base.GamePlayer; -import de.presti.ree6.game.core.base.GameState; -import de.presti.ree6.game.core.base.IGame; -import de.presti.ree6.game.impl.blackjack.entities.BlackJackCard; -import de.presti.ree6.game.impl.blackjack.entities.BlackJackPlayer; -import de.presti.ree6.game.impl.blackjack.util.BlackJackCardUtility; +package de.presti.ree6.module.game.impl.blackjack; + +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; +import de.presti.ree6.module.game.core.GameManager; +import de.presti.ree6.module.game.core.GameSession; +import de.presti.ree6.module.game.core.base.GameInfo; +import de.presti.ree6.module.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GameState; +import de.presti.ree6.module.game.core.base.IGame; +import de.presti.ree6.module.game.impl.blackjack.entities.BlackJackCard; +import de.presti.ree6.module.game.impl.blackjack.entities.BlackJackPlayer; +import de.presti.ree6.module.game.impl.blackjack.util.BlackJackCardUtility; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.Setting; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; @@ -23,7 +22,6 @@ import java.awt.*; import java.util.ArrayList; -import java.util.Map; /** * Class used to represent the game of blackjack. @@ -77,20 +75,20 @@ public Blackjack(GameSession gameSession) { @Override public void createGame() { if (session.getParticipants().isEmpty() || session.getParticipants().size() > 2) { - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.gameCore.needMore", 2), session.getChannel()); + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.gameCore.needMore", 2).block(), session.getChannel()); stopGame(); } MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack")); - embedBuilder.setColor(BotWorker.randomEmbedColor()); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.welcome", session.getGameIdentifier())); + embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); + embedBuilder.setColor(BotConfig.getMainColor()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.welcome", session.getGameIdentifier()).block()); messageCreateBuilder.setEmbeds(embedBuilder.build()); - messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame")).asDisabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame")).asEnabled()); + messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").block()).asDisabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").block()).asEnabled()); session.getChannel().sendMessage(messageCreateBuilder.build()).queue(message -> menuMessage = message); } @@ -117,7 +115,7 @@ public void startGame() { playerTwo.getHand().add(getRandomCard()); updateViews(player, playerTwo); - Main.getInstance().getCommandManager().deleteMessage(menuMessage, null); + Main.getInstance().getCommandManager().deleteMessageWithoutException(menuMessage, null); currentPlayer = player; } @@ -127,17 +125,17 @@ public void startGame() { @Override public void joinGame(GamePlayer user) { if (session.getGameState() == GameState.STARTED) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyStarted")).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyStarted").block()).queue(); return; } if (player != null && playerTwo != null) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.full")).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.full").block()).queue(); return; } if ((player != null && user.getRelatedUserId() == player.getRelatedUserId()) || (playerTwo != null && user.getRelatedUserId() == playerTwo.getRelatedUserId())) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyIn")).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyIn").block()).queue(); return; } @@ -151,18 +149,18 @@ public void joinGame(GamePlayer user) { MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); messageEditBuilder.applyMessage(menuMessage); EmbedBuilder embedBuilder = new EmbedBuilder(messageEditBuilder.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReached")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReached").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame")).asEnabled()); + messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").block()).asEnabled()); menuMessage.editMessage(messageEditBuilder.build()).queue(); messageEditBuilder.clear(); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); playerTwo.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); messageEditBuilder.clear(); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReachedHost")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReachedHost").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); player.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); } @@ -292,18 +290,18 @@ public void stand(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) { public void stopGame(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack")); - embedBuilder.setColor(BotWorker.randomEmbedColor()); + embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); + embedBuilder.setColor(BotConfig.getMainColor()); BlackJackPlayer winner = findWinner(); if (winner == null) { - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.draw")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.draw").block()); } else { - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.win", winner.getRelatedUser().getAsMention(), winner.getHandValue(true))); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.win", winner.getRelatedUser().getAsMention(), winner.getHandValue(true)).block()); } - embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)), true); - embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)), true); + embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()).block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)).block(), true); + embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()).block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)).block(), true); messageCreateBuilder.setEmbeds(embedBuilder.build()); messageCreateBuilder.setComponents(new ArrayList<>()); @@ -311,8 +309,10 @@ public void stopGame(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) nextPlayer.getInteractionHook().editOriginalComponents(new ArrayList<>()).queue(); Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), session.getChannel()); - rewardPlayer(session, winner, SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_blackjack_win")).getValue()); + SQLSession.getSqlConnector().getSqlWorker().getSetting(session.getGuild().getIdLong(), + "configuration_rewards_blackjack_win") + .subscribe(setting -> rewardPlayer(session, winner, setting.get().getValue())); + stopGame(); } @@ -337,33 +337,33 @@ public void updateViews(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlaye MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); EmbedBuilder currentPlayerEmbed = new EmbedBuilder(); - currentPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack")); - currentPlayerEmbed.setColor(Color.GREEN); + currentPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); + currentPlayerEmbed.setColor(BotConfig.getMainColor()); currentPlayerEmbed.setAuthor(currentPlayer.getRelatedUser().getEffectiveName(), null, currentPlayer.getRelatedUser().getEffectiveAvatarUrl()); - currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf"), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", - currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)), true); - currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", - nextPlayer.getHandAsString(false), nextPlayer.getHandValue(false)), true); + currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf").block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", + currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)).block(), true); + currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()).block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", + nextPlayer.getHandAsString(false), nextPlayer.getHandValue(false)).block(), true); - currentPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.player")); + currentPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.player").block()); messageEditBuilder.setEmbeds(currentPlayerEmbed.build()); if (addButtons) { - messageEditBuilder.setActionRow(Button.primary("game_blackjack_hit", LanguageService.getByGuild(session.getGuild(), "label.hit")), - Button.success("game_blackjack_stand", LanguageService.getByGuild(session.getGuild(), "label.stand"))); + messageEditBuilder.setActionRow(Button.primary("game_blackjack_hit", LanguageService.getByGuild(session.getGuild(), "label.hit").block()), + Button.success("game_blackjack_stand", LanguageService.getByGuild(session.getGuild(), "label.stand").block())); } currentPlayer.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); EmbedBuilder nextPlayerEmbed = new EmbedBuilder(); - nextPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack")); - nextPlayerEmbed.setColor(Color.red); + nextPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); + nextPlayerEmbed.setColor(Color.RED); nextPlayerEmbed.setAuthor(nextPlayer.getRelatedUser().getEffectiveName(), null, nextPlayer.getRelatedUser().getEffectiveAvatarUrl()); - nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf"), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)), true); - nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(false), currentPlayer.getHandValue(false)), true); - nextPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.wait")); + nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf").block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)).block(), true); + nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()).block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(false), currentPlayer.getHandValue(false)).block(), true); + nextPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.wait").block()); messageEditBuilder.setEmbeds(nextPlayerEmbed.build()); nextPlayer.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackCard.java b/src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackCard.java similarity index 96% rename from src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackCard.java rename to src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackCard.java index 5a0948833..22d66f09b 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackCard.java +++ b/src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackCard.java @@ -1,4 +1,4 @@ -package de.presti.ree6.game.impl.blackjack.entities; +package de.presti.ree6.module.game.impl.blackjack.entities; import net.dv8tion.jda.api.entities.emoji.CustomEmoji; diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackPlayer.java b/src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackPlayer.java similarity index 96% rename from src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackPlayer.java rename to src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackPlayer.java index 7dbcbb359..14681d852 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackPlayer.java +++ b/src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackPlayer.java @@ -1,6 +1,6 @@ -package de.presti.ree6.game.impl.blackjack.entities; +package de.presti.ree6.module.game.impl.blackjack.entities; -import de.presti.ree6.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GamePlayer; import net.dv8tion.jda.api.entities.User; import java.util.ArrayList; diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/util/BlackJackCardUtility.java b/src/main/java/de/presti/ree6/module/game/impl/blackjack/util/BlackJackCardUtility.java similarity index 98% rename from src/main/java/de/presti/ree6/game/impl/blackjack/util/BlackJackCardUtility.java rename to src/main/java/de/presti/ree6/module/game/impl/blackjack/util/BlackJackCardUtility.java index 91474d224..f44e5a86a 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/util/BlackJackCardUtility.java +++ b/src/main/java/de/presti/ree6/module/game/impl/blackjack/util/BlackJackCardUtility.java @@ -1,6 +1,6 @@ -package de.presti.ree6.game.impl.blackjack.util; +package de.presti.ree6.module.game.impl.blackjack.util; -import de.presti.ree6.game.impl.blackjack.entities.BlackJackCard; +import de.presti.ree6.module.game.impl.blackjack.entities.BlackJackCard; import de.presti.ree6.utils.others.RandomUtils; import net.dv8tion.jda.api.entities.emoji.Emoji; diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java similarity index 80% rename from src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java rename to src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java index 124802f7a..cf3cc6ec3 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java +++ b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java @@ -1,18 +1,17 @@ -package de.presti.ree6.game.impl.musicquiz; - -import de.presti.ree6.bot.BotWorker; -import de.presti.ree6.game.core.GameSession; -import de.presti.ree6.game.core.base.GameInfo; -import de.presti.ree6.game.core.base.GamePlayer; -import de.presti.ree6.game.core.base.GameState; -import de.presti.ree6.game.core.base.IGame; -import de.presti.ree6.game.impl.musicquiz.entities.MusicQuizEntry; -import de.presti.ree6.game.impl.musicquiz.entities.MusicQuizPlayer; -import de.presti.ree6.game.impl.musicquiz.util.MusicQuizUtil; +package de.presti.ree6.module.game.impl.musicquiz; + +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; +import de.presti.ree6.module.game.core.GameSession; +import de.presti.ree6.module.game.core.base.GameInfo; +import de.presti.ree6.module.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GameState; +import de.presti.ree6.module.game.core.base.IGame; +import de.presti.ree6.module.game.impl.musicquiz.entities.MusicQuizEntry; +import de.presti.ree6.module.game.impl.musicquiz.entities.MusicQuizPlayer; +import de.presti.ree6.module.game.impl.musicquiz.util.MusicQuizUtil; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.utils.others.ThreadUtil; import lavalink.client.player.event.IPlayerEventListener; import lavalink.client.player.event.TrackEndEvent; @@ -29,7 +28,6 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.List; -import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -105,20 +103,20 @@ public MusicQuiz(GameSession gameSession) { public void createGame() { if (session.getHost().getVoiceState() == null || session.getHost().getVoiceState().getChannel() == null) { - session.getChannel().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.default.notInVoiceChannel")).queue(); + session.getChannel().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.default.notInVoiceChannel").block()).queue(); return; } MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.musicQuiz")); - embedBuilder.setColor(BotWorker.randomEmbedColor()); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier())); + embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.musicQuiz").block()); + embedBuilder.setColor(BotConfig.getMainColor()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier()).block()); messageCreateBuilder.setEmbeds(embedBuilder.build()); - messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame")).asDisabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame")).asEnabled()); + messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").block()).asDisabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").block()).asEnabled()); menuMessage = session.getChannel().sendMessage(messageCreateBuilder.build()).complete(); } @@ -150,7 +148,7 @@ public void startGame() { public void joinGame(GamePlayer user) { if (participants.stream().anyMatch(c -> c.getRelatedUserId() == user.getRelatedUserId())) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyJoined")).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyJoined").block()).queue(); return; } @@ -159,16 +157,16 @@ public void joinGame(GamePlayer user) { MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(menuMessage.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.secondary("game_leave:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.leaveGame")).asEnabled()); + messageEditBuilder.setActionRow(Button.secondary("game_leave:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.leaveGame").block()).asEnabled()); user.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); if (participants.size() >= 2) { - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier())); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier()).block()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame")).asEnabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame")).asEnabled()); + messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").block()).asEnabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").block()).asEnabled()); menuMessage.editMessage(messageEditBuilder.build()).queue(); } } @@ -186,10 +184,10 @@ public void leaveGame(GamePlayer user) { messageEditBuilder.applyMessage(menuMessage); EmbedBuilder embedBuilder = new EmbedBuilder(messageEditBuilder.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame")).asDisabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame")).asEnabled()); + messageEditBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").block()).asDisabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").block()).asEnabled()); menuMessage = menuMessage.editMessage(messageEditBuilder.build()).complete(); } } @@ -213,33 +211,38 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { if (currentEntry.checkTitle(messageContent)) { musicQuizPlayer.addPoints(1); - rewardPlayer(session, musicQuizPlayer,SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_title")).getValue()); - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundTitle", currentEntry.getTitle())).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(session.getGuild().getIdLong(), "configuration_rewards_musicquiz_title") + .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.get().getValue())); + + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundTitle", currentEntry.getTitle()).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); } if (currentEntry.checkArtist(messageContent)) { musicQuizPlayer.addPoints(2); - rewardPlayer(session, musicQuizPlayer,SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_artist")).getValue()); - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundArtists", currentEntry.getArtist())).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(session.getGuild().getIdLong(), + "configuration_rewards_musicquiz_artist") + .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.get().getValue())); + + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundArtists", currentEntry.getArtist()).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); } if (currentEntry.checkFeatures(messageContent)) { musicQuizPlayer.addPoints(3); - rewardPlayer(session, musicQuizPlayer,SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_feature")).getValue()); - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundFeature", String.join(",", currentEntry.getFeatures()))).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(session.getGuild().getIdLong(), + "configuration_rewards_musicquiz_feature") + .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.get().getValue())); + + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundFeature", String.join(",", currentEntry.getFeatures())).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); } if (currentEntry.isTitleGuessed() && currentEntry.isArtistGuessed() && currentEntry.isFeaturesGuessed()) { - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundAll")).queue(); + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundAll").block()).queue(); selectNextSong(); } } @@ -266,22 +269,23 @@ public void stopGame() { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(menuMessage.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong").block()); List sortedList = participants.stream().sorted(Comparator.comparingInt(MusicQuizPlayer::getPoints).reversed()).toList(); for (int i = 0; i < sortedList.size(); i++) { MusicQuizPlayer musicQuizPlayer = sortedList.get(i); - embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.position", i + 1), + embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.position", i + 1).block(), LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.points", musicQuizPlayer.getRelatedUser().getAsMention(), - musicQuizPlayer.getPoints()), false); + musicQuizPlayer.getPoints()).block(), false); } messageCreateBuilder.setEmbeds(embedBuilder.build()); menuMessage.delete().queue(); session.getChannel().sendMessage(messageCreateBuilder.build()).queue(); - rewardPlayer(session, sortedList.get(0), SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_win")).getValue()); + SQLSession.getSqlConnector().getSqlWorker().getSetting(session.getGuild().getIdLong(), + "configuration_rewards_musicquiz_win") + .subscribe(setting -> rewardPlayer(session, sortedList.get(0), setting.get().getValue())); Main.getInstance().getMusicWorker().disconnect(session.getGuild()); } @@ -317,9 +321,9 @@ public void selectNextSong() { messageEditBuilder.applyMessage(menuMessage); EmbedBuilder embedBuilder = new EmbedBuilder(messageEditBuilder.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.success("game_musicquiz_skip", LanguageService.getByGuild(session.getGuild(), "label.skip")).asEnabled()); + messageEditBuilder.setActionRow(Button.success("game_musicquiz_skip", LanguageService.getByGuild(session.getGuild(), "label.skip").block()).asEnabled()); menuMessage.editMessage(messageEditBuilder.build()).queue(); AudioChannel audioChannel = session.getGuild().getMember(session.getHost()).getVoiceState().getChannel(); diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizEntry.java b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizEntry.java similarity index 98% rename from src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizEntry.java rename to src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizEntry.java index 3d7430eb6..f795dd291 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizEntry.java +++ b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizEntry.java @@ -1,4 +1,4 @@ -package de.presti.ree6.game.impl.musicquiz.entities; +package de.presti.ree6.module.game.impl.musicquiz.entities; import lombok.Getter; diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizPlayer.java b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizPlayer.java similarity index 84% rename from src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizPlayer.java rename to src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizPlayer.java index 5338e622c..ef61bb966 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizPlayer.java +++ b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizPlayer.java @@ -1,8 +1,7 @@ -package de.presti.ree6.game.impl.musicquiz.entities; +package de.presti.ree6.module.game.impl.musicquiz.entities; -import de.presti.ree6.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GamePlayer; import lombok.Getter; -import net.dv8tion.jda.api.hooks.ListenerAdapter; /** * Class used to store information about a player in the music quiz game. diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/util/MusicQuizUtil.java b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/util/MusicQuizUtil.java similarity index 97% rename from src/main/java/de/presti/ree6/game/impl/musicquiz/util/MusicQuizUtil.java rename to src/main/java/de/presti/ree6/module/game/impl/musicquiz/util/MusicQuizUtil.java index 42edee100..ec9c45132 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/util/MusicQuizUtil.java +++ b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/util/MusicQuizUtil.java @@ -1,6 +1,6 @@ -package de.presti.ree6.game.impl.musicquiz.util; +package de.presti.ree6.module.game.impl.musicquiz.util; -import de.presti.ree6.game.impl.musicquiz.entities.MusicQuizEntry; +import de.presti.ree6.module.game.impl.musicquiz.entities.MusicQuizEntry; import de.presti.ree6.utils.apis.SpotifyAPIHandler; import de.presti.ree6.utils.apis.YouTubeAPIHandler; import de.presti.ree6.utils.others.RandomUtils; diff --git a/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java b/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java index 7ae4d03d5..67a277606 100644 --- a/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java +++ b/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java @@ -5,7 +5,6 @@ import de.presti.ree6.sql.entities.Giveaway; import de.presti.ree6.utils.others.RandomUtils; import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.utils.messages.MessageEditBuilder; @@ -35,8 +34,9 @@ public GiveawayManager() { */ @Override public void load() { - replace(SQLSession.getSqlConnector().getSqlWorker() - .getEntityList(new Giveaway(), "FROM Giveaway", null)); + SQLSession.getSqlConnector().getSqlWorker() + .getEntityList(new Giveaway(), "FROM Giveaway", null) + .subscribe(this::replace); } /** @@ -58,18 +58,18 @@ public Giveaway get(long value) { } } - Giveaway giveaway = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Giveaway(), "FROM Giveaway WHERE messageId = :id", Map.of("id", value)); - - if (giveaway != null) { - giveaways.add(giveaway); - return giveaway; - } - return null; + return SQLSession.getSqlConnector().getSqlWorker().getEntity(new Giveaway(), "FROM Giveaway WHERE messageId = :id", Map.of("id", value)).mapNotNull(giveaway -> { + if (giveaway.isPresent()) { + giveaways.add(giveaway.get()); + return giveaway.get(); + } + return null; + }).block(); } @Override public void remove(Giveaway object) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(object); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(object).block(); IManager.super.remove(object); } diff --git a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java index 8615ce955..58c5b5402 100644 --- a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java +++ b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java @@ -18,7 +18,6 @@ /** * Utility class to contain every Invite and manage the Invites in our Database. */ -// TODO:: continue with the rework of this entire system @Slf4j public class InviteContainerManager implements IManager { @@ -43,7 +42,8 @@ public List getInvites(long guildId) { @Override public void load() { - replace(SQLSession.getSqlConnector().getSqlWorker().getEntityList(new de.presti.ree6.sql.entities.Invite(), "FROM Invite", null).stream().map(InviteContainer::new).toList()); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new de.presti.ree6.sql.entities.Invite(), "FROM Invite", null) + .subscribe(invites1 -> replace(invites1.stream().map(InviteContainer::new).toList())); } /** @@ -53,8 +53,8 @@ public void load() { */ public void refreshGuild(long guildId) { invites.removeIf(x -> x.guildId == guildId); - getList().addAll(SQLSession.getSqlConnector().getSqlWorker().getEntityList(new de.presti.ree6.sql.entities.Invite(), "FROM Invite WHERE guildAndCode.guildId = :gid", Map.of("gid", guildId)) - .stream().map(InviteContainer::new).toList()); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new de.presti.ree6.sql.entities.Invite(), "FROM Invite WHERE guildAndCode.guildId = :gid", Map.of("gid", guildId)) + .subscribe(invites1 -> replace(invites1.stream().map(InviteContainer::new).toList())); } /** @@ -81,7 +81,7 @@ public void add(InviteContainer inviteContainer) { getList().add(inviteContainer); try { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new de.presti.ree6.sql.entities.Invite(inviteContainer.getGuildId(), inviteContainer.getCreatorId(), inviteContainer.getUses(), inviteContainer.getCode())); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new de.presti.ree6.sql.entities.Invite(inviteContainer.getGuildId(), inviteContainer.getCreatorId(), inviteContainer.getUses(), inviteContainer.getCode())).block(); } catch (Exception ex) { log.error("[InviteManager] Error while Saving Invites: " + ex.getMessage()); } @@ -171,35 +171,37 @@ public InviteContainer getRightInvite(Guild guild) { } // Go through every Invite of the Guild from our Database. - for (InviteContainer inv2 : getInvites(guild.getIdLong())) { + for (InviteContainer databaseInvite : getInvites(guild.getIdLong())) { // Check if its correct invite. - if (inv.getCode().equalsIgnoreCase(inv2.getCode())) { + if (inv.getCode().equalsIgnoreCase(databaseInvite.getCode())) { foundOne = true; // Check if the Creator of the Invite isn't the same as in our Database. - if (inv.getInviter().getIdLong() != inv2.getCreatorId()) { + if (inv.getInviter().getIdLong() != databaseInvite.getCreatorId()) { // Check if its Vanity Invite. if (vanityInvite != null && inv.getCode().equalsIgnoreCase(vanityInvite.getCode())) { // Correct the information. - inv2.setVanity(true); - inv2.setGuildId(guild.getIdLong()); - if (inv2.getCreatorId() == 0) { - inv2.setCreatorId(guild.getOwnerIdLong()); + databaseInvite.setVanity(true); + databaseInvite.setGuildId(guild.getIdLong()); + if (databaseInvite.getCreatorId() == 0) { + databaseInvite.setCreatorId(guild.getOwnerIdLong()); } } else { // This should never be reached so, log it. - log.warn("Detected a very weird Invite? Owner does not match database entry! Guild: " + guild.getName() + " (" + guild.getId() + ") Invite: " + inv.getInviter().getIdLong() + " Database: " + inv2.getCreatorId()); + log.warn("Detected a very weird Invite? Owner does not match database entry! Guild: " + guild.getName() + " (" + guild.getId() + ") Invite: " + inv.getInviter().getIdLong() + " Database: " + databaseInvite.getCreatorId()); break; } } // Check if the Invite from Discord exactly one more usage than in our Database. // If so, we most likely got the correct one. - if (inv.getUses() - 1 == inv2.getUses()) { - inv2.setVanity(vanityInvite != null && inv2.getCode().equalsIgnoreCase(vanityInvite.getCode())); - return inv2; + // Big Issue, if many users join at the same time the value updates quicker than Ree6 can react. + // So -1 would not work at all. + if (inv.getUses() - 1 == databaseInvite.getUses()) { + databaseInvite.setVanity(vanityInvite != null && databaseInvite.getCode().equalsIgnoreCase(vanityInvite.getCode())); + return databaseInvite; } } } diff --git a/src/main/java/de/presti/ree6/logger/LogMessage.java b/src/main/java/de/presti/ree6/module/logger/LogMessage.java similarity index 98% rename from src/main/java/de/presti/ree6/logger/LogMessage.java rename to src/main/java/de/presti/ree6/module/logger/LogMessage.java index d54c3a17c..55ecfa6f7 100644 --- a/src/main/java/de/presti/ree6/logger/LogMessage.java +++ b/src/main/java/de/presti/ree6/module/logger/LogMessage.java @@ -1,4 +1,4 @@ -package de.presti.ree6.logger; +package de.presti.ree6.module.logger; import club.minnced.discord.webhook.send.WebhookMessage; import net.dv8tion.jda.api.entities.Guild; diff --git a/src/main/java/de/presti/ree6/logger/LogTyp.java b/src/main/java/de/presti/ree6/module/logger/LogTyp.java similarity index 97% rename from src/main/java/de/presti/ree6/logger/LogTyp.java rename to src/main/java/de/presti/ree6/module/logger/LogTyp.java index 8752dbdaa..4e6a9ec16 100644 --- a/src/main/java/de/presti/ree6/logger/LogTyp.java +++ b/src/main/java/de/presti/ree6/module/logger/LogTyp.java @@ -1,4 +1,4 @@ -package de.presti.ree6.logger; +package de.presti.ree6.module.logger; /** * The used Log-Types. diff --git a/src/main/java/de/presti/ree6/logger/LoggerQueue.java b/src/main/java/de/presti/ree6/module/logger/LoggerQueue.java similarity index 93% rename from src/main/java/de/presti/ree6/logger/LoggerQueue.java rename to src/main/java/de/presti/ree6/module/logger/LoggerQueue.java index 3071f27d1..bc3e6ec84 100644 --- a/src/main/java/de/presti/ree6/logger/LoggerQueue.java +++ b/src/main/java/de/presti/ree6/module/logger/LoggerQueue.java @@ -1,15 +1,15 @@ -package de.presti.ree6.logger; +package de.presti.ree6.module.logger; import club.minnced.discord.webhook.send.WebhookEmbed; import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.util.WebhookUtil; import de.presti.ree6.language.LanguageService; -import de.presti.ree6.logger.events.LogMessageMember; -import de.presti.ree6.logger.events.LogMessageRole; -import de.presti.ree6.logger.events.LogMessageUser; -import de.presti.ree6.logger.events.LogMessageVoice; -import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.module.logger.events.LogMessageMember; +import de.presti.ree6.module.logger.events.LogMessageRole; +import de.presti.ree6.module.logger.events.LogMessageUser; +import de.presti.ree6.module.logger.events.LogMessageVoice; import de.presti.ree6.utils.others.ThreadUtil; import net.dv8tion.jda.api.Permission; @@ -71,7 +71,8 @@ public void add(LogMessage loggerMessage) { // Set the new Webhook Message. webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(logMessageVoice.getMember().getUser().getEffectiveName(), logMessageVoice.getMember().getEffectiveAvatarUrl(), null)); - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.rejoin", logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.rejoin", + logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention()).block()); modified = true; } @@ -92,7 +93,8 @@ else if (loggerMessage.getType() == LogTyp.VC_MOVE && loggerMessage instanceof L // Set the new Webhook Message. webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(logMessageVoice.getMember().getUser().getEffectiveName(), logMessageVoice.getMember().getEffectiveAvatarUrl(), null)); - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.moveMany", logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.moveMany", + logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention()).block()); modified = true; } @@ -112,7 +114,8 @@ else if (loggerMessage.getType() == LogTyp.VC_LEAVE && loggerMessage instanceof // Set the new Webhook Message. webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(logMessageVoice.getMember().getUser().getEffectiveName(), logMessageVoice.getMember().getEffectiveAvatarUrl(), null)); - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.leaveInstant", logMessageVoice.getMember().getAsMention(), logMessageVoice.getPreviousVoiceChannel().getAsMention())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.leaveInstant", + logMessageVoice.getMember().getAsMention(), logMessageVoice.getPreviousVoiceChannel().getAsMention()).block()); modified = true; } @@ -146,7 +149,7 @@ else if (loggerMessage.getType() == LogTyp.NICKNAME_CHANGE && loggerMessage inst webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.nickname.changed", logMessageMember.getMember().getAsMention(), logMessageMember.getPreviousName(), - memberData != null && memberData.getPreviousName() != null ? memberData.getPreviousName() : logMessageMember.getMember().getUser().getName())); + memberData != null && memberData.getPreviousName() != null ? memberData.getPreviousName() : logMessageMember.getMember().getUser().getName()).block()); modified = true; } @@ -216,10 +219,10 @@ else if (loggerMessage.getType() == LogTyp.MEMBERROLE_CHANGE && loggerMessage in logMessageMember.getMember().getEffectiveAvatarUrl(), null)); webhookEmbedBuilder.setThumbnailUrl(logMessageMember.getMember().getEffectiveAvatarUrl()); webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.member", - logMessageMember.getMember().getAsMention())); + logMessageMember.getMember().getAsMention()).block()); if (!logMessageMember.getAddedRoles().isEmpty() || !logMessageMember.getRemovedRoles().isEmpty()) - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.roles") + ":**", stringBuilder.toString())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.roles").block() + ":**", stringBuilder.toString())); modified = true; } @@ -312,14 +315,14 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (!logMessageRole.isCreated() && !logMessageRole.isDeleted()) { // Set update as Description - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.update", logMessageRole.getCurrentName())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.update", logMessageRole.getCurrentName()).block()); // Check if there is a previous and current Name. if (logMessageRole.getPreviousName() != null && logMessageRole.getCurrentName() != null) { // Add new Fields with Information. - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldName") + "**", logMessageRole.getPreviousName())); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newName") + "**", logMessageRole.getCurrentName())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldName").block() + "**", logMessageRole.getPreviousName())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newName").block() + "**", logMessageRole.getCurrentName())); webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "** **", "** **")); } @@ -327,8 +330,8 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (logMessageRole.isChangedMentioned()) { // Add new Fields with Information. - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldMentionable") + "**", String.valueOf(!logMessageRole.isMentioned()))); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newMentionable") + "**", String.valueOf(logMessageRole.isMentioned()))); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldMentionable").block() + "**", String.valueOf(!logMessageRole.isMentioned()))); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newMentionable").block() + "**", String.valueOf(logMessageRole.isMentioned()))); webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "** **", "** **")); } @@ -336,8 +339,8 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (logMessageRole.isChangedHoisted()) { // Add new Fields with Information. - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldHoist") + "**", String.valueOf(!logMessageRole.isHoisted()))); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newHoist") + "**", String.valueOf(logMessageRole.isHoisted()))); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldHoist").block() + "**", String.valueOf(!logMessageRole.isHoisted()))); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newHoist").block() + "**", String.valueOf(logMessageRole.isHoisted()))); webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "** **", "** **")); } @@ -345,9 +348,9 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (logMessageRole.getPreviousColor() != null || logMessageRole.getCurrentColor() != null) { // Add new Fields with Information. - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldColor") + "**", String.valueOf((logMessageRole.getPreviousColor() != null ? + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldColor").block() + "**", String.valueOf((logMessageRole.getPreviousColor() != null ? logMessageRole.getPreviousColor() : Color.gray).getRGB()))); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newColor") + "**", String.valueOf((logMessageRole.getCurrentColor() != null ? + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newColor").block() + "**", String.valueOf((logMessageRole.getCurrentColor() != null ? logMessageRole.getCurrentColor() : Color.gray).getRGB()))); webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "** **", "** **")); } @@ -385,17 +388,17 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst // Add the String from the StringBuilder as Embed to the Message if (!stringBuilder.toString().isEmpty()) - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newPermissions") + "**", stringBuilder.toString())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newPermissions").block() + "**", stringBuilder.toString())); } else { // Check if the Role has been created. if (logMessageRole.isCreated()) { // Set description to new Role created. - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.create", logMessageRole.getCurrentName())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.create", logMessageRole.getCurrentName()).block()); } else { // Set description to Role deleted. - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.delete", logMessageRole.getCurrentName())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.delete", logMessageRole.getCurrentName()).block()); } } @@ -425,12 +428,12 @@ else if (loggerMessage.getType() == LogTyp.SERVER_LEAVE && loggerMessage instanc loggerMessages instanceof LogMessageUser logMessageUser1 && logMessageUser1.getUser().getIdLong() == logMessageUser.getUser().getIdLong()) .anyMatch(loggerMessages -> loggerMessages.getType() == LogTyp.USER_BAN)) { - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.banned", logMessageUser.getUser().getAsMention())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.banned", logMessageUser.getUser().getAsMention()).block()); logs.stream().filter(logMessage -> logMessage != loggerMessage && logMessage.getId() == loggerMessage.getId() && logMessage instanceof LogMessageUser logMessageUser1 && logMessageUser1.getUser().getIdLong() == logMessageUser.getUser().getIdLong()).forEach(LogMessage::cancel); } else { - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.joined.leave", logMessageUser.getUser().getAsMention())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.joined.leave", logMessageUser.getUser().getAsMention()).block()); } modified = true; @@ -467,7 +470,7 @@ else if (loggerMessage.getType() == LogTyp.SERVER_LEAVE && loggerMessage instanc ThreadUtil.createThread(x -> { // If not canceled, send it. if (!loggerMessage.isCanceled()) { - WebhookUtil.sendWebhook(loggerMessage, loggerMessage.getWebhookMessage(), loggerMessage.getId(), loggerMessage.getAuthCode(), true); + WebhookUtil.sendWebhook(loggerMessage, loggerMessage.getWebhookMessage(), loggerMessage.getId(), loggerMessage.getAuthCode(), WebhookUtil.WebhookTyp.LOG); } // Remove it from the list. diff --git a/src/main/java/de/presti/ree6/logger/events/LogMessageMember.java b/src/main/java/de/presti/ree6/module/logger/events/LogMessageMember.java similarity index 97% rename from src/main/java/de/presti/ree6/logger/events/LogMessageMember.java rename to src/main/java/de/presti/ree6/module/logger/events/LogMessageMember.java index bea7787ea..17d89c2e9 100644 --- a/src/main/java/de/presti/ree6/logger/events/LogMessageMember.java +++ b/src/main/java/de/presti/ree6/module/logger/events/LogMessageMember.java @@ -1,8 +1,8 @@ -package de.presti.ree6.logger.events; +package de.presti.ree6.module.logger.events; import club.minnced.discord.webhook.send.WebhookMessage; -import de.presti.ree6.logger.LogMessage; -import de.presti.ree6.logger.LogTyp; +import de.presti.ree6.module.logger.LogMessage; +import de.presti.ree6.module.logger.LogTyp; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Role; @@ -184,7 +184,7 @@ public void setCurrentName(String currentName) { */ public List getRemovedRoles() { if (removedRoles == null) - return removedRoles = new ArrayList<>(); + removedRoles = new ArrayList<>(); return removedRoles; } @@ -205,7 +205,7 @@ public void setRemovedRoles(List removedRoles) { */ public List getAddedRoles() { if (addedRoles == null) - return addedRoles = new ArrayList<>(); + addedRoles = new ArrayList<>(); return addedRoles; } diff --git a/src/main/java/de/presti/ree6/logger/events/LogMessageRole.java b/src/main/java/de/presti/ree6/module/logger/events/LogMessageRole.java similarity index 99% rename from src/main/java/de/presti/ree6/logger/events/LogMessageRole.java rename to src/main/java/de/presti/ree6/module/logger/events/LogMessageRole.java index f0d94e40a..251f8e385 100644 --- a/src/main/java/de/presti/ree6/logger/events/LogMessageRole.java +++ b/src/main/java/de/presti/ree6/module/logger/events/LogMessageRole.java @@ -1,8 +1,8 @@ -package de.presti.ree6.logger.events; +package de.presti.ree6.module.logger.events; import club.minnced.discord.webhook.send.WebhookMessage; -import de.presti.ree6.logger.LogMessage; -import de.presti.ree6.logger.LogTyp; +import de.presti.ree6.module.logger.LogMessage; +import de.presti.ree6.module.logger.LogTyp; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Role; diff --git a/src/main/java/de/presti/ree6/logger/events/LogMessageUser.java b/src/main/java/de/presti/ree6/module/logger/events/LogMessageUser.java similarity index 89% rename from src/main/java/de/presti/ree6/logger/events/LogMessageUser.java rename to src/main/java/de/presti/ree6/module/logger/events/LogMessageUser.java index bf011fc8f..1272a4571 100644 --- a/src/main/java/de/presti/ree6/logger/events/LogMessageUser.java +++ b/src/main/java/de/presti/ree6/module/logger/events/LogMessageUser.java @@ -1,8 +1,8 @@ -package de.presti.ree6.logger.events; +package de.presti.ree6.module.logger.events; import club.minnced.discord.webhook.send.WebhookMessage; -import de.presti.ree6.logger.LogMessage; -import de.presti.ree6.logger.LogTyp; +import de.presti.ree6.module.logger.LogMessage; +import de.presti.ree6.module.logger.LogTyp; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.User; diff --git a/src/main/java/de/presti/ree6/logger/events/LogMessageVoice.java b/src/main/java/de/presti/ree6/module/logger/events/LogMessageVoice.java similarity index 95% rename from src/main/java/de/presti/ree6/logger/events/LogMessageVoice.java rename to src/main/java/de/presti/ree6/module/logger/events/LogMessageVoice.java index b38dda8d8..fbace4fcb 100644 --- a/src/main/java/de/presti/ree6/logger/events/LogMessageVoice.java +++ b/src/main/java/de/presti/ree6/module/logger/events/LogMessageVoice.java @@ -1,8 +1,8 @@ -package de.presti.ree6.logger.events; +package de.presti.ree6.module.logger.events; import club.minnced.discord.webhook.send.WebhookMessage; -import de.presti.ree6.logger.LogMessage; -import de.presti.ree6.logger.LogTyp; +import de.presti.ree6.module.logger.LogMessage; +import de.presti.ree6.module.logger.LogTyp; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.channel.middleman.AudioChannel; @@ -17,7 +17,7 @@ public class LogMessageVoice extends LogMessage { /** * An instance of the Member Entity. */ - private Member member; + private final Member member; /** * The Audio Channels associated with the Events. diff --git a/src/main/java/de/presti/ree6/module/news/Announcement.java b/src/main/java/de/presti/ree6/module/news/Announcement.java new file mode 100644 index 000000000..3fc8f2e50 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/news/Announcement.java @@ -0,0 +1,11 @@ +package de.presti.ree6.module.news; + +/** + * Announcement entity class to store information about an announcement. + * + * @param id The ID of the announcement. + * @param title The title of the announcement. + * @param content The content of the announcement. + */ +public record Announcement(String id, String title, String content) { +} diff --git a/src/main/java/de/presti/ree6/news/AnnouncementManager.java b/src/main/java/de/presti/ree6/module/news/AnnouncementManager.java similarity index 90% rename from src/main/java/de/presti/ree6/news/AnnouncementManager.java rename to src/main/java/de/presti/ree6/module/news/AnnouncementManager.java index 13606d088..95134e561 100644 --- a/src/main/java/de/presti/ree6/news/AnnouncementManager.java +++ b/src/main/java/de/presti/ree6/module/news/AnnouncementManager.java @@ -1,7 +1,6 @@ -package de.presti.ree6.news; +package de.presti.ree6.module.news; import de.presti.ree6.bot.BotConfig; -import lombok.AccessLevel; import lombok.Getter; import java.util.ArrayList; @@ -13,6 +12,13 @@ */ public class AnnouncementManager { + /** + * Constructor should not be called, since it is a utility class that doesn't need an instance. + */ + private AnnouncementManager() { + throw new IllegalStateException("Utility class"); + } + /** * List of all announcements. */ diff --git a/src/main/java/de/presti/ree6/module/notifications/ISonic.java b/src/main/java/de/presti/ree6/module/notifications/ISonic.java new file mode 100644 index 000000000..fec82eb67 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/ISonic.java @@ -0,0 +1,49 @@ +package de.presti.ree6.module.notifications; + +import de.presti.ree6.module.IManager; +import de.presti.ree6.sql.entities.stats.ChannelStats; + +import java.util.List; + +/** + * Interface for Secure Online Notification Interoperable Class Modules. + */ +public interface ISonic extends IManager { + + default void load(List channelStats) { + load(); + } + void load(); + void run(); + default void unload() { + clear(); + } + + default void add(long identifier) { + add(new SonicIdentifier(String.valueOf(identifier))); + } + + default void add(String identifier) { + add(new SonicIdentifier(identifier)); + } + + default boolean contains(long identifier) { + return getList().stream().anyMatch(x -> x.getIdentifierAsLong() == identifier); + } + + default boolean contains(String identifier) { + return getList().stream().anyMatch(x -> x.getIdentifier().equals(identifier)); + } + + default boolean contains(SonicIdentifier identifier) { + return getList().stream().anyMatch(x -> x.getIdentifier().equals(identifier.getIdentifier())); + } + + default void remove(long identifier) { + remove(get(identifier)); + } + + default void remove(String identifier) { + remove(get(identifier)); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/SonicIdentifier.java b/src/main/java/de/presti/ree6/module/notifications/SonicIdentifier.java new file mode 100644 index 000000000..6a8db249a --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/SonicIdentifier.java @@ -0,0 +1,14 @@ +package de.presti.ree6.module.notifications; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class SonicIdentifier { + private String identifier; + + public long getIdentifierAsLong() { + return Long.parseLong(this.identifier); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java new file mode 100644 index 000000000..f15fa6e5f --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java @@ -0,0 +1,156 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import com.github.instagram4j.instagram4j.actions.feed.FeedIterator; +import com.github.instagram4j.instagram4j.models.media.timeline.TimelineImageMedia; +import com.github.instagram4j.instagram4j.models.media.timeline.TimelineVideoMedia; +import com.github.instagram4j.instagram4j.requests.feed.FeedUserRequest; +import com.github.instagram4j.instagram4j.responses.feed.FeedUserResponse; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.language.LanguageService; +import de.presti.ree6.main.Main; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; + +import java.awt.*; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@Slf4j +public class InstagramSonic implements ISonic { + + ArrayList instagramChannels = new ArrayList<>(); + + @Override + public void load(List channelStats) { + try { + channelStats.stream().map(ChannelStats::getInstagramFollowerChannelUsername).filter(Objects::nonNull).forEach(this::add); + load(); + } catch (Exception exception) { + log.error("Error while loading Instagram data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public void load() { + // Register all Instagram Users. + SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers().subscribe(instagramUsers -> + instagramUsers.forEach(this::add)); + } + + @Override + public List getList() { + return instagramChannels; + } + + @Override + public void run() { + if (!Main.getInstance().getNotifier().getInstagramClient().isLoggedIn()) return; + for (String username : getList().stream().map(SonicIdentifier::getIdentifier).toList()) { + + Main.getInstance().getNotifier().getInstagramClient().actions().users().findByUsername(username).thenAccept(userAction -> { + com.github.instagram4j.instagram4j.models.user.User user = userAction.getUser(); + + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)).subscribe(channelStats -> { + if (!channelStats.isEmpty()) { + for (ChannelStats channelStat : channelStats) { + if (channelStat.getInstagramFollowerChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getInstagramFollowerChannelId()); + + if (guildChannel == null) continue; + + LanguageService.getByGuild(guildChannel.getGuild(), "label.instagramCountName", user.getFollower_count()).subscribe(newName -> { + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + return; + + guildChannel.getManager().setName(newName).queue(); + } + }); + } + } + } + }); + + SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).subscribe(webhooks -> { + if (webhooks.isEmpty()) return; + + if (!user.is_private()) { + FeedIterator iterable = new FeedIterator<>(Main.getInstance().getNotifier().getInstagramClient(), new FeedUserRequest(user.getPk())); + + int limit = 1; + while (iterable.hasNext() && limit-- > 0) { + FeedUserResponse response = iterable.next(); + // Actions here + response.getItems().stream().filter(post -> post.getTaken_at() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(instagramPost -> { + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getUsername(), "https://www.instagram.com/" + user.getUsername())); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Instagram Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + + // Set the rest of the Information. + if (instagramPost instanceof TimelineImageMedia timelineImageMedia) { + webhookEmbedBuilder.setImageUrl(timelineImageMedia.getImage_versions2().getCandidates().get(0).getUrl()); + webhookEmbedBuilder.setDescription(timelineImageMedia.getCaption().getText()); + } else if (instagramPost instanceof TimelineVideoMedia timelineVideoMedia) { + webhookEmbedBuilder.setDescription("[Click here to watch the video](" + timelineVideoMedia.getVideo_versions().get(0).getUrl() + ")"); + } else { + webhookEmbedBuilder.setDescription(user.getUsername() + " just posted something new on Instagram!"); + } + + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + + webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + + webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.setContent(webhook.getMessage() + .replace("%username%", user.getUsername())).build(), webhook, WebhookUtil.WebhookTyp.INSTAGRAM)); + }); + } + } + }); + }).exceptionally(exception -> { + log.error("Could not get Instagram User!", exception); + Sentry.captureException(exception); + return null; + }).join(); + } + } + + @Override + public void remove(SonicIdentifier object) { + if (Main.getInstance().getNotifier().getInstagramClient() == null) return; + if (!contains(object)) return; + + SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", + Map.of("name", object.getIdentifier())).subscribe(channelStats -> { + if (channelStats.isPresent()) return; + + instagramChannels.remove(object); + }); + }); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java new file mode 100644 index 000000000..cb6ec5f66 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java @@ -0,0 +1,237 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import com.apptasticsoftware.rssreader.Channel; +import com.apptasticsoftware.rssreader.Image; +import com.apptasticsoftware.rssreader.Item; +import com.apptasticsoftware.rssreader.module.itunes.ItunesItem; +import com.apptasticsoftware.rssreader.module.itunes.ItunesRssReader; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; + +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +@Slf4j +public class RSSSonic implements ISonic { + + ArrayList rssUrls = new ArrayList<>(); + + @Override + public void load() { + try { + // Register all RSS-Feeds. + SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls().subscribe(rssUrl -> + rssUrl.forEach(this::add)); + } catch (Exception exception) { + log.error("Error while loading RSS data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public List getList() { + return rssUrls; + } + + @Override + public void run() { + Collection urls = getList().stream().map(SonicIdentifier::getIdentifier).toList(); + + /* + * Either switch to RSSHub, YouTubes RSS or stay on API based. + * Issue with RSSHub is that it takes 2 hours to update, because of caching. + * Issue with YouTube is RSS that it takes over 30 minutes to update, because of idk random internal stuff. + * + * ////Collection urls = new ArrayList<>(registeredYouTubeChannels.stream().map(c -> "https://rsshub.app/youtube/channel/" + c).toList()); + * + * Wait till Nitter has fixed their RSS Feeds. Or Twitter finally gets the stick out of their ass and stop limiting simple scraping. 05.07: Twitter still has a stick up their ass and Nitter died because of it. WoW. + * ////urls.addAll(registeredTwitterUsers.stream().map(c -> "https://nitter.net/" + c + "/rss").toList()); + * + * ////urls.addAll(registeredRSSFeeds); + */ + + + List checkedIds = new ArrayList<>(); + + // To support Podcast RSS. + new ItunesRssReader() + .addItemExtension("media:description", Item::setDescription) + .addItemExtension("media:thumbnail", "url", (item, element) -> { + Image image = item.getChannel().getImage().orElse(new Image()); + image.setUrl(element); + item.getChannel().setImage(image); + }).addItemExtension("media:thumbnail", "width", (item, element) -> { + Image image = item.getChannel().getImage().orElse(new Image()); + image.setWidth(Integer.valueOf(element)); + item.getChannel().setImage(image); + }).addItemExtension("media:thumbnail", "height", (item, element) -> { + Image image = item.getChannel().getImage().orElse(new Image()); + image.setHeight(Integer.valueOf(element)); + item.getChannel().setImage(image); + }).addChannelExtension("published", Channel::setPubDate) + .addItemExtension("dc:creator", Item::setAuthor) + .addItemExtension("dc:date", Item::setPubDate) + .addItemExtension("yt:channelId", Item::setAuthor) + .setUserAgent("Ree6Bot/" + BotWorker.getBuild() + " (by Presti)") + .read(urls) + .sorted() + .forEach(item -> { + if (item.getPubDate().isEmpty()) return; + + String typ = "other"; + + if (item.getGuid().isPresent()) { + String guid = item.getGuid().get(); + + if (guid.contains("nitter")) { + typ = "tw"; + } else { + typ = "other"; + } + } + + + OffsetDateTime dateTime = OffsetDateTime.parse(item.getPubDate().orElse(""), DateTimeFormatter.ISO_OFFSET_DATE_TIME); + + OffsetDateTime now = OffsetDateTime.now(); + OffsetDateTime threeMinuteAgo = now.minusMinutes(3); + + if (dateTime.isBefore(threeMinuteAgo)) return; + + if (item.getChannel() != null) { + + String id = ""; + + if (typ.equals("tw")) { + id = item.getChannel().getLink().replace("https://nitter.net/", ""); + } else { + id = item.getChannel().getLink(); + } + + if (checkedIds.contains(id)) { + return; + } + + + if (typ.equals("tw")) { + SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(item.getChannel().getLink().replace("https://nitter.net/", "")).subscribe(webhooks -> { + + if (webhooks.isEmpty()) return; + + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + item.getChannel().getImage().ifPresentOrElse(image -> + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), + URLDecoder.decode(image.getUrl().replace("nitter.net/pic/", ""), StandardCharsets.UTF_8), null)), + () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); + + + webhookEmbedBuilder.setDescription(item.getTitle() + "\n"); + + item.getDescription().ifPresent(description -> { + if (description.contains(" { + String message = webhook.getMessage() + .replace("%name%", item.getChannel().getTitle()); + + if (item.getLink().isPresent()) { + message = message.replace("%url%", item.getLink().get() + .replace("nitter.net", "twitter.com")) + .replace("#m", ""); + } + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.RSS); + }); + }); + } else { + try { + SQLSession.getSqlConnector().getSqlWorker().getRSSWebhooksByUrl(id).subscribe(webhooks -> { + if (webhooks.isEmpty()) return; + + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + item.getChannel().getImage().ifPresentOrElse(image -> + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), + URLDecoder.decode(image.getUrl(), StandardCharsets.UTF_8), null)), + () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); + + item.getDescription().ifPresent(description -> webhookEmbedBuilder.setDescription(description + "\n")); + + if (item instanceof ItunesItem itunesItem) { + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(itunesItem.getItunesTitle().orElse("No Title"), item.getLink().orElse("No Link"))); + itunesItem.getItunesImage().ifPresent(webhookEmbedBuilder::setThumbnailUrl); + } else { + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(item.getTitle().orElse("No Title"), item.getLink().orElse("No Link"))); + } + + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("RSS Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); + + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); + webhookEmbedBuilder.setTimestamp(Instant.now()); + webhookEmbedBuilder.setColor(BotConfig.getMainColor().getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + + webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.RSS)); + }); + } catch (Exception exception) { + Sentry.captureException(exception); + } + } + + checkedIds.add(id); + } + }); + } + + @Override + public void remove(SonicIdentifier object) { + if (!contains(object)) return; + + SQLSession.getSqlConnector().getSqlWorker().getRSSWebhooksByUrl(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + rssUrls.remove(object); + }); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java new file mode 100644 index 000000000..b0e7e2821 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java @@ -0,0 +1,177 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import cn.hutool.core.exceptions.ValidateException; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.main.Main; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import masecla.reddit4j.exceptions.AuthenticationException; +import masecla.reddit4j.objects.RedditPost; +import masecla.reddit4j.objects.Sorting; +import masecla.reddit4j.objects.subreddit.RedditSubreddit; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; + +import java.awt.*; +import java.io.IOException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.*; + +@Slf4j +public class RedditSonic implements ISonic { + + ArrayList subreddits = new ArrayList<>(); + + @Override + public void load(List channelStats) { + try { + channelStats.stream().map(ChannelStats::getSubredditMemberChannelSubredditName).filter(Objects::nonNull).forEach(this::add); + load(); + } catch (Exception exception) { + log.error("Error while loading Reddit data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public void load() { + // Register all Reddit Subreddits. + SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits().subscribe(channel -> + channel.forEach(this::add)); + } + + @Override + public List getList() { + return subreddits; + } + + @Override + public void run() { + try { + for (String subreddit : subreddits.stream().map(SonicIdentifier::getIdentifier).toList()) { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)).subscribe(channelStats -> { + if (!channelStats.isEmpty()) { + RedditSubreddit subredditEntity; + try { + subredditEntity = getSubreddit(subreddit); + } catch (IOException | InterruptedException e) { + return; + } + + for (ChannelStats channelStat : channelStats) { + if (channelStat.getSubredditMemberChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getSubredditMemberChannelId()); + String newName = "Subreddit Members: " + subredditEntity.getActiveUserCount(); + if (guildChannel != null && + !guildChannel.getName().equalsIgnoreCase(newName)) { + + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + continue; + + guildChannel.getManager().setName(newName).queue(); + } + } + } + } + }); + + getSubredditPosts(subreddit, Sorting.NEW, 50).stream().filter(redditPost -> redditPost.getCreated() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(redditPost -> SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).subscribe(webhooks -> { + if (webhooks.isEmpty()) return; + + // Create Webhook Message. + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(redditPost.getTitle(), redditPost.getUrl())); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Reddit Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + + + if (!redditPost.getThumbnail().equalsIgnoreCase("self")) + webhookEmbedBuilder.setImageUrl(redditPost.getThumbnail()); + + // Set rest of the Information. + webhookEmbedBuilder.setDescription(URLDecoder.decode(redditPost.getSelftext(), StandardCharsets.UTF_8)); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Author**", redditPost.getAuthor())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Subreddit**", redditPost.getSubreddit())); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + + webhookEmbedBuilder.setColor(Color.ORANGE.getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%title%", redditPost.getTitle()) + .replace("%author%", redditPost.getAuthor()) + .replace("%name%", redditPost.getSubreddit()) + .replace("%url%", redditPost.getUrl()); + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.REDDIT); + }); + })); + } + } catch (Exception exception) { + log.error("Could not get Reddit Posts!", exception); + Sentry.captureException(exception); + } + } + + /** + * Used to get a Subreddit. + * + * @param subreddit the Name of the Subreddit. + * @return the Subreddit. + * @throws IOException if the Subreddit couldn't be found. + * @throws InterruptedException if the Thread was interrupted. + */ + public RedditSubreddit getSubreddit(String subreddit) throws IOException, InterruptedException { + return Main.getInstance().getNotifier().getRedditClient().getSubreddit(subreddit); + } + + + public List getSubredditPosts(String subreddit, Sorting sorting, int limit) throws AuthenticationException, IOException, InterruptedException { + try { + return Main.getInstance().getNotifier().getRedditClient().getSubredditPosts(subreddit, sorting).limit(limit).submit(); + } catch (ValidateException exception) { + if (exception.getMessage().startsWith("The parameter")) { + Main.getInstance().getNotifier().getRedditClient().userlessConnect(); + return Main.getInstance().getNotifier().getRedditClient().getSubredditPosts(subreddit, sorting).limit(limit).submit(); + } + } + + return Collections.emptyList(); + } + + @Override + public void remove(SonicIdentifier object) { + if (Main.getInstance().getNotifier().getRedditClient() == null) return; + if (!contains(object)) return; + + SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", + Map.of("name", object.getIdentifier())).subscribe(channelStats -> { + if (channelStats.isPresent()) return; + + subreddits.remove(object); + }); + }); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java new file mode 100644 index 000000000..a2e633940 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -0,0 +1,146 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import de.presti.ree6.sql.entities.webhook.WebhookSpotify; +import de.presti.ree6.utils.apis.SpotifyAPIHandler; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import se.michaelthelin.spotify.model_objects.specification.AlbumSimplified; +import se.michaelthelin.spotify.model_objects.specification.ArtistSimplified; +import se.michaelthelin.spotify.model_objects.specification.EpisodeSimplified; + +import java.awt.*; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Slf4j +public class SpotifySonic implements ISonic { + ArrayList spotifyEntries = new ArrayList<>(); + + SimpleDateFormat spotifyTimestamp = new SimpleDateFormat("yyyy-MM-dd"); + + @Override + public void load(List channelStats) { + load(); + // No need for this. + } + + @Override + public void load() { + // Register all Spotify artists and podcasts. + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new WebhookSpotify(), "FROM WebhookSpotify", Map.of()).subscribe(spotifyNotify -> spotifyNotify.forEach(x -> { + if (x.getEntityTyp() == 0) { + add("art:" + x.getEntityId()); + } else { + add("pot:" + x.getEntityId()); + } + })); + } + + @Override + public List getList() { + return spotifyEntries; + } + + @Override + public void run() { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new WebhookSpotify(), "FROM WebhookSpotify", Map.of()).subscribe(spotifyNotify -> { + Date yesterday = Date.from(Instant.now().minus(1, ChronoUnit.DAYS)); + for (String entry : spotifyEntries.stream().map(SonicIdentifier::getIdentifier).toList()) { + String actualId = entry.substring(entry.lastIndexOf(':') + 1); + try { + if (entry.startsWith("art")) { + ArrayList albums = SpotifyAPIHandler.getInstance().getArtistAlbums(actualId); + if (albums.isEmpty()) return; + AlbumSimplified album = albums.get(0); + if (album == null) return; + if (album.getReleaseDatePrecision().precision.equals("year")) continue; + if (album.getReleaseDatePrecision().precision.equals("month")) continue; + + Date date = spotifyTimestamp.parse(album.getReleaseDate()); + + if (date.after(yesterday)) { + ArtistSimplified artistSimplified = album.getArtists()[0]; + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(artistSimplified.getName(), artistSimplified.getHref())); + webhookEmbedBuilder.setImageUrl(album.getImages()[0].getUrl()); + + sendWebhooks(webhookEmbedBuilder, album.getName(), artistSimplified.getName(), album.getHref(), spotifyNotify); + } + } else { + ArrayList episodes = SpotifyAPIHandler.getInstance().getPodcastEpisodes(actualId); + if (episodes.isEmpty()) continue; + EpisodeSimplified episode = episodes.get(0); + if (episode == null) continue; + if (episode.getReleaseDatePrecision().precision.equals("year")) continue; + if (episode.getReleaseDatePrecision().precision.equals("month")) continue; + + Date date = spotifyTimestamp.parse(episode.getReleaseDate()); + + if (date.after(yesterday)) { + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(episode.getName(), episode.getHref())); + webhookEmbedBuilder.setImageUrl(episode.getImages()[0].getUrl()); + + sendWebhooks(webhookEmbedBuilder, episode.getDescription(), episode.getName(), episode.getHref(), spotifyNotify); + } + } + } catch (Exception exception) { + Sentry.captureException(exception); + } + } + }); + } + + public void sendWebhooks(WebhookEmbedBuilder webhookEmbed, String description, String authorName, String redirect, List webhooks) { + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + + webhookEmbed.setAuthor(new WebhookEmbed.EmbedAuthor("Spotify Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + webhookEmbed.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + webhookEmbed.setColor(Color.GREEN.getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbed.build()); + + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%description%", description) + .replace("%author%", authorName) + .replace("%name%", authorName) + .replace("%url%", redirect); + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.SPOTIFY); + }); + } + + @Override + public void remove(SonicIdentifier object) { + if (SpotifyAPIHandler.getInstance() == null) return; + if (!contains(object)) return; + String actualId = object.getIdentifier(); + actualId = actualId.substring(actualId.lastIndexOf(':') + 1); + + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new WebhookSpotify(), "FROM WebhookSpotify WHERE entityId=:id", Map.of("id", actualId)).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + spotifyEntries.remove(object); + }); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java new file mode 100644 index 000000000..5afac9e98 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java @@ -0,0 +1,122 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.wrapper.tiktok.TikTokWrapper; +import de.presti.wrapper.tiktok.entities.TikTokUser; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import org.jsoup.HttpStatusException; + +import java.awt.*; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +public class TikTokSonic implements ISonic { + + ArrayList tiktokChannels = new ArrayList<>(); + + @Override + public void load() { + try { + // Register all TikTok Users. + SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames().subscribe(tiktokNames -> + tiktokNames.forEach(this::add)); + } catch (Exception exception) { + log.error("Error while loading TikTok data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public List getList() { + return tiktokChannels; + } + + @Override + public void run() { + for (long id : getList().stream().map(SonicIdentifier::getIdentifierAsLong).toList()) { + try { + TikTokUser user = TikTokWrapper.getUser(id); + + SQLSession.getSqlConnector().getSqlWorker().getTikTokWebhooksByName(user.getId()).subscribe(webhooks -> { + if (webhooks.isEmpty()) { + return; + } + + AtomicInteger limit = new AtomicInteger(); + + user.getPosts().forEach(post -> { + if (limit.get() > 3) return; + + if (post.getCreationTime() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())) { + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getDisplayName(), "https://www.tiktok.com/@" + user.getName())); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("TikTok Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + + // Set rest of the Information. + if (post.getCover() != null) { + webhookEmbedBuilder.setImageUrl(post.getCover().getMediumUrl()); + webhookEmbedBuilder.setDescription("[Click here to watch the video](https://tiktok.com/share/video/" + post.getId() + ")"); + } else { + webhookEmbedBuilder.setDescription(user.getDisplayName() + " just posted something new on TikTok!"); + } + + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + + webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%description%", post.getDescription()) + .replace("%author%", user.getName()) + .replace("%name%", user.getDisplayName()) + .replace("%url%", "https://tiktok.com/share/video/" + post.getId()); + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.TIKTOK); + }); + } + limit.incrementAndGet(); + }); + }); + } catch (IOException e) { + if (e instanceof HttpStatusException httpStatusException && httpStatusException.getStatusCode() == 404) { + // TODO:: check, maybe delete on 404? + return; + } + + Sentry.captureException(e); + } + } + } + + @Override + public void remove(SonicIdentifier object) { + if (!contains(object)) return; + + SQLSession.getSqlConnector().getSqlWorker().getTikTokWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + tiktokChannels.remove(object); + }); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java new file mode 100644 index 000000000..275e00a9c --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java @@ -0,0 +1,179 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import club.minnced.discord.webhook.send.component.button.Button; +import club.minnced.discord.webhook.send.component.layout.ActionRow; +import com.github.twitch4j.events.ChannelFollowCountUpdateEvent; +import com.github.twitch4j.events.ChannelGoLiveEvent; +import com.github.twitch4j.helix.domain.GameList; +import com.github.twitch4j.helix.domain.User; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.language.LanguageService; +import de.presti.ree6.main.Main; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; + +import java.awt.*; +import java.util.List; +import java.util.*; + +@Slf4j +public class TwitchSonic implements ISonic { + + ArrayList twitchChannels = new ArrayList<>(); + + @Override + public void load(List channelStats) { + try { + channelStats.stream().map(ChannelStats::getTwitchFollowerChannelUsername).filter(Objects::nonNull).forEach(this::add); + load(); + } catch (Exception exception) { + log.error("Error while loading Twitch data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public void load() { + // Register all Twitch Channels. + SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames().subscribe(channel -> + channel.forEach(this::add)); + // Register the Event-handler. + run(); + } + + @Override + public List getList() { + return twitchChannels; + } + + @Override + public void run() { + Main.getInstance().getNotifier().getTwitchClient().getEventManager().onEvent(ChannelGoLiveEvent.class, channelGoLiveEvent -> SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(channelGoLiveEvent.getChannel().getName()).subscribe(webhooks -> { + if (webhooks.isEmpty()) { + return; + } + + String twitchUrl = "https://twitch.tv/" + channelGoLiveEvent.getChannel().getName(); + + // Create a Webhook Message. + WebhookMessageBuilder wmb = new WebhookMessageBuilder(); + + wmb.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); + wmb.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(channelGoLiveEvent.getStream().getUserName(), twitchUrl)); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Twitch Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); + + // Try getting the User. + Optional twitchUserRequest = Main.getInstance().getNotifier().getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(channelGoLiveEvent.getStream().getUserName())).execute().getUsers().stream().findFirst(); + if (twitchUserRequest.isPresent()) { + webhookEmbedBuilder.setThumbnailUrl(twitchUserRequest.orElseThrow().getProfileImageUrl()); + } + + // Set rest of the Information. + webhookEmbedBuilder.setDescription("**" + channelGoLiveEvent.getStream().getTitle() + "**"); + GameList gameList = Main.getInstance().getNotifier().getTwitchClient().getClientHelper().getTwitchHelix().getGames(null, List.of(channelGoLiveEvent.getStream().getGameId()), null, null).execute(); + if (!gameList.getGames().isEmpty()) { + webhookEmbedBuilder.setThumbnailUrl(gameList.getGames().get(0).getBoxArtUrl()); + } + + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(channelGoLiveEvent.getStream().getUserName(), twitchUserRequest.map(User::getProfileImageUrl).orElse(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()), twitchUrl)); + webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrlTemplate()); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(channelGoLiveEvent.getStream().getGameName(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); + webhookEmbedBuilder.setColor(Color.MAGENTA.darker().getRGB()); + + wmb.addComponents(ActionRow.of(new Button(Button.Style.LINK, twitchUrl).setLabel(twitchUserRequest.isPresent() ? twitchUserRequest.get().getDisplayName() : "Watch Stream"))); + wmb.addEmbeds(webhookEmbedBuilder.build()); + + // Go through every Webhook that is registered for the Twitch Channel + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%name%", channelGoLiveEvent.getStream().getUserName()) + .replace("%url%", twitchUrl); + wmb.setContent(message); + WebhookUtil.sendWebhook(wmb.build(), webhook, WebhookUtil.WebhookTyp.TWITCH); + }); + })); + + Main.getInstance().getNotifier().getTwitchClient().getEventManager().onEvent(ChannelFollowCountUpdateEvent.class, channelFollowCountUpdateEvent -> SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE LOWER(twitchFollowerChannelUsername) = :name", + Map.of("name", channelFollowCountUpdateEvent.getChannel().getName().toLowerCase())).subscribe(channelStats -> { + if (!channelStats.isEmpty()) { + for (ChannelStats channelStat : channelStats) { + if (channelStat.getTwitchFollowerChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); + if (guildChannel != null) { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + continue; + + LanguageService.getByGuild(guildChannel.getGuild(), "label.twitchCountName", channelFollowCountUpdateEvent.getFollowCount()).subscribe(newName -> { + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + guildChannel.getManager().setName(newName).queue(); + } + }); + } + } + } + } + })); + } + + @Override + public void unload() { + twitchChannels.forEach(channel -> { + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().disableStreamEventListener(channel.getIdentifier()); + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().disableFollowEventListener(channel.getIdentifier()); + }); + } + + @Override + public void add(SonicIdentifier object) { + if (Main.getInstance().getNotifier().getTwitchClient() == null) return; + if (contains(object)) return; + + String twitchChannel = object.getIdentifier().toLowerCase(); + + twitchChannels.add(new SonicIdentifier(twitchChannel)); + + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().enableStreamEventListener(twitchChannel); + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().enableFollowEventListener(twitchChannel); + } + + @Override + public boolean contains(String identifier) { + return ISonic.super.contains(identifier.toLowerCase()); + } + + @Override + public void remove(SonicIdentifier object) { + if (Main.getInstance().getNotifier().getTwitchClient() == null) return; + + String twitchChannel = object.getIdentifier().toLowerCase(); + + SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(twitchChannel).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitchFollowerChannelUsername=:name", Map.of("name", twitchChannel)) + .subscribe(channelStats -> { + if (channelStats.isPresent()) return; + + twitchChannels.remove(object); + + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().disableStreamEventListener(twitchChannel); + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().disableFollowEventListener(twitchChannel); + }); + }); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TwitterSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TwitterSonic.java new file mode 100644 index 000000000..782ff3f2e --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TwitterSonic.java @@ -0,0 +1,96 @@ +package de.presti.ree6.module.notifications.impl; + +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.language.LanguageService; +import de.presti.ree6.main.Main; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import io.github.redouane59.twitter.dto.user.UserV2; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; + +import java.util.*; + +@Slf4j +public class TwitterSonic implements ISonic { + + ArrayList twitterChannels = new ArrayList<>(); + + @Override + public void load(List channelStats) { + try { + channelStats.stream().map(ChannelStats::getTwitterFollowerChannelUsername).filter(Objects::nonNull).forEach(this::add); + load(); + } catch (Exception exception) { + log.error("Error while loading Twitter data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public void load() { + // Register all Twitter Users. + SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames().subscribe(twitterNames -> + twitterNames.forEach(this::add)); + } + + @Override + public List getList() { + return twitterChannels; + } + + @Override + public void run() { + for (String twitterName : getList().stream().map(SonicIdentifier::getIdentifier).toList()) { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", twitterName)).subscribe(channelStats -> { + if (!channelStats.isEmpty()) { + UserV2 twitterUser; + try { + twitterUser = Main.getInstance().getNotifier().getTwitterClient().getUserFromUserName(twitterName); + } catch (NoSuchElementException e) { + return; + } + + if (twitterUser.getData() == null) return; + + for (ChannelStats channelStat : channelStats) { + if (channelStat.getTwitterFollowerChannelUsername() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); + if (guildChannel == null) continue; + + LanguageService.getByGuild(guildChannel.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).subscribe(newName -> { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + return; + + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + guildChannel.getManager().setName(newName).queue(); + } + }); + } + } + } + }); + } + } + + @Override + public void remove(SonicIdentifier object) { + if (Main.getInstance().getNotifier().getTwitterClient() == null) return; + if (!contains(object)) return; + + SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", + Map.of("name", object.getIdentifier())).subscribe(channelStats -> { + if (channelStats.isPresent()) return; + + twitterChannels.remove(object); + }); + }); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java new file mode 100644 index 000000000..bbbeb6cde --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java @@ -0,0 +1,163 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.language.LanguageService; +import de.presti.ree6.main.Main; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import de.presti.ree6.utils.apis.YouTubeAPIHandler; +import de.presti.wrapper.entities.VideoResult; +import de.presti.wrapper.entities.channel.ChannelResult; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; + +import java.awt.*; +import java.time.Duration; +import java.util.List; +import java.util.*; + +@Slf4j +public class YouTubeSonic implements ISonic { + ArrayList youtubeChannels = new ArrayList<>(); + + @Override + public void load(List channelStats) { + try { + channelStats.stream().map(ChannelStats::getYoutubeSubscribersChannelUsername).filter(Objects::nonNull).forEach(this::add); + load(); + } catch (Exception exception) { + log.error("Error while loading YouTube data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public void load() { + // Register all YouTube channels. + SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels().subscribe(channel -> + channel.forEach(this::add)); + } + + @Override + public List getList() { + return youtubeChannels; + } + + @Override + public void run() { + for (String channel : getList().stream().map(SonicIdentifier::getIdentifier).toList()) { + SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(channel).subscribe(webhooks -> { + if (!webhooks.isEmpty()) { + try { + List playlistItemList = YouTubeAPIHandler.getInstance().getYouTubeUploads(channel); + if (!playlistItemList.isEmpty()) { + for (VideoResult playlistItem : playlistItemList) { + + Main.getInstance().logAnalytic("Video: " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate() + " | " + playlistItem.getTimeAgo()); + Main.getInstance().logAnalytic("Current: " + System.currentTimeMillis() + " | " + (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis()) + " | " + + (playlistItem.getActualUploadDate() != null && playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) + " | " + (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())); + + if (playlistItem.getUploadDate() != -1 && (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis() || + (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())) && + playlistItem.getActualUploadDate() != null && !playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) { + + Main.getInstance().logAnalytic("Passed! -> " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate()); + // Create a Webhook Message. + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(playlistItem.getOwnerName(), null)); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("YouTube Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + + webhookEmbedBuilder.setImageUrl(playlistItem.getThumbnail()); + + webhookEmbedBuilder.setDescription("[**" + playlistItem.getTitle() + "**](https://www.youtube.com/watch?v=" + playlistItem.getId() + ")"); + + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + webhookEmbedBuilder.setColor(Color.RED.getRGB()); + + webhooks.forEach(webhook -> { + String message = webhook.getMessage().replace("%name%", playlistItem.getOwnerName()) + .replace("%title%", playlistItem.getTitle()) + .replace("%description%", playlistItem.getDescriptionSnippet() != null ? "No Description" : playlistItem.getDescriptionSnippet()) + .replace("%url%", "https://www.youtube.com/watch?v=" + playlistItem.getId()); + + webhookMessageBuilder.setContent(message); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.YOUTUBE); + }); + + break; + } + } + } + } catch (Exception exception) { + Sentry.captureException(exception); + log.error("Couldn't get user data of " + channel + "!", exception); + } + } + }); + + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", channel)).subscribe(channelStats -> { + if (!channelStats.isEmpty()) { + ChannelResult youTubeChannel; + try { + youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelById(channel); + } catch (Exception e) { + Sentry.captureException(e); + return; + } + + if (youTubeChannel == null) return; + + for (ChannelStats channelStat : channelStats) { + if (channelStat.getYoutubeSubscribersChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getYoutubeSubscribersChannelId()); + + if (guildChannel == null) continue; + + LanguageService.getByGuild(guildChannel.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).subscribe(newName -> { + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + return; + + guildChannel.getManager().setName(newName).queue(); + } + }); + } + } + } + }); + } + } + + @Override + public void remove(SonicIdentifier object) { + if (YouTubeAPIHandler.getInstance() == null) return; + if (!contains(object)) return; + + SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", + Map.of("name", object.getIdentifier())).subscribe(channelStats -> { + if (channelStats.isPresent()) return; + + youtubeChannels.remove(object); + }); + }); + } +} diff --git a/src/main/java/de/presti/ree6/news/Announcement.java b/src/main/java/de/presti/ree6/news/Announcement.java deleted file mode 100644 index 7a9094446..000000000 --- a/src/main/java/de/presti/ree6/news/Announcement.java +++ /dev/null @@ -1,39 +0,0 @@ -package de.presti.ree6.news; - -/** - * Announcement entity class to store information about an announcement. - * - * @param id The ID of the announcement. - * @param title The title of the announcement. - * @param content The content of the announcement. - */ -public record Announcement(String id, String title, String content) { - - /** - * Get the ID of the announcement. - * @return The ID of the announcement. - */ - @Override - public String id() { - return id; - } - - /** - * Get the title of the announcement. - * - * @return The title of the announcement. - */ - @Override - public String title() { - return title; - } - - /** - * Get the content of the announcement. - * @return The content of the announcement. - */ - @Override - public String content() { - return content; - } -} diff --git a/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java b/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java index 4ac8f8b02..cfbd2a74b 100644 --- a/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java +++ b/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java @@ -79,7 +79,7 @@ public static String getResponse(Member member, String message) { response = getResponse(messages); } catch (BizException e) { Sentry.captureException(e); - return LanguageService.getByGuild(member.getGuild(), "message.default.retrievalError"); + return LanguageService.getByGuild(member.getGuild(), "message.default.retrievalError").block(); } messages.add(new Message("assistant", response)); diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 5b3f2e748..ebb05227c 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -1,20 +1,6 @@ package de.presti.ree6.utils.apis; -import club.minnced.discord.webhook.send.WebhookEmbed; -import club.minnced.discord.webhook.send.WebhookEmbedBuilder; -import club.minnced.discord.webhook.send.WebhookMessageBuilder; -import cn.hutool.core.exceptions.ValidateException; -import com.apptasticsoftware.rssreader.Channel; -import com.apptasticsoftware.rssreader.Image; -import com.apptasticsoftware.rssreader.Item; -import com.apptasticsoftware.rssreader.module.itunes.ItunesItem; -import com.apptasticsoftware.rssreader.module.itunes.ItunesRssReader; import com.github.instagram4j.instagram4j.IGClient; -import com.github.instagram4j.instagram4j.actions.feed.FeedIterator; -import com.github.instagram4j.instagram4j.models.media.timeline.TimelineImageMedia; -import com.github.instagram4j.instagram4j.models.media.timeline.TimelineVideoMedia; -import com.github.instagram4j.instagram4j.requests.feed.FeedUserRequest; -import com.github.instagram4j.instagram4j.responses.feed.FeedUserResponse; import com.github.instagram4j.instagram4j.utils.IGChallengeUtils; import com.github.philippheuer.credentialmanager.CredentialManager; import com.github.philippheuer.credentialmanager.CredentialManagerBuilder; @@ -24,31 +10,19 @@ import com.github.twitch4j.auth.TwitchAuth; import com.github.twitch4j.auth.providers.TwitchIdentityProvider; import com.github.twitch4j.chat.events.channel.FollowEvent; -import com.github.twitch4j.events.ChannelFollowCountUpdateEvent; -import com.github.twitch4j.events.ChannelGoLiveEvent; import com.github.twitch4j.eventsub.events.ChannelSubscribeEvent; -import com.github.twitch4j.helix.domain.User; import com.github.twitch4j.pubsub.PubSubSubscription; import com.github.twitch4j.pubsub.events.RewardRedeemedEvent; -import de.presti.ree6.actions.streamtools.container.StreamActionContainer; -import de.presti.ree6.actions.streamtools.container.StreamActionContainerCreator; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; -import de.presti.ree6.bot.util.WebhookUtil; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; +import de.presti.ree6.module.actions.streamtools.container.StreamActionContainerCreator; +import de.presti.ree6.module.notifications.impl.*; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.TwitchIntegration; -import de.presti.ree6.sql.entities.stats.ChannelStats; -import de.presti.ree6.sql.entities.webhook.*; -import de.presti.ree6.utils.data.DatabaseStorageBackend; +import de.presti.ree6.utils.oauth.DatabaseStorageBackend; import de.presti.ree6.utils.others.ThreadUtil; -import de.presti.wrapper.entities.VideoResult; -import de.presti.wrapper.entities.channel.ChannelResult; -import de.presti.wrapper.tiktok.TikTokWrapper; -import de.presti.wrapper.tiktok.entities.TikTokUser; import io.github.redouane59.twitter.TwitterClient; -import io.github.redouane59.twitter.dto.user.UserV2; import io.github.redouane59.twitter.signature.TwitterCredentials; import io.sentry.Sentry; import lombok.AccessLevel; @@ -56,27 +30,11 @@ import lombok.extern.slf4j.Slf4j; import masecla.reddit4j.client.Reddit4J; import masecla.reddit4j.exceptions.AuthenticationException; -import masecla.reddit4j.objects.RedditPost; -import masecla.reddit4j.objects.Sorting; -import masecla.reddit4j.objects.subreddit.RedditSubreddit; -import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; -import org.jsoup.HttpStatusException; -import java.awt.*; -import java.io.IOException; -import java.net.URLDecoder; -import java.nio.charset.StandardCharsets; import java.time.Duration; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.List; -import java.util.*; +import java.util.HashMap; +import java.util.Scanner; import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; - -// TODO:: translate -// TODO:: fix the Twitter Stream handler, wait for responses via https://github.com/redouane59/twittered/issues/447 /** * Utility class used for Event Notifiers. Such as Twitch Livestream, YouTube Upload or Twitter Tweet. @@ -121,52 +79,67 @@ public class Notifier { private IGClient instagramClient; /** - * Local list of registered Twitch Channels. + * Instance of the YouTube Sonic Manager. */ - private final ArrayList registeredTwitchChannels = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private YouTubeSonic youTubeSonic; /** - * A list with all the Twitch Subscription for the Streaming Tools. + * Instance of the Twitch Sonic Manager. */ @Getter(AccessLevel.PUBLIC) - private final HashMap twitchSubscription = new HashMap<>(); + private TwitchSonic twitchSonic; /** - * Local list of registered YouTube Channels. + * Instance of the Instagram Sonic Manager. */ - private final ArrayList registeredYouTubeChannels = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private InstagramSonic instagramSonic; + /** - * Local list of registered Twitter Users. + * Instance of the TikTok Sonic Manager. */ - private final ArrayList registeredTwitterUsers = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private TikTokSonic tikTokSonic; /** - * Local list of registered Subreddits. + * Instance of the Twitter Sonic Manager. */ - private final ArrayList registeredSubreddits = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private TwitterSonic twitterSonic; /** - * Local list of registered Instagram Users. + * Instance of the Reddit Sonic Manager. */ - private final ArrayList registeredInstagramUsers = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private RedditSonic redditSonic; /** - * Local list of registered RSS-Feeds. + * Instance of the RSS Sonic Manager. */ - private final ArrayList registeredRSSFeeds = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private RSSSonic rssSonic; /** - * Local list of registered TikTok Users. + * Instance of the Spotify Sonic Manager. */ - private final ArrayList registeredTikTokUsers = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private SpotifySonic spotifySonic; /** - * Constructor used to created instance of the API Clients. + * A list with all the Twitch Subscription for the Streaming Tools. + */ + @Getter(AccessLevel.PUBLIC) + private final HashMap twitchSubscription = new HashMap<>(); + + /** + * Constructor used to create instance of the API Clients. */ public Notifier() { if (!BotConfig.isModuleActive("notifier")) return; log.info("Initializing Twitch Client..."); + twitchSonic = new TwitchSonic(); try { credentialManager = CredentialManagerBuilder.builder() .withStorageBackend(new DatabaseStorageBackend()) @@ -186,65 +159,57 @@ public Notifier() { .withCredentialManager(credentialManager) .build(); - for (TwitchIntegration twitchIntegrations : - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null)) { - - OAuth2Credential credential = new OAuth2Credential("twitch", twitchIntegrations.getToken()); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null).subscribe(twitchIntegrations -> { + for (TwitchIntegration twitchIntegration : twitchIntegrations) { + OAuth2Credential credential = new OAuth2Credential("twitch", twitchIntegration.getToken()); - PubSubSubscription[] subscriptions = new PubSubSubscription[2]; - subscriptions[0] = getTwitchClient().getPubSub().listenForChannelPointsRedemptionEvents(credential, twitchIntegrations.getChannelId()); - subscriptions[1] = getTwitchClient().getPubSub().listenForSubscriptionEvents(credential, twitchIntegrations.getChannelId()); + PubSubSubscription[] subscriptions = new PubSubSubscription[2]; + subscriptions[0] = getTwitchClient().getPubSub().listenForChannelPointsRedemptionEvents(credential, twitchIntegration.getChannelId()); + subscriptions[1] = getTwitchClient().getPubSub().listenForSubscriptionEvents(credential, twitchIntegration.getChannelId()); - getTwitchClient().getClientHelper().enableFollowEventListener(twitchIntegrations.getChannelId()); + getTwitchClient().getClientHelper().enableFollowEventListener(twitchIntegration.getChannelId()); - twitchSubscription.put(credential.getUserId(), subscriptions); - } + twitchSubscription.put(credential.getUserId(), subscriptions); + } + }); - twitchClient.getEventManager().onEvent(RewardRedeemedEvent.class, event -> { - List list = StreamActionContainerCreator.getContainers(0); - list.forEach(container -> { - if (!event.getRedemption().getChannelId().equalsIgnoreCase(container.getTwitchChannelId())) return; + twitchClient.getEventManager().onEvent(RewardRedeemedEvent.class, event -> StreamActionContainerCreator.getContainers(0).subscribe(list -> list.forEach(container -> { + if (!event.getRedemption().getChannelId().equalsIgnoreCase(container.getTwitchChannelId())) + return; - if (container.getExtraArgument() == null || event.getRedemption().getReward().getId().equals(container.getExtraArgument())) { - container.runActions(event, event.getRedemption().getUserInput()); - } - }); - }); + if (container.getExtraArgument() == null || event.getRedemption().getReward().getId().equals(container.getExtraArgument())) { + container.runActions(event, event.getRedemption().getUserInput()); + } + }))); - twitchClient.getEventManager().onEvent(FollowEvent.class, event -> { - List list = StreamActionContainerCreator.getContainers(1); - list.forEach(container -> { - if (!event.getChannel().getId().equalsIgnoreCase(container.getTwitchChannelId())) return; + twitchClient.getEventManager().onEvent(FollowEvent.class, event -> StreamActionContainerCreator.getContainers(1).subscribe(list -> list.forEach(container -> { + if (!event.getChannel().getId().equalsIgnoreCase(container.getTwitchChannelId())) return; - container.runActions(event, event.getUser().getName()); - }); - }); + container.runActions(event, event.getUser().getName()); + }))); - twitchClient.getEventManager().onEvent(ChannelSubscribeEvent.class, event -> { - List list = StreamActionContainerCreator.getContainers(2); - list.forEach(container -> { - if (!event.getBroadcasterUserId().equalsIgnoreCase(container.getTwitchChannelId())) return; + twitchClient.getEventManager().onEvent(ChannelSubscribeEvent.class, event -> StreamActionContainerCreator.getContainers(2).subscribe(list -> list.forEach(container -> { + if (!event.getBroadcasterUserId().equalsIgnoreCase(container.getTwitchChannelId())) return; - container.runActions(null, event.getUserName()); - }); - }); + container.runActions(null, event.getUserName()); + }))); } catch (Exception exception) { Sentry.captureException(exception); log.error("Failed to create Twitch Client.", exception); } - log.info("Initializing Twitter Client..."); - try { + log.info("Initializing Twitter Client..."); + twitterSonic = new TwitterSonic(); twitterClient = new TwitterClient(TwitterCredentials.builder() .bearerToken(Main.getInstance().getConfig().getConfiguration().getString("twitter.bearer")).build()); } catch (Exception exception) { log.error("Failed to create Twitter Client.", exception); } - log.info("Initializing Reddit Client..."); - try { + log.info("Initializing Reddit Client..."); + redditSonic = new RedditSonic(); redditClient = Reddit4J .rateLimited() .setClientId(Main.getInstance().getConfig().getConfiguration().getString("reddit.client.id")) @@ -252,7 +217,6 @@ public Notifier() { .setUserAgent("Ree6Bot/" + BotWorker.getBuild() + " (by /u/PrestiSchmesti)"); redditClient.userlessConnect(); - createRedditPostStream(); } catch (Exception exception) { if (exception instanceof AuthenticationException) { log.warn("Reddit Credentials are invalid, you can ignore this if you don't use Reddit."); @@ -261,1071 +225,122 @@ public Notifier() { Sentry.captureException(exception); } } - - log.info("Initializing Instagram Client..."); - - // Callable that returns inputted code from System.in - Callable inputCode = () -> { - Scanner scanner = new Scanner(System.in); - log.error("Please input code: "); - String code = scanner.nextLine(); - scanner.close(); - return code; - }; - - // handler for challenge login - IGClient.Builder.LoginHandler challengeHandler = (client, response) -> IGChallengeUtils.resolveChallenge(client, response, inputCode); - - instagramClient = IGClient.builder() - .username(Main.getInstance().getConfig().getConfiguration().getString("instagram.username")) - .password(Main.getInstance().getConfig().getConfiguration().getString("instagram.password")) - .onChallenge(challengeHandler).build(); - - instagramClient.sendLoginRequest().exceptionally(throwable -> { - if (BotConfig.isDebug()) { - log.error("Failed to login to Instagram API, you can ignore this if you don't use Instagram.", throwable); - } else { - log.error("Failed to login to Instagram API, you can ignore this if you don't use Instagram."); - log.error("Error Message: " + throwable.getMessage() - .replace("com.github.instagram4j.instagram4j.exceptions.IGResponseException: ", "") - .replace("'", "'")); - } - return null; - }); - createInstagramPostStream(); - - log.info("Initializing Streams..."); - - log.info("Creating YouTube Streams..."); - createYTStream(); - - log.info("Creating Twitter Streams..."); - ThreadUtil.createThread(x -> { - for (String twitterName : registeredTwitterUsers) { - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", twitterName)); - if (!channelStats.isEmpty()) { - UserV2 twitterUser; - try { - twitterUser = Main.getInstance().getNotifier().getTwitterClient().getUserFromUserName(twitterName); - } catch (NoSuchElementException e) { - continue; - } - - if (twitterUser.getData() == null) continue; - - for (ChannelStats channelStat : channelStats) { - if (channelStat.getTwitterFollowerChannelUsername() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); - if (guildChannel == null) continue; - String newName = LanguageService.getByGuild(guildChannel.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()); - - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; - - if (!guildChannel.getName().equalsIgnoreCase(newName)) { - guildChannel.getManager().setName(newName).queue(); - } - } - } + try { + log.info("Initializing Instagram Client..."); + instagramSonic = new InstagramSonic(); + // Callable that returns inputted code from System.in + Callable inputCode = () -> { + Scanner scanner = new Scanner(System.in); + log.error("Please input code: "); + String code = scanner.nextLine(); + scanner.close(); + return code; + }; + + // handler for challenge login + IGClient.Builder.LoginHandler challengeHandler = (client, response) -> IGChallengeUtils.resolveChallenge(client, response, inputCode); + + instagramClient = IGClient.builder() + .username(Main.getInstance().getConfig().getConfiguration().getString("instagram.username")) + .password(Main.getInstance().getConfig().getConfiguration().getString("instagram.password")) + .onChallenge(challengeHandler).build(); + + instagramClient.sendLoginRequest().exceptionally(throwable -> { + if (BotConfig.isDebug()) { + log.error("Failed to login to Instagram API, you can ignore this if you don't use Instagram.", throwable); + } else { + log.error("Failed to login to Instagram API, you can ignore this if you don't use Instagram."); + log.error("Error Message: {}", throwable.getMessage() + .replace("com.github.instagram4j.instagram4j.exceptions.IGResponseException: ", "") + .replace("'", "'")); } - } - }, x -> { - log.error("Failed to run Twitter Follower count checker!", x); - Sentry.captureException(x); - }, Duration.ofMinutes(5), true, true); - - log.info("Creating RSS Streams..."); - createRssStream(); - - log.info("Creating TikTok Streams..."); - createTikTokStream(); - } - - /** - * Creates an RSS Stream. - */ - public void createRssStream() { - ThreadUtil.createThread(x -> { - - Collection urls = new ArrayList<>(registeredRSSFeeds); - - /* - * TODO:: Either switch to RSSHub, YouTubes RSS or stay on API based. - * Issue with RSSHub is that it takes 2 hours to update, because of caching. - * Issue with YouTube is that it takes over 30 minutes to update, because of idk random internal stuff. - */ - - ////Collection urls = new ArrayList<>(registeredYouTubeChannels.stream().map(c -> "https://rsshub.app/youtube/channel/" + c).toList()); - - // TODO:: Wait till Nitter has fixed their RSS Feeds. Or Twitter finally gets the stick out of their ass and stop limiting simple scraping. - ////urls.addAll(registeredTwitterUsers.stream().map(c -> "https://nitter.net/" + c + "/rss").toList()); - - ////urls.addAll(registeredRSSFeeds); - - List checkedIds = new ArrayList<>(); - - // To support Podcast RSS. - new ItunesRssReader() - .addItemExtension("media:description", Item::setDescription) - .addItemExtension("media:thumbnail", "url", (item, element) -> { - Image image = item.getChannel().getImage().orElse(new Image()); - image.setUrl(element); - item.getChannel().setImage(image); - }).addItemExtension("media:thumbnail", "width", (item, element) -> { - Image image = item.getChannel().getImage().orElse(new Image()); - image.setWidth(Integer.valueOf(element)); - item.getChannel().setImage(image); - }).addItemExtension("media:thumbnail", "height", (item, element) -> { - Image image = item.getChannel().getImage().orElse(new Image()); - image.setHeight(Integer.valueOf(element)); - item.getChannel().setImage(image); - }).addChannelExtension("published", Channel::setPubDate) - .addItemExtension("dc:creator", Item::setAuthor) - .addItemExtension("dc:date", Item::setPubDate) - .addItemExtension("yt:channelId", Item::setAuthor) - .setUserAgent("Ree6Bot/" + BotWorker.getBuild() + " (by Presti)") - .read(urls) - .sorted() - .forEach(item -> { - if (item.getPubDate().isEmpty()) return; - - String typ = "other"; - - if (item.getGuid().isPresent()) { - String guid = item.getGuid().get(); - - if (guid.contains("nitter")) { - typ = "tw"; - } else { - typ = "other"; - } - } - - - OffsetDateTime dateTime = OffsetDateTime.parse(item.getPubDate().orElse(""), DateTimeFormatter.ISO_OFFSET_DATE_TIME); - - OffsetDateTime now = OffsetDateTime.now(); - OffsetDateTime threeMinuteAgo = now.minusMinutes(3); - - if (dateTime.isBefore(threeMinuteAgo)) return; - - if (item.getChannel() != null) { - - String id = ""; - - switch (typ) { - case "tw" -> id = item.getChannel().getLink().replace("https://nitter.net/", ""); - - case "other" -> id = item.getChannel().getLink(); - } - - if (checkedIds.contains(id)) { - return; - } - - - if (typ.equals("tw")) { - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(item.getChannel().getLink().replace("https://nitter.net/", "")); - - if (webhooks.isEmpty()) return; - - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - item.getChannel().getImage().ifPresentOrElse(image -> - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), - URLDecoder.decode(image.getUrl().replace("nitter.net/pic/", ""), StandardCharsets.UTF_8), null)), - () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); - - - webhookEmbedBuilder.setDescription(item.getTitle() + "\n"); - - item.getDescription().ifPresent(description -> { - if (description.contains(" { - String message = webhook.getMessage() - .replace("%name%", item.getChannel().getTitle()); - - if (item.getLink().isPresent()) { - message = message.replace("%url%", item.getLink().get() - .replace("nitter.net", "twitter.com")) - .replace("#m", ""); - } - webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); - }); - } else { - try { - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getRSSWebhooksByUrl(id); - - if (webhooks.isEmpty()) return; - - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - item.getChannel().getImage().ifPresentOrElse(image -> - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), - URLDecoder.decode(image.getUrl(), StandardCharsets.UTF_8), null)), - () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); - - item.getDescription().ifPresent(description -> webhookEmbedBuilder.setDescription(description + "\n")); - - if (item instanceof ItunesItem itunesItem) { - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(itunesItem.getItunesTitle().orElse("No Title"), item.getLink().orElse("No Link"))); - itunesItem.getItunesImage().ifPresent(webhookEmbedBuilder::setThumbnailUrl); - } else { - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(item.getTitle().orElse("No Title"), item.getLink().orElse("No Link"))); - } - - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("RSS Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); - - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); - webhookEmbedBuilder.setTimestamp(Instant.now()); - webhookEmbedBuilder.setColor(Color.CYAN.getRGB()); - - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - - webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); - } catch (Exception exception) { - Sentry.captureException(exception); - } - } - - checkedIds.add(id); - } - }); - }, Duration.ofMinutes(3), true, true); - } - - //region Twitch - - /** - * Register an EventHandler for the Twitch Livestream Event. - */ - public void registerTwitchEventHandler() { - getTwitchClient().getEventManager().onEvent(ChannelGoLiveEvent.class, channelGoLiveEvent -> { - - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(channelGoLiveEvent.getChannel().getName()); - if (webhooks.isEmpty()) { - return; - } - - String twitchUrl = "https://twitch.tv/" + channelGoLiveEvent.getChannel().getName(); - - // Create a Webhook Message. - WebhookMessageBuilder wmb = new WebhookMessageBuilder(); - - wmb.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); - wmb.setUsername(BotConfig.getBotName()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(channelGoLiveEvent.getStream().getUserName(), twitchUrl)); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Twitch Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); - - // Try getting the User. - Optional twitchUserRequest = getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(channelGoLiveEvent.getStream().getUserName())).execute().getUsers().stream().findFirst(); - if (twitchUserRequest.isPresent()) { - webhookEmbedBuilder.setThumbnailUrl(twitchUserRequest.orElseThrow().getProfileImageUrl()); - } - webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrl()); - - // Set rest of the Information. - webhookEmbedBuilder.setDescription("**" + channelGoLiveEvent.getStream().getTitle() + "**\n[Watch Stream](" + twitchUrl + ")"); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Game**", channelGoLiveEvent.getStream().getGameName())); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Viewer**", String.valueOf(channelGoLiveEvent.getStream().getViewerCount()))); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); - - wmb.addEmbeds(webhookEmbedBuilder.build()); - - // Go through every Webhook that is registered for the Twitch Channel - webhooks.forEach(webhook -> { - String message = webhook.getMessage() - .replace("%name%", channelGoLiveEvent.getStream().getUserName()) - .replace("%url%", twitchUrl); - wmb.setContent(message); - WebhookUtil.sendWebhook(wmb.build(), webhook); + return null; }); - }); - - getTwitchClient().getEventManager().onEvent(ChannelFollowCountUpdateEvent.class, channelFollowCountUpdateEvent -> { - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE LOWER(twitchFollowerChannelUsername) = :name", - Map.of("name", channelFollowCountUpdateEvent.getChannel().getName().toLowerCase())); - if (!channelStats.isEmpty()) { - for (ChannelStats channelStat : channelStats) { - if (channelStat.getTwitchFollowerChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); - if (guildChannel != null) { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; - - guildChannel.getManager().setName(LanguageService.getByGuild(guildChannel.getGuild(), "label.twitchCountName", channelFollowCountUpdateEvent.getFollowCount())).queue(); - } - } - } - } - }); - } - - /** - * Used to Register a Livestream Event for the given Twitch Channel - * - * @param twitchChannel the Name of the Twitch Channel. - */ - public void registerTwitchChannel(String twitchChannel) { - if (getTwitchClient() == null) return; - - twitchChannel = twitchChannel.toLowerCase(); - - if (!isTwitchRegistered(twitchChannel)) registeredTwitchChannels.add(twitchChannel); - - getTwitchClient().getClientHelper().enableStreamEventListener(twitchChannel); - getTwitchClient().getClientHelper().enableFollowEventListener(twitchChannel); - } - - /** - * Used to Register a Livestream Event for the given Twitch Channels - * - * @param twitchChannels the Names of the Twitch Channels. - */ - public void registerTwitchChannel(List twitchChannels) { - if (getTwitchClient() == null) return; - - twitchChannels.forEach(s -> { - if (s == null) return; - - s = s.toLowerCase(); - if (!isTwitchRegistered(s)) registeredTwitchChannels.add(s); - }); - - getTwitchClient().getClientHelper().enableStreamEventListener(twitchChannels); - getTwitchClient().getClientHelper().enableFollowEventListener(twitchChannels); - } - - /** - * Used to Unregister a Livestream Event for the given Twitch Channel - * - * @param twitchChannel the Name of the Twitch Channel. - */ - public void unregisterTwitchChannel(String twitchChannel) { - if (getTwitchClient() == null) return; - - twitchChannel = twitchChannel.toLowerCase(); - - if (!SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(twitchChannel).isEmpty() || - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitchFollowerChannelUsername=:name", Map.of("name", twitchChannel)) != null) - return; - - if (isTwitchRegistered(twitchChannel)) registeredTwitchChannels.remove(twitchChannel); - - getTwitchClient().getClientHelper().disableStreamEventListener(twitchChannel); - getTwitchClient().getClientHelper().disableFollowEventListener(twitchChannel); - } - - /** - * Check if a Twitch Channel is already being checked. - * - * @param twitchChannel the Name of the Twitch Channel. - * @return true, if there is an Event for the Channel | false, if there isn't an Event for the Channel. - */ - public boolean isTwitchRegistered(String twitchChannel) { - return registeredTwitchChannels.contains(twitchChannel.toLowerCase()); - } - - //endregion - - //region Twitter - - /** - * Used to Register a Tweet Event for the given Twitter Users - * - * @param twitterUsers the Names of the Twitter Users. - */ - public void registerTwitterUser(List twitterUsers) { - twitterUsers.forEach(this::registerTwitterUser); - } - - /** - * Used to Register a Tweet Event for the given Twitter User - * - * @param twitterUser the Name of the Twitter User. - */ - public void registerTwitterUser(String twitterUser) { - if (getTwitterClient() == null) return; - - twitterUser = twitterUser.toLowerCase(); - - if (!isTwitterRegistered(twitterUser)) { - registeredTwitterUsers.add(twitterUser); + } catch (Exception exception) { + log.error("Failed to create Instagram Client.", exception); } - } - /** - * Used to Unregister a Tweet Event for the given Twitter User - * - * @param twitterUser the Name of the Twitter User. - */ - public void unregisterTwitterUser(String twitterUser) { - if (getTwitterClient() == null) return; - - twitterUser = twitterUser.toLowerCase(); - - if (!SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(twitterUser).isEmpty() || - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", twitterUser)) != null) - return; - - if (isTwitterRegistered(twitterUser)) { - registeredTwitterUsers.remove(twitterUser); + try { + log.info("Initializing Spotify Client..."); + spotifySonic = new SpotifySonic(); + } catch (Exception exception) { + log.error("Failed to create Spotify Client.", exception); } - } - - /** - * Check if a Twitter User is already being checked. - * - * @param twitterUser the Name of the Twitter User. - * @return true, if there is an Event for the User | false, if there isn't an Event for the User. - */ - public boolean isTwitterRegistered(String twitterUser) { - return registeredTwitterUsers.contains(twitterUser.toLowerCase()); - } - - //endregion - - //region YouTube - - /** - * Create an API Stream used to update ChannelStats and Notifier of YT. - */ - public void createYTStream() { - ThreadUtil.createThread(x -> { - for (String channel : registeredYouTubeChannels) { - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(channel); - - if (!webhooks.isEmpty()) { - try { - List playlistItemList = YouTubeAPIHandler.getInstance().getYouTubeUploads(channel); - if (!playlistItemList.isEmpty()) { - for (VideoResult playlistItem : playlistItemList) { - - Main.getInstance().logAnalytic("Video: " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate() + " | " + playlistItem.getTimeAgo()); - Main.getInstance().logAnalytic("Current: " + System.currentTimeMillis() + " | " + (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis()) + " | " - + (playlistItem.getActualUploadDate() != null && playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) + " | " + (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())); - - if (playlistItem.getUploadDate() != -1 && (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis() || - (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())) && - playlistItem.getActualUploadDate() != null && !playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) { - - Main.getInstance().logAnalytic("Passed! -> " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate()); - // Create a Webhook Message. - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(playlistItem.getOwnerName(), null)); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("YouTube Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - - webhookEmbedBuilder.setImageUrl(playlistItem.getThumbnail()); - - webhookEmbedBuilder.setDescription("[**" + playlistItem.getTitle() + "**](https://www.youtube.com/watch?v=" + playlistItem.getId() + ")"); - - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - webhookEmbedBuilder.setColor(Color.RED.getRGB()); - - webhooks.forEach(webhook -> { - String message = webhook.getMessage().replace("%name%", playlistItem.getOwnerName()) - .replace("%title%", playlistItem.getTitle()) - .replace("%description%", playlistItem.getDescriptionSnippet() != null ? "No Description" : playlistItem.getDescriptionSnippet()) - .replace("%url%", "https://www.youtube.com/watch?v=" + playlistItem.getId()); - - webhookMessageBuilder.setContent(message); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); - }); - - break; - } - } - } - } catch (Exception exception) { - Sentry.captureException(exception); - log.error("Couldn't get user data of " + channel + "!", exception); - } - } - - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", channel)); - - if (!channelStats.isEmpty()) { - ChannelResult youTubeChannel; - try { - // TODO:: change YT Tracker to use the ID instead of username. - youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelById(channel); - } catch (Exception e) { - Sentry.captureException(e); - continue; - } - - if (youTubeChannel == null) continue; - - for (ChannelStats channelStat : channelStats) { - if (channelStat.getYoutubeSubscribersChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getYoutubeSubscribersChannelId()); - - if (guildChannel == null) continue; - String newName = LanguageService.getByGuild(guildChannel.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()); - if (!guildChannel.getName().equalsIgnoreCase(newName)) { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; - - guildChannel.getManager().setName(newName).queue(); - } - } - } - } - } - }, x -> { - log.error("Couldn't run YT checker!", x); - Sentry.captureException(x); - // Default is 5 minutes. - }, Duration.ofMinutes(5), true, true); - } - - /** - * Used to register an Upload Event for the given YouTube Channel. - * - * @param youtubeChannel the Name of the YouTube Channel. - */ - public void registerYouTubeChannel(String youtubeChannel) { - if (YouTubeAPIHandler.getInstance() == null) return; - - if (!isYouTubeRegistered(youtubeChannel)) registeredYouTubeChannels.add(youtubeChannel); - } - - /** - * Used to register an upload Event for the given YouTube Channels. - * - * @param youtubeChannels the Names of the YouTube Channels. - */ - public void registerYouTubeChannel(List youtubeChannels) { - if (YouTubeAPIHandler.getInstance() == null) return; - - youtubeChannels.forEach(s -> { - if (!isYouTubeRegistered(s)) registeredYouTubeChannels.add(s); - }); - } - - /** - * Used to unregister an Upload Event for the given YouTube Channel - * - * @param youtubeChannel the Name of the YouTube Channel. - */ - public void unregisterYouTubeChannel(String youtubeChannel) { - if (YouTubeAPIHandler.getInstance() == null) return; - - if (!SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(youtubeChannel).isEmpty() || - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", youtubeChannel)) != null) - return; - - if (isYouTubeRegistered(youtubeChannel)) registeredYouTubeChannels.remove(youtubeChannel); - } - - /** - * Check if a YouTube Channel is already being checked. - * - * @param youtubeChannel the Name of the YouTube Channel. - * @return true, if there is an Event for the Channel | false, if there isn't an Event for the Channel. - */ - public boolean isYouTubeRegistered(String youtubeChannel) { - return registeredYouTubeChannels.contains(youtubeChannel); - } - - //endregion - - //region Reddit + log.info("Initializing Streams..."); - public List getSubredditPosts(String subreddit, Sorting sorting, int limit) throws AuthenticationException, IOException, InterruptedException { try { - return redditClient.getSubredditPosts(subreddit, sorting).limit(limit).submit(); - } catch (ValidateException exception) { - if (exception.getMessage().startsWith("The parameter")) { - redditClient.userlessConnect(); - return redditClient.getSubredditPosts(subreddit, sorting).limit(limit).submit(); - } + log.info("Creating YouTube Streams..."); + youTubeSonic = new YouTubeSonic(); + ThreadUtil.createThread(x -> youTubeSonic.run(), x -> { + log.error("Failed to run YouTube Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); + } catch (Exception exception) { + log.error("Failed to create YouTube Streams.", exception); } - return Collections.emptyList(); - } - - /** - * Used to register a Reddit-Post Event for all Subreddits. - */ - public void createRedditPostStream() { - ThreadUtil.createThread(x -> { - try { - for (String subreddit : registeredSubreddits) { - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)); - - if (!channelStats.isEmpty()) { - RedditSubreddit subredditEntity; - try { - subredditEntity = Main.getInstance().getNotifier().getSubreddit(subreddit); - } catch (IOException | InterruptedException e) { - return; - } - - for (ChannelStats channelStat : channelStats) { - if (channelStat.getSubredditMemberChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getSubredditMemberChannelId()); - String newName = "Subreddit Members: " + subredditEntity.getActiveUserCount(); - if (guildChannel != null && - !guildChannel.getName().equalsIgnoreCase(newName)) { - - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; - - guildChannel.getManager().setName(newName).queue(); - } - } - } - } - - getSubredditPosts(subreddit, Sorting.NEW, 50).stream().filter(redditPost -> redditPost.getCreated() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(redditPost -> { - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit); - - if (webhooks.isEmpty()) return; - - // Create Webhook Message. - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(redditPost.getTitle(), redditPost.getUrl())); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Reddit Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - - - if (!redditPost.getThumbnail().equalsIgnoreCase("self")) - webhookEmbedBuilder.setImageUrl(redditPost.getThumbnail()); - - // Set rest of the Information. - webhookEmbedBuilder.setDescription(URLDecoder.decode(redditPost.getSelftext(), StandardCharsets.UTF_8)); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Author**", redditPost.getAuthor())); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Subreddit**", redditPost.getSubreddit())); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - - webhookEmbedBuilder.setColor(Color.ORANGE.getRGB()); - - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - - webhooks.forEach(webhook -> { - String message = webhook.getMessage() - .replace("%title%", redditPost.getTitle()) - .replace("%author%", redditPost.getAuthor()) - .replace("%name%", redditPost.getSubreddit()) - .replace("%url%", redditPost.getUrl()); - webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); - }); - }); - } - } catch (Exception exception) { - log.error("Could not get Reddit Posts!", exception); - Sentry.captureException(exception); - } - }, x -> { - log.error("Couldn't start Reddit Stream!"); - Sentry.captureException(x); - }, Duration.ofMinutes(5), true, true); - } - - /** - * Used to get a Subreddit. - * - * @param subreddit the Name of the Subreddit. - * @return the Subreddit. - * @throws IOException if the Subreddit couldn't be found. - * @throws InterruptedException if the Thread was interrupted. - */ - public RedditSubreddit getSubreddit(String subreddit) throws IOException, InterruptedException { - return redditClient.getSubreddit(subreddit); - } - - /** - * Used to register a Reddit-Post Event for the given Subreddit - * - * @param subreddit the Names of the Subreddit. - */ - public void registerSubreddit(String subreddit) { - if (getRedditClient() == null) return; - - if (!isSubredditRegistered(subreddit)) registeredSubreddits.add(subreddit); - } - - /** - * Used to register a Reddit-Post Event for the Subreddit. - * - * @param subreddits the Names of the Subreddits. - */ - public void registerSubreddit(List subreddits) { - if (getRedditClient() == null) return; - - subreddits.forEach(s -> { - if (!isSubredditRegistered(s)) registeredSubreddits.add(s); - }); - } - - /** - * Used to unregister a Reddit-Post Event for the given Subreddit. - * - * @param subreddit the Names of the Subreddit. - */ - public void unregisterSubreddit(String subreddit) { - if (getRedditClient() == null) return; - - if (!SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).isEmpty() || - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)) != null) - return; - - if (isSubredditRegistered(subreddit)) registeredSubreddits.remove(subreddit); - } - - /** - * Check if a Subreddit is already being checked. - * - * @param subreddit the Names of the Subreddit. - * @return true, if there is an Event for the Channel | false, if there isn't an Event for the Channel. - */ - public boolean isSubredditRegistered(String subreddit) { - return registeredSubreddits.contains(subreddit); - } - - //endregion - - //region Instagram - - /** - * Used to register an Instagram-Post Event for all Insta-Users. - */ - public void createInstagramPostStream() { - ThreadUtil.createThread(x -> { - if (!instagramClient.isLoggedIn()) return; - - for (String username : registeredInstagramUsers) { - - instagramClient.actions().users().findByUsername(username).thenAccept(userAction -> { - com.github.instagram4j.instagram4j.models.user.User user = userAction.getUser(); - - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)); - - if (!channelStats.isEmpty()) { - for (ChannelStats channelStat : channelStats) { - if (channelStat.getInstagramFollowerChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getInstagramFollowerChannelId()); - - if (guildChannel == null) continue; - - String newName = LanguageService.getByGuild(guildChannel.getGuild(), "label.instagramCountName", user.getFollower_count()); - if (!guildChannel.getName().equalsIgnoreCase(newName)) { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; - - guildChannel.getManager().setName(newName).queue(); - } - } - } - } - - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username); - - if (webhooks.isEmpty()) return; - - if (!user.is_private()) { - FeedIterator iterable = new FeedIterator<>(instagramClient, new FeedUserRequest(user.getPk())); - - int limit = 1; - while (iterable.hasNext() && limit-- > 0) { - FeedUserResponse response = iterable.next(); - // Actions here - response.getItems().stream().filter(post -> post.getTaken_at() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(instagramPost -> { - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getUsername(), "https://www.instagram.com/" + user.getUsername())); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Instagram Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - - // Set rest of the Information. - if (instagramPost instanceof TimelineImageMedia timelineImageMedia) { - webhookEmbedBuilder.setImageUrl(timelineImageMedia.getImage_versions2().getCandidates().get(0).getUrl()); - webhookEmbedBuilder.setDescription(timelineImageMedia.getCaption().getText()); - } else if (instagramPost instanceof TimelineVideoMedia timelineVideoMedia) { - webhookEmbedBuilder.setDescription("[Click here to watch the video](" + timelineVideoMedia.getVideo_versions().get(0).getUrl() + ")"); - } else { - webhookEmbedBuilder.setDescription(user.getUsername() + " just posted something new on Instagram!"); - } - - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); - - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - - // TODO:: add this with message. - - webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); - }); - } - } - }).exceptionally(exception -> { - log.error("Could not get Instagram User!", exception); - Sentry.captureException(exception); - return null; - }).join(); - } - }, x -> { - log.error("Couldn't start Instagram Stream!"); - Sentry.captureException(x); - }, Duration.ofMinutes(5), true, true); - } - - /** - * Used to register an Instagram-Post Event for all Insta-Users. - * - * @param username the Names of the User. - */ - public void registerInstagramUser(String username) { - if (getInstagramClient() == null) return; - - if (!isInstagramUserRegistered(username)) registeredInstagramUsers.add(username); - } - - /** - * Used to register an Instagram-Post Event for all Insta-Users. - * - * @param usernames the Names of the Users. - */ - public void registerInstagramUser(List usernames) { - if (getInstagramClient() == null) return; - - usernames.forEach(s -> { - if (!isInstagramUserRegistered(s)) registeredInstagramUsers.add(s); - }); - } - - /** - * Used to unregister an Instagram-Post Event for all Insta-Users. - * - * @param username the Names of the User. - */ - public void unregisterInstagramUser(String username) { - if (getInstagramClient() == null) return; - - if (!SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).isEmpty() || - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)) != null) - return; - - if (isInstagramUserRegistered(username)) registeredInstagramUsers.remove(username); - } - - /** - * Check if a User is already being checked. - * - * @param username the Names of the User. - * @return true, if there is an Event for the Channel | false, if there isn't an Event for the Channel. - */ - public boolean isInstagramUserRegistered(String username) { - return registeredInstagramUsers.contains(username); - } - - //endregion - - //region TikTok - - /** - * Used to create a Thread that handles TikTok notifications. - */ - public void createTikTokStream() { - ThreadUtil.createThread(x -> { - for (long id : registeredTikTokUsers) { - try { - TikTokUser user = TikTokWrapper.getUser(id); - - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getTikTokWebhooksByName(user.getId()); - - if (webhooks.isEmpty()) { - return; - } - - AtomicInteger limit = new AtomicInteger(); - - user.getPosts().forEach(post -> { - if (limit.get() > 3) return; - - if (post.getCreationTime() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())) { - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getDisplayName(), "https://www.tiktok.com/@" + user.getName())); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("TikTok Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - - // Set rest of the Information. - if (post.getCover() != null) { - webhookEmbedBuilder.setImageUrl(post.getCover().getMediumUrl()); - webhookEmbedBuilder.setDescription("[Click here to watch the video](https://tiktok.com/share/video/" + post.getId() + ")"); - } else { - webhookEmbedBuilder.setDescription(user.getDisplayName() + " just posted something new on TikTok!"); - } - - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); - - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - - webhooks.forEach(webhook -> { - String message = webhook.getMessage() - .replace("%description%", post.getDescription()) - .replace("%author%", user.getName()) - .replace("%name%", user.getDisplayName()) - .replace("%url%", "https://tiktok.com/share/video/" + post.getId()); - webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); - }); - } - limit.incrementAndGet(); - }); - } catch (IOException e) { - if (e instanceof HttpStatusException httpStatusException) { - if (httpStatusException.getStatusCode() == 404) return; - // TODO:: check, maybe delete on 404? - } - - Sentry.captureException(e); - } - } - }, Duration.ofMinutes(5), true, true); - } - - /** - * Used to register a TikTok User. - * - * @param id the ID of the TikTok User. - */ - public void registerTikTokUser(long id) { - if (!isTikTokUserRegistered(id)) registeredTikTokUsers.add(id); - } - - /** - * Used to register multiple TikTok Users. - * - * @param users the ID of the TikTok Users. - */ - public void registerTikTokUser(List users) { - users.forEach(this::registerTikTokUser); - } - - /** - * Used to unregister a TikTok User. - * - * @param id the ID of the TikTok User. - */ - public void unregisterTikTokUser(long id) { - if (isTikTokUserRegistered(id)) registeredTikTokUsers.remove(id); - } - - /** - * Check if a TikTok User is already being checked. - * - * @param id the Name of the TikTok User. - * @return true, if there is a User | false, if there isn't a User. - */ - public boolean isTikTokUserRegistered(long id) { - return registeredTikTokUsers.contains(id); - } - - //endregion + try { + log.info("Creating Twitter Streams..."); + ThreadUtil.createThread(x -> twitterSonic.run(), x -> { + log.error("Failed to run Twitter Follower count checker!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); + } catch (Exception exception) { + log.error("Failed to create Twitter Streams.", exception); + } - //region RSS + try { + log.info("Creating RSS Streams..."); + rssSonic = new RSSSonic(); + ThreadUtil.createThread(x -> rssSonic.run(), x -> { + log.error("Failed to run RSS Feed Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(3), true, true); + } catch (Exception exception) { + log.error("Failed to create RSS Streams.", exception); + } - /** - * Used to register an RSS Feed. - * - * @param rssUrl the Url of the RSS-Feed. - */ - public void registerRSS(String rssUrl) { - if (!isRSSRegistered(rssUrl)) registeredRSSFeeds.add(rssUrl); - } + try { + log.info("Creating TikTok Streams..."); + tikTokSonic = new TikTokSonic(); + ThreadUtil.createThread(x -> tikTokSonic.run(), x -> { + log.error("Failed to run TikTok Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); + } catch (Exception exception) { + log.error("Failed to create TikTok Streams.", exception); + } - /** - * Used to register an RSS Feed. - * - * @param rssUrls the Urls of the RSS-Feeds. - */ - public void registerRSS(List rssUrls) { - rssUrls.forEach(s -> { - if (!isRSSRegistered(s)) registeredRSSFeeds.add(s); - }); - } + try { + log.info("Creating Instagram Streams..."); + ThreadUtil.createThread(x -> instagramSonic.run(), x -> { + log.error("Failed to run Instagram Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); + } catch (Exception exception) { + log.error("Failed to create Instagram Streams.", exception); + } - /** - * Used to unregister an RSS Feed. - * - * @param rssUrl the Url of the RSS-Feed. - */ - public void unregisterRSS(String rssUrl) { - if (isRSSRegistered(rssUrl)) registeredRSSFeeds.remove(rssUrl); - } + try { + log.info("Creating Reddit Streams..."); + ThreadUtil.createThread(x -> redditSonic.run(), x -> { + log.error("Failed to run Reddit Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); + } catch (Exception exception) { + log.error("Failed to create Reddit Streams.", exception); + } - /** - * Check if an RSS-Feed is already being checked. - * - * @param rssUrl the Url of the RSS-Feed. - * @return true, if there is an Url | false, if there isn't an Url. - */ - public boolean isRSSRegistered(String rssUrl) { - return registeredRSSFeeds.contains(rssUrl); + try { + // Use 1 day instead of minutes, because Spotify release date is at max precise to the day + log.info("Creating Spotify Streams..."); + ThreadUtil.createThread(x -> spotifySonic.run(), x -> { + log.error("Failed to run Spotify Stream!", x); + Sentry.captureException(x); + }, Duration.ofDays(1), true, true); + } catch (Exception exception) { + log.error("Failed to create Spotify Streams.", exception); + } } - - //endregion } diff --git a/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java b/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java index 6d840e837..95fe3e789 100644 --- a/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java +++ b/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java @@ -14,8 +14,9 @@ import se.michaelthelin.spotify.model_objects.specification.*; import se.michaelthelin.spotify.requests.authorization.client_credentials.ClientCredentialsRequest; import se.michaelthelin.spotify.requests.data.albums.GetAlbumsTracksRequest; +import se.michaelthelin.spotify.requests.data.artists.GetArtistsAlbumsRequest; import se.michaelthelin.spotify.requests.data.playlists.GetPlaylistRequest; -import se.michaelthelin.spotify.requests.data.tracks.GetTrackRequest; +import se.michaelthelin.spotify.requests.data.shows.GetShowsEpisodesRequest; import java.io.IOException; import java.util.ArrayList; @@ -228,6 +229,127 @@ public ArrayList getTracks(String playlistId) { return tracks; } + /** + * Get the Artist based on their ID. + * + * @param artistId The Artist ID. + * @return The Artist. + * @throws ParseException if the response is not a Valid JSON. + * @throws SpotifyWebApiException if an error occurs. + * @throws IOException if there was a network error. + */ + public Artist getArtist(String artistId) throws ParseException, SpotifyWebApiException, IOException { + if (!isSpotifyConnected) return null; + return spotifyApi.getArtist(artistId).build().execute(); + } + + /** + * Get the Albums of an Artist. + * + * @param artistId The Artist ID. + * @return All Albums of the Artist. + * @throws ParseException if the response is not a Valid JSON. + * @throws SpotifyWebApiException if an error occurs. + * @throws IOException if there was a network error. + */ + public ArrayList getArtistAlbums(String artistId) throws ParseException, SpotifyWebApiException, IOException { + if (!isSpotifyConnected) return new ArrayList<>(); + ArrayList albums = new ArrayList<>(); + + if (retries.getOrDefault(artistId, 0) >= 3) return albums; + + GetArtistsAlbumsRequest request = spotifyApi.getArtistsAlbums(artistId).build(); + try { + Paging albumList = request.execute(); + + for (AlbumSimplified album : albumList.getItems()) { + if (album == null) continue; + + albums.add(album); + } + retries.remove(artistId); + } catch (UnauthorizedException unauthorizedException) { + if (spotifyApi.getClientId() != null) { + + try { + isSpotifyConnected = false; + retries.put(artistId, retries.getOrDefault(artistId, 0) + 1); + initSpotify(); + } catch (Exception exception) { + Sentry.captureException(exception); + } + + return getArtistAlbums(artistId); + } else { + log.error("Couldn't get Album from Artist", unauthorizedException); + } + } catch (ParseException | SpotifyWebApiException | IOException e) { + log.error("Couldn't get Album from Artist", e); + } + + return albums; + } + + /** + * Get a Podcast. + * + * @param podcastId The Podcast ID. + * @return The Podcast. + * @throws ParseException if the response is not a Valid JSON. + * @throws SpotifyWebApiException if an error occurs. + * @throws IOException if there was a network error. + */ + public Show getPodcast(String podcastId) throws ParseException, SpotifyWebApiException, IOException { + if (!isSpotifyConnected) return null; + return spotifyApi.getShow(podcastId).build().execute(); + } + + /** + * Get all Podcast Episodes. + * + * @param podcastId The Podcast ID. + * @return The Podcast episodes. + * @throws ParseException if the response is not a Valid JSON. + * @throws SpotifyWebApiException if an error occurs. + * @throws IOException if there was a network error. + */ + public ArrayList getPodcastEpisodes(String podcastId) throws ParseException, SpotifyWebApiException, IOException { + if (!isSpotifyConnected) return new ArrayList<>(); + ArrayList episodes = new ArrayList<>(); + + if (retries.getOrDefault(podcastId, 0) >= 3) return episodes; + + GetShowsEpisodesRequest request = spotifyApi.getShowEpisodes(podcastId).build(); + try { + Paging albumList = request.execute(); + + for (EpisodeSimplified episode : albumList.getItems()) { + if (episode == null) continue; + + episodes.add(episode); + } + retries.remove(podcastId); + } catch (UnauthorizedException unauthorizedException) { + if (spotifyApi.getClientId() != null) { + + try { + isSpotifyConnected = false; + retries.put(podcastId, retries.getOrDefault(podcastId, 0) + 1); + initSpotify(); + } catch (Exception exception) { + Sentry.captureException(exception); + } + + return getPodcastEpisodes(podcastId); + } else { + log.error("Couldn't get Episodes from Podcast", unauthorizedException); + } + } catch (ParseException | SpotifyWebApiException | IOException e) { + log.error("Couldn't get Episodes from Podcast", e); + } + return episodes; + } + /** * Get the Artist and Track Name of a Track. * diff --git a/src/main/java/de/presti/ree6/utils/apis/YouTubeAPIHandler.java b/src/main/java/de/presti/ree6/utils/apis/YouTubeAPIHandler.java index 453e05fb5..52740a4af 100644 --- a/src/main/java/de/presti/ree6/utils/apis/YouTubeAPIHandler.java +++ b/src/main/java/de/presti/ree6/utils/apis/YouTubeAPIHandler.java @@ -18,8 +18,6 @@ import java.util.List; import java.util.regex.Pattern; -// TODO:: check if there is a way to make this more efficient, maybe use a cache system or merge multiple requests into one and split the result for further use again? - /** * YouTubeAPIHandler. */ diff --git a/src/main/java/de/presti/ree6/utils/data/Config.java b/src/main/java/de/presti/ree6/utils/config/Config.java similarity index 88% rename from src/main/java/de/presti/ree6/utils/data/Config.java rename to src/main/java/de/presti/ree6/utils/config/Config.java index c20c78048..da454caf4 100644 --- a/src/main/java/de/presti/ree6/utils/data/Config.java +++ b/src/main/java/de/presti/ree6/utils/config/Config.java @@ -1,4 +1,4 @@ -package de.presti.ree6.utils.data; +package de.presti.ree6.utils.config; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.utils.others.VersionUtil; @@ -34,7 +34,7 @@ public class Config { /** * The config version. */ - private final String version = "3.1.12"; + private final String version = "4.0.0"; /** * Initialize the Configuration. @@ -120,6 +120,7 @@ public void createConfigFile() { .parent().path("dev").addDefault("DevTokenhere").commentSide("Token used when set to dev build.") .parent().parent().path("misc").comment("Configuration for the Bot itself.").blankLine() .path("status").addDefault("ree6.de | %guilds% Servers. (%shard%)").commentSide("The Status of the Bot.") + .parent().path("mainColor").addDefault("#c80292").commentSide("Color that should be used in various places.") .parent().path("feedbackChannelId").addDefault(0L).commentSide("The Channel used for Feedback.") .parent().path("ownerId").addDefault(321580743488831490L).commentSide("The ID of the Bot Owner. Change this to yours!") .parent().path("predefineInformation").addDefault(""" @@ -277,77 +278,69 @@ public void migrateOldConfig() { log.warn("This means the config file is not backed up by us!"); } - if (getFile().delete()) { - init(); + try { + if (Files.deleteIfExists(getFile().toPath())) { + init(); - for (Map.Entry entry : resources.entrySet()) { - String key = entry.getKey(); + for (Map.Entry entry : resources.entrySet()) { + String key = entry.getKey(); - boolean modified = false; + boolean modified = false; - if (key.startsWith("config")) - continue; + if (key.startsWith("config") || entry.getValue() instanceof MemorySection) + continue; - if (entry.getValue() instanceof MemorySection) - continue; + // Migrate to 1.10.0 + if (compareVersion("1.10.0", configVersion)) { - // Migrate to 1.10.0 - if (compareVersion("1.10.0", configVersion)) { + if (key.startsWith("mysql")) + key = key.replace("mysql", "hikari.sql"); - if (key.startsWith("mysql")) - key = key.replace("mysql", "hikari.sql"); + if (key.endsWith(".rel")) + key = key.replace(".rel", ".release"); - if (key.endsWith(".rel")) - key = key.replace(".rel", ".release"); + yamlFile.set(key, entry.getValue()); + modified = true; + } - yamlFile.set(key, entry.getValue()); - modified = true; - } + // Migrate to 2.2.0 + if (compareVersion("2.2.0", configVersion) && !key.startsWith("youtube")) { + yamlFile.set(key, entry.getValue()); + modified = true; + } - // Migrate to 2.2.0 - if (compareVersion("2.2.0", configVersion)) { - if (key.startsWith("youtube")) + // Migrate to 2.4.11 + if (compareVersion("2.4.11", configVersion) && key.startsWith("twitter") && !key.endsWith("bearer")) continue; - yamlFile.set(key, entry.getValue()); - modified = true; - } - + // Migrate to 3.1.9 + if (compareVersion("3.1.9", configVersion)) { - // Migrate to 2.4.11 - if (compareVersion("2.4.11", configVersion)) { - if (key.startsWith("twitter") && !key.endsWith("bearer")) continue; - } + if (key.startsWith("bot.misc.leveling.modules.")) + key = key.replace("bot.misc.leveling.modules.", "bot.misc.modules."); - // Migrate to 3.1.9 - if (compareVersion("3.1.9", configVersion)) { + if (key.endsWith("bot.misc.leveling.rankCard.")) + key = key.replace("bot.misc.leveling.rankCard.", "bot.misc.rankCard."); - if (key.startsWith("bot.misc.leveling.modules.")) - key = key.replace("bot.misc.leveling.modules.", "bot.misc.modules."); + yamlFile.set(key, entry.getValue()); + modified = true; + } - if (key.endsWith("bot.misc.leveling.rankCard.")) - key = key.replace("bot.misc.leveling.rankCard.", "bot.misc.rankCard."); - yamlFile.set(key, entry.getValue()); - modified = true; + if (!modified) { + yamlFile.set(key, entry.getValue()); + } } - - if (!modified) { - yamlFile.set(key, entry.getValue()); + if (compareVersion("2.2.0", configVersion)) { + yamlFile.remove("youtube"); } - } - if (compareVersion("2.2.0", configVersion)) { - yamlFile.remove("youtube"); - } - - try { yamlFile.save(getFile()); - } catch (Exception exception) { - exception.printStackTrace(); } + } catch (Exception exception) { + log.error("Could not migrate old config!", exception); } } @@ -404,10 +397,12 @@ public File getFile() { */ public YamlFile createTemporal() { try { - return yamlTempFile = new YamlFile(getTemporalFile()); + yamlTempFile = new YamlFile(getTemporalFile()); } catch (Exception e) { return new YamlFile(); } + + return yamlTempFile; } /** diff --git a/src/main/java/de/presti/ree6/utils/data/ArrayUtil.java b/src/main/java/de/presti/ree6/utils/data/ArrayUtil.java index 9812dc865..6f6543095 100644 --- a/src/main/java/de/presti/ree6/utils/data/ArrayUtil.java +++ b/src/main/java/de/presti/ree6/utils/data/ArrayUtil.java @@ -27,10 +27,10 @@ private ArrayUtil() { } /** - * HashMap used to store conversations between the user and the Chat-GPT implementation. + * HashMap used to store conversations between the user and the ChatGPT implementation. * These are being stored guild specific so Ree6 will not continue a conversation in another guild. - * While at the same time we store them in memory to protect users privacy, since there is no actual - * reason for us to keep these longer then the current application uptime. + * While at the same time we store them in memory to protect users' privacy, since there is no actual + * reason for us to keep these longer than the current application uptime. */ public static final Map> chatGPTMessages = new HashMap<>(); @@ -40,7 +40,7 @@ private ArrayUtil() { public static final Map messageIDwithMessage = new HashMap<>(); /** - * HashMap used to store user Ids that are associated with a message, to show the content when the message gets deleted. + * HashMap used to store user Ids that are associated with a message to show the content when the message gets deleted. */ public static final Map messageIDwithUser = new HashMap<>(); @@ -55,12 +55,12 @@ private ArrayUtil() { public static final Map musicPanelList = new HashMap<>(); /** - * HashMap used to store a users Ids, to keep them from spamming commands. + * HashMap used to store a user's Ids, to keep them from spamming commands. */ public static final List commandCooldown = new ArrayList<>(); /** - * HashMap used to store a users Ids, to keep them from earning XP with every message. + * HashMap used to store a user's Ids, to keep them from earning XP with every message. */ public static final List timeout = new ArrayList<>(); diff --git a/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java b/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java deleted file mode 100644 index bf858b72f..000000000 --- a/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java +++ /dev/null @@ -1,84 +0,0 @@ -package de.presti.ree6.utils.data; - -import com.github.philippheuer.credentialmanager.api.IStorageBackend; -import com.github.philippheuer.credentialmanager.domain.Credential; -import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.TwitchIntegration; - -import java.util.*; - -/** - * The Storage backend to allow the Twitch4J CredentialManager to store the Data in our Database. - */ -public class DatabaseStorageBackend implements IStorageBackend { - - /** - * Load the Credentials - * - * @return List Credential - */ - @Override - public List loadCredentials() { - List twitchIntegrations = - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), - "FROM TwitchIntegration", null); - - List credentials = new ArrayList<>(); - - twitchIntegrations.forEach(twitchIntegration -> credentials.add(new CustomOAuth2Credential(twitchIntegration.getUserId(),"twitch", twitchIntegration.getToken(), - twitchIntegration.getRefresh(), twitchIntegration.getChannelId(), twitchIntegration.getName(), twitchIntegration.getExpiresIn(), Collections.emptyList()))); - - return credentials; - } - - /** - * Save the Credentials - * - * @param list List Credential - */ - @Override - public void saveCredentials(List list) { - list.forEach(credential -> { - if (credential instanceof CustomOAuth2Credential oAuth2Credential) { - TwitchIntegration twitchIntegration = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), - "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid",oAuth2Credential.getUserId())); - - if (twitchIntegration == null) { - twitchIntegration = new TwitchIntegration(); - twitchIntegration.setChannelId(oAuth2Credential.getUserId()); - twitchIntegration.setUserId(oAuth2Credential.getDiscordId()); - } - - twitchIntegration.setToken(oAuth2Credential.getAccessToken()); - twitchIntegration.setRefresh(oAuth2Credential.getRefreshToken()); - twitchIntegration.setName(oAuth2Credential.getUserName()); - twitchIntegration.setExpiresIn(oAuth2Credential.getExpiresIn()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(twitchIntegration); - } - }); - } - - /** - * Gets a Credential by UserId - * - * @param userId User Id - * @return Credential - */ - @Override - public Optional getCredentialByUserId(String userId) { - Optional twitchIntegration = Optional.ofNullable(SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), - "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid", userId))); - - if (twitchIntegration.isPresent()) { - TwitchIntegration twitchIntegration1 = twitchIntegration.get(); - CustomOAuth2Credential oAuth2Credential - = new CustomOAuth2Credential(twitchIntegration1.getUserId(),"twitch", twitchIntegration1.getToken(), - twitchIntegration1.getRefresh(), twitchIntegration1.getChannelId(), twitchIntegration1.getName(), twitchIntegration1.getExpiresIn(), Collections.emptyList()); - - return Optional.of(oAuth2Credential); - } else { - return Optional.empty(); - } - } -} \ No newline at end of file diff --git a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java index 0b8464323..79ef12f01 100644 --- a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java +++ b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java @@ -4,6 +4,8 @@ import de.presti.ree6.sql.entities.economy.MoneyHolder; import de.presti.ree6.sql.entities.economy.MoneyTransaction; import net.dv8tion.jda.api.entities.Member; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; import java.sql.Timestamp; import java.time.Instant; @@ -20,7 +22,7 @@ public class EconomyUtil { * @param member The Member. * @return If the MoneyHolder has any cash. */ - public static boolean hasCash(Member member) { + public static Mono hasCash(Member member) { return hasCash(member.getGuild().getIdLong(), member.getIdLong()); } @@ -31,8 +33,8 @@ public static boolean hasCash(Member member) { * @param memberId The ID of the Member. * @return If the MoneyHolder has any cash. */ - public static boolean hasCash(long guildId, long memberId) { - return hasCash(getMoneyHolder(guildId, memberId)); + public static Mono hasCash(long guildId, long memberId) { + return getMoneyHolder(guildId, memberId).map(EconomyUtil::hasCash); } /** @@ -51,7 +53,7 @@ public static boolean hasCash(MoneyHolder moneyHolder) { * @param member The Member. * @return The MoneyHolder. */ - public static MoneyHolder getMoneyHolder(Member member) { + public static Mono getMoneyHolder(Member member) { return getMoneyHolder(member.getGuild().getIdLong(), member.getIdLong()); } @@ -62,7 +64,7 @@ public static MoneyHolder getMoneyHolder(Member member) { * @param memberId The ID of the Member. * @return The MoneyHolder. */ - public static MoneyHolder getMoneyHolder(long guildId, long memberId) { + public static Mono getMoneyHolder(long guildId, long memberId) { return getMoneyHolder(guildId, memberId, true); } @@ -74,18 +76,18 @@ public static MoneyHolder getMoneyHolder(long guildId, long memberId) { * @param createIfNotExists If the MoneyHolder should be created if it does not exist. * @return The MoneyHolder. */ - public static MoneyHolder getMoneyHolder(long guildId, long memberId, boolean createIfNotExists) { - MoneyHolder moneyHolder = SQLSession.getSqlConnector().getSqlWorker().getEntity(new MoneyHolder(), "FROM MoneyHolder WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", - Map.of("gid", guildId, "uid", memberId)); - - if (moneyHolder == null && createIfNotExists) { - moneyHolder = new MoneyHolder(); - moneyHolder.setGuildId(guildId); - moneyHolder.setUserId(memberId); - moneyHolder = SQLSession.getSqlConnector().getSqlWorker().updateEntity(moneyHolder); - } + public static Mono getMoneyHolder(long guildId, long memberId, boolean createIfNotExists) { + return SQLSession.getSqlConnector().getSqlWorker().getEntity(new MoneyHolder(), "FROM MoneyHolder WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", + Map.of("gid", guildId, "uid", memberId)).publishOn(Schedulers.boundedElastic()).mapNotNull(moneyHolderOptional -> { + if (moneyHolderOptional.isEmpty() && createIfNotExists) { + MoneyHolder moneyHolder = new MoneyHolder(); + moneyHolder.setGuildId(guildId); + moneyHolder.setUserId(memberId); + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(moneyHolder).block(); + } - return moneyHolder; + return moneyHolderOptional.get(); + }); } /** @@ -133,7 +135,7 @@ public static boolean set(MoneyHolder holder, double amount, boolean setBank) { holder.setAmount(amount); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(holder); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(holder).block(); return true; } @@ -159,7 +161,7 @@ public static boolean pay(MoneyHolder sender, MoneyHolder receiver, double amoun receiver.setAmount(receiver.getAmount() + amount); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(receiver); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(receiver).block(); if (!isSystem) { if (fromBank) { @@ -168,10 +170,10 @@ public static boolean pay(MoneyHolder sender, MoneyHolder receiver, double amoun sender.setAmount(sender.getAmount() - amount); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(sender); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(sender).block(); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new MoneyTransaction(0L, isSystem, isSystem ? receiver.getGuildUserId().getGuildId() : sender.getGuildUserId().getGuildId(), isSystem && sender == null ? receiver : sender, receiver, toBank, fromBank, amount, Timestamp.from(Instant.now()))); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new MoneyTransaction(0L, isSystem, isSystem ? receiver.getGuildUserId().getGuildId() : sender.getGuildUserId().getGuildId(), isSystem && sender == null ? receiver : sender, receiver, toBank, fromBank, amount, Timestamp.from(Instant.now()))).block(); return true; } diff --git a/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java b/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java index f8a10fc72..e8b2160fd 100644 --- a/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java +++ b/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java @@ -3,6 +3,7 @@ import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.main.Main; +import de.presti.ree6.sql.entities.UserRankCard; import de.presti.ree6.sql.entities.level.UserLevel; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.entities.User; @@ -19,8 +20,7 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.HashMap; - -// TODO:: translate. +import java.util.Optional; /** * A utility to create Images. @@ -53,7 +53,7 @@ private ImageCreationUtility() { * @return the bytes of the Image. * @throws IOException when URL-Format is Invalid or the URL is not a valid Image. */ - public static byte[] createRankImage(UserLevel userLevel) throws IOException { + public static byte[] createRankImage(UserLevel userLevel, Optional card) throws IOException { long start = System.currentTimeMillis(); long actionPerformance = System.currentTimeMillis(); @@ -88,8 +88,11 @@ public static byte[] createRankImage(UserLevel userLevel) throws IOException { Main.getInstance().logAnalytic("Loading and creating Background base. ({}ms)", System.currentTimeMillis() - actionPerformance); actionPerformance = System.currentTimeMillis(); - // Generate a 885x211 Image Background. + // Generate a 1920x1080 Image Background. Dog what is this? if (rankBackgroundBase == null) rankBackgroundBase = ImageIO.read(new File("storage/images/base.png")); + + BufferedImage background = card.isPresent() ? ImageIO.read(new ByteArrayInputStream(card.get().getRankCard())) : rankBackgroundBase; + BufferedImage base = new BufferedImage(1920, 1080, BufferedImage.TYPE_INT_ARGB); Main.getInstance().logAnalytic("Loaded and created Background base. ({}ms)", System.currentTimeMillis() - actionPerformance); @@ -122,7 +125,7 @@ public static byte[] createRankImage(UserLevel userLevel) throws IOException { actionPerformance = System.currentTimeMillis(); // Draw Background art. graphics2D.setComposite(AlphaComposite.Src); - graphics2D.drawImage(rankBackgroundBase, null, 0, 0); + graphics2D.drawImage(background, null, 0, 0); graphics2D.setColor(Color.WHITE); graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Main.getInstance().logAnalytic("Finished drawing Background Image. ({}ms)", System.currentTimeMillis() - actionPerformance); @@ -138,15 +141,6 @@ public static byte[] createRankImage(UserLevel userLevel) throws IOException { Main.getInstance().logAnalytic("Finished drawing User Image. ({}ms)", System.currentTimeMillis() - actionPerformance); actionPerformance = System.currentTimeMillis(); - String discriminatorText = "#" + user.getDiscriminator(); - - Font verdana60 = retrieveFont(60, discriminatorText); - Font verdana50 = retrieveFont(50, rank); - Font verdana40 = retrieveFont(40, formattedExperience + " Rank Level"); - - Main.getInstance().logAnalytic("Finished creating Fonts. ({}ms)", System.currentTimeMillis() - actionPerformance); - actionPerformance = System.currentTimeMillis(); - String username = new String(user.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); if (username.length() > 13) { @@ -156,17 +150,18 @@ public static byte[] createRankImage(UserLevel userLevel) throws IOException { Main.getInstance().logAnalytic("Finished substring on Username. ({}ms)", System.currentTimeMillis() - actionPerformance); actionPerformance = System.currentTimeMillis(); + Font verdana60 = retrieveFont(60, username); + Font verdana50 = retrieveFont(50, rank); + Font verdana40 = retrieveFont(40, formattedExperience + " Rank Level"); + + Main.getInstance().logAnalytic("Finished creating Fonts. ({}ms)", System.currentTimeMillis() - actionPerformance); + actionPerformance = System.currentTimeMillis(); + + graphics2D.setColor(BotConfig.getRankTextColor()); graphics2D.setFont(verdana60); graphics2D.drawString(username, 425, 675); - // TODO:: remove this once discord removes discriminators. - if (!user.getDiscriminator().equals("#0000")) { - graphics2D.setColor(BotConfig.getRankDetailColor()); - graphics2D.setFont(verdana40); - graphics2D.drawString(discriminatorText, 425, 675 - graphics2D.getFontMetrics(verdana60).getHeight() + 5); - } - graphics2D.setColor(BotConfig.getRankProgressbarBackgroundColor()); graphics2D.fillRoundRect(175, 705, base.getWidth() - 950, 50, 50, 50); diff --git a/src/main/java/de/presti/ree6/utils/data/RegExUtil.java b/src/main/java/de/presti/ree6/utils/data/RegExUtil.java index 95024bac8..11c6a80e8 100644 --- a/src/main/java/de/presti/ree6/utils/data/RegExUtil.java +++ b/src/main/java/de/presti/ree6/utils/data/RegExUtil.java @@ -47,7 +47,13 @@ public class RegExUtil { /** * The Regex to detect any dhm based time input. - * For example 1d, 2h, 3m + * For example, 1d, 2h, 3m */ public static final String TIME_INPUT_REGEX = "\\d+[dhms]"; + + /** + * The Regex to detect if the given string is a valid language path. + * For example, message.kick.default + */ + public static final String ALLOWED_LANGUAGE_PATHS = "^(message\\.|label\\.|command\\.|game\\.|category\\.)\\S*"; } diff --git a/src/main/java/de/presti/ree6/utils/data/TranscriptUtil.java b/src/main/java/de/presti/ree6/utils/data/TranscriptUtil.java new file mode 100644 index 000000000..94bcd63ca --- /dev/null +++ b/src/main/java/de/presti/ree6/utils/data/TranscriptUtil.java @@ -0,0 +1,91 @@ +package de.presti.ree6.utils.data; + +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.entities.Message; + +import java.util.List; + +public class TranscriptUtil { + + /** + * Constructor should not be called, since it is a utility class that doesn't need an instance. + */ + private TranscriptUtil() { + throw new IllegalStateException("Utility class"); + } + + /** + * The HTML template that should be used for the transcripts. + */ + public static final String template = """ + + + + + + + + + + + + + + + Opened: %opened% + Transcript Generated: %closed% + Total Messages: %messages_count% + + + + %messages% + + + + + """; + + /** + * The Message template to be inserted into the HTML template. + */ + public static final String messageTemplate = """ + + %name%%time% + + %message% + + """; + + /** + * Generates a Transcript based on the templates. + * @param selfUser The Bot Self User to use as an Icon. + * @param messages The messages that should be put into the transcript. + * @param opened When the Ticket was opened. + * @param closed When the Ticket was closed. + * @return A filled-out template as {@link String} + */ + public static String generateTranscript(JDA selfUser, List messages, String opened, String closed) { + String icon = selfUser.getSelfUser().getEffectiveAvatarUrl(); + StringBuilder messageBuilder = new StringBuilder(); + for (Message message : messages) { + messageBuilder.append(messageTemplate + .replace("%name%", message.getAuthor().getName()) + .replace("%time%", message.getTimeCreated().toString()) + .replace("%message%", message.getContentRaw())); + } + + return template + .replace("%icon%", icon) + .replace("%opened%", opened) + .replace("%closed%", closed) + .replace("%messages_count%", String.valueOf(messages.size())) + .replace("%messages%", messageBuilder.toString()); + } + +} diff --git a/src/main/java/de/presti/ree6/utils/data/CustomOAuth2Credential.java b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Credential.java similarity index 98% rename from src/main/java/de/presti/ree6/utils/data/CustomOAuth2Credential.java rename to src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Credential.java index 28b27553e..24eca8546 100644 --- a/src/main/java/de/presti/ree6/utils/data/CustomOAuth2Credential.java +++ b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Credential.java @@ -1,8 +1,7 @@ -package de.presti.ree6.utils.data; +package de.presti.ree6.utils.oauth; import com.github.philippheuer.credentialmanager.domain.Credential; import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; -import io.sentry.MeasurementUnit; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @@ -48,7 +47,7 @@ public class CustomOAuth2Credential extends Credential { /** * OAuth Scopes */ - private List scopes; + private final List scopes; /** * Access Token context that can be used to store additional information diff --git a/src/main/java/de/presti/ree6/utils/data/CustomOAuth2Util.java b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java similarity index 90% rename from src/main/java/de/presti/ree6/utils/data/CustomOAuth2Util.java rename to src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java index d79917df7..8b27311d5 100644 --- a/src/main/java/de/presti/ree6/utils/data/CustomOAuth2Util.java +++ b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java @@ -1,4 +1,4 @@ -package de.presti.ree6.utils.data; +package de.presti.ree6.utils.oauth; import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; import com.github.philippheuer.credentialmanager.identityprovider.OAuth2IdentityProvider; @@ -12,6 +12,13 @@ */ public class CustomOAuth2Util { + /** + * Constructor should not be called, since it is a utility class that doesn't need an instance. + */ + private CustomOAuth2Util() { + throw new IllegalStateException("Utility class"); + } + /** * A bridge method to convert a CustomOAuth2Credential to an enriched CustomOAuth2Credential. * @param customOAuth2Credential The CustomOAuth2Credential to convert. @@ -33,7 +40,7 @@ public static CustomOAuth2Credential convert(long discordId, OAuth2Credential oA // OAuth2 OAuth2IdentityProvider oAuth2IdentityProvider = Main.getInstance().getNotifier().getCredentialManager().getIdentityProviderByName("twitch") .filter(idp -> idp.getProviderType().equalsIgnoreCase("oauth2") && idp instanceof OAuth2IdentityProvider) - .map(idp -> (OAuth2IdentityProvider) idp) + .map(OAuth2IdentityProvider.class::cast) .orElseThrow(() -> new RuntimeException("Can't find a unique identity provider for the specified credential!")); Optional enrichedCredential = oAuth2IdentityProvider.getAdditionalCredentialInformation(oAuth2Credential); diff --git a/src/main/java/de/presti/ree6/utils/oauth/DatabaseStorageBackend.java b/src/main/java/de/presti/ree6/utils/oauth/DatabaseStorageBackend.java new file mode 100644 index 000000000..917f263af --- /dev/null +++ b/src/main/java/de/presti/ree6/utils/oauth/DatabaseStorageBackend.java @@ -0,0 +1,81 @@ +package de.presti.ree6.utils.oauth; + +import com.github.philippheuer.credentialmanager.api.IStorageBackend; +import com.github.philippheuer.credentialmanager.domain.Credential; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.TwitchIntegration; + +import java.util.*; + +/** + * The Storage backend to allow the Twitch4J CredentialManager to store the Data in our Database. + */ +public class DatabaseStorageBackend implements IStorageBackend { + + /** + * Load the Credentials + * + * @return List Credential + */ + @Override + public List loadCredentials() { + return SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), + "FROM TwitchIntegration", null).map(twitchIntegrations -> { + List credentials = new ArrayList<>(); + + twitchIntegrations.forEach(twitchIntegration -> credentials.add(new CustomOAuth2Credential(twitchIntegration.getUserId(), "twitch", twitchIntegration.getToken(), + twitchIntegration.getRefresh(), twitchIntegration.getChannelId(), twitchIntegration.getName(), twitchIntegration.getExpiresIn(), Collections.emptyList()))); + return credentials; + }).block(); + } + + /** + * Save the Credentials + * + * @param list List Credential + */ + @Override + public void saveCredentials(List list) { + list.forEach(credential -> { + if (credential instanceof CustomOAuth2Credential oAuth2Credential) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), + "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid", oAuth2Credential.getUserId())).subscribe(twitchIntegrationOptional -> { + TwitchIntegration twitchIntegration = twitchIntegrationOptional.orElse(new TwitchIntegration()); + if (twitchIntegrationOptional.isEmpty()) { + twitchIntegration.setChannelId(oAuth2Credential.getUserId()); + twitchIntegration.setUserId(oAuth2Credential.getDiscordId()); + } + + twitchIntegration.setToken(oAuth2Credential.getAccessToken()); + twitchIntegration.setRefresh(oAuth2Credential.getRefreshToken()); + twitchIntegration.setName(oAuth2Credential.getUserName()); + twitchIntegration.setExpiresIn(oAuth2Credential.getExpiresIn()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(twitchIntegration).block(); + }); + } + }); + } + + /** + * Gets a Credential by UserId + * + * @param userId User Id + * @return Credential + */ + @Override + public Optional getCredentialByUserId(String userId) { + Optional twitchIntegration = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), + "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid", userId)).block(); + + if (twitchIntegration != null && twitchIntegration.isPresent()) { + TwitchIntegration twitchIntegration1 = twitchIntegration.get(); + CustomOAuth2Credential oAuth2Credential + = new CustomOAuth2Credential(twitchIntegration1.getUserId(), "twitch", twitchIntegration1.getToken(), + twitchIntegration1.getRefresh(), twitchIntegration1.getChannelId(), twitchIntegration1.getName(), twitchIntegration1.getExpiresIn(), Collections.emptyList()); + + return Optional.of(oAuth2Credential); + } else { + return Optional.empty(); + } + } +} \ No newline at end of file diff --git a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java index eaf0bca5d..7f2fcc02e 100644 --- a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java +++ b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java @@ -1,5 +1,6 @@ package de.presti.ree6.utils.others; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; @@ -36,47 +37,52 @@ private GuildUtil() { */ public static void handleMemberJoin(Guild guild, Member member) { - if (!SQLSession.getSqlConnector().getSqlWorker().isAutoRoleSetup(guild.getIdLong())) return; + SQLSession.getSqlConnector().getSqlWorker().isAutoRoleSetup(guild.getIdLong()).subscribe(x -> { + if (!x) return; - if (member.getIdLong() == guild.getOwnerIdLong()) return; + if (member.getIdLong() == guild.getOwnerIdLong()) return; - ThreadUtil.createThread(x -> { if (!guild.getSelfMember().canInteract(member)) { log.error("[AutoRole] Failed to give a role, when someone joined the Guild!"); log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getAsMention())) - .queue()); + LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getUser().getName()).subscribe(message -> + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + privateChannel.sendMessage(message) + .queue())); return; } - for (de.presti.ree6.sql.entities.roles.Role roles : SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong())) { - Role role = guild.getRoleById(roles.getRoleId()); + SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong()).subscribe(roles -> { + for (de.presti.ree6.sql.entities.roles.Role roleEntry : roles) { + Role role = guild.getRoleById(roleEntry.getRoleId()); - if (role != null && !guild.getSelfMember().canInteract(role)) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? - "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName())) - .queue()); - return; - } else if (role == null) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.deleted")) - .queue()); + if (role != null && !guild.getSelfMember().canInteract(role)) { + if (guild.getOwner() != null) + LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? + "message.brs.autoRole.hierarchy" + : "message.brs.autoRole.missingPermission", role.getName()).subscribe(message -> + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + privateChannel.sendMessage(message) + .queue())); + return; + } else if (role == null) { + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").subscribe(message -> + privateChannel.sendMessage(message) + .queue())); - SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), roles.getRoleId()); - return; - } + SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), roleEntry.getRoleId()); + return; + } - addRole(guild, member, role); - } - }, null, null, false, true); + addRole(guild, member, role); + } + }); + }); } /** @@ -87,55 +93,58 @@ public static void handleMemberJoin(Guild guild, Member member) { */ public static void handleVoiceLevelReward(Guild guild, Member member) { - if (!SQLSession.getSqlConnector().getSqlWorker().isVoiceLevelRewardSetup(guild.getIdLong())) - return; + SQLSession.getSqlConnector().getSqlWorker().isVoiceLevelRewardSetup(guild.getIdLong()).subscribe(x -> { + if (!x) return; - if (member.getIdLong() == guild.getOwnerIdLong()) return; + if (member.getIdLong() == guild.getOwnerIdLong()) return; - ThreadUtil.createThread(x -> { - long level = SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(guild.getIdLong(), member.getUser().getIdLong()).getLevel(); + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(guild.getIdLong(), member.getUser().getIdLong()).subscribe(data -> { + if (data == null) return; - if (!guild.getSelfMember().canInteract(member)) { - log.error("[AutoRole] Failed to give a role, when someone leveled up in Voice!"); - log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); - log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); + if (!guild.getSelfMember().canInteract(member)) { + log.error("[AutoRole] Failed to give a role, when someone leveled up in Voice!"); + log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); + log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getAsMention())) - .queue()); + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getUser().getName()).subscribe(message -> + privateChannel.sendMessage(message).queue())); - return; - } + return; + } - for (Map.Entry entry : SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(guild.getIdLong()).entrySet()) { + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(guild.getIdLong()).subscribe(roles -> { + for (Map.Entry entry : roles.entrySet()) { - if (entry.getKey() <= level) { + if (entry.getKey() <= data.getLevel()) { - Role role = guild.getRoleById(entry.getValue()); + Role role = guild.getRoleById(entry.getValue()); - if (role != null && !guild.getSelfMember().canInteract(role)) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? + if (role != null && !guild.getSelfMember().canInteract(role)) { + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName())) - .queue()); - return; - } else if (role == null) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.deleted")) - .queue()); - - SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), entry.getValue()); - return; + : "message.brs.autoRole.missingPermission", role.getName()).subscribe(message -> + privateChannel.sendMessage(message).queue())); + return; + } else if (role == null) { + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").subscribe(message -> + privateChannel.sendMessage(message).queue())); + + SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), entry.getValue()); + return; + } + + addRole(guild, member, role); + } } - - addRole(guild, member, role); - } - } - }, null, null, false, true); + }); + }); + }); } /** @@ -146,55 +155,55 @@ public static void handleVoiceLevelReward(Guild guild, Member member) { */ public static void handleChatLevelReward(Guild guild, Member member) { - if (!SQLSession.getSqlConnector().getSqlWorker().isChatLevelRewardSetup(guild.getIdLong())) - return; - - if (member.getIdLong() == guild.getOwnerIdLong()) return; + SQLSession.getSqlConnector().getSqlWorker().isChatLevelRewardSetup(guild.getIdLong()).subscribe(x -> { + if (!x) return; - ThreadUtil.createThread(x -> { + if (member.getIdLong() == guild.getOwnerIdLong()) return; - long level = (SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(guild.getIdLong(), member.getUser().getIdLong()).getLevel()); - - if (!guild.getSelfMember().canInteract(member)) { - log.error("[AutoRole] Failed to give a Role, when someone leveled up in Chat!"); - log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); - log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(guild.getIdLong(), member.getUser().getIdLong()).subscribe(data -> { + if (data == null) return; - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getAsMention())) - .queue()); + if (!guild.getSelfMember().canInteract(member)) { + log.error("[AutoRole] Failed to give a Role, when someone leveled up in Chat!"); + log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); + log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); - return; - } + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getUser().getName()) + .subscribe(message -> privateChannel.sendMessage(message).queue())); + return; + } - for (Map.Entry entry : SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(guild.getIdLong()).entrySet()) { + SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(guild.getIdLong()).subscribe(roles -> { + for (Map.Entry entry : roles.entrySet()) { - if (entry.getKey() <= level) { - Role role = guild.getRoleById(entry.getValue()); + if (entry.getKey() <= data.getLevel()) { + Role role = guild.getRoleById(entry.getValue()); - if (role != null && !guild.getSelfMember().canInteract(role)) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? + if (role != null && !guild.getSelfMember().canInteract(role)) { + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName())) - .queue()); - } else if (role == null) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.deleted")) - .queue()); - - SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), entry.getValue()); - return; + : "message.brs.autoRole.missingPermission", role.getName()).subscribe(message -> + privateChannel.sendMessage(message).queue())); + } else if (role == null) { + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").subscribe(message -> + privateChannel.sendMessage(message).queue())); + + SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), entry.getValue()); + return; + } + + addRole(guild, member, role); + } } - - addRole(guild, member, role); - } - - } - }, null, null, false, true); + }); + }); + }); } /** @@ -213,29 +222,51 @@ private static void addRole(Guild guild, Member member, Role role) { log.error("[AutoRole] Failed to give a Role!"); log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? - "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName())) - .queue()); + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> { + String[] languageResource = getFailedRoleReason(guild, member, role); + LanguageService.getByGuild(guild, languageResource[0], languageResource[1]).subscribe(message -> + privateChannel.sendMessage(message).queue()); + }); } } + /** + * Get a String Array with the Language Path and the correct Parameter. + * + * @param guild the {@link Guild} Entity. + * @param member the {@link Member} Entity. + * @param role the {@link Role} Entity. + * @return the String Array with two entries, 0 = language path and 1 = parameter. + */ + private static String[] getFailedRoleReason(Guild guild, Member member, Role role) { + String languageResource = "message.brs.autoRole.missingPermission"; + + if (!guild.getSelfMember().canInteract(member)) languageResource = "message.brs.autoRole.user"; + if (guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES)) + languageResource = "message.brs.autoRole.hierarchy"; + + return new String[]{languageResource, guild.getSelfMember().canInteract(member) ? role.getName() : member.getUser().getName()}; + } + /** * Get all roles that Ree6 can manage. + * * @param guild the Guild to get the roles from. * @return a List of Roles that Ree6 can manage. */ - public static List getManagableRoles(Guild guild) { + public static List getManageableRoles(Guild guild) { return guild.getRoles().stream().filter(role -> guild.getSelfMember().canInteract(role) && !role.isManaged() && !role.isPublicRole()).toList(); } /** * Checks if a specific user has supported Ree6 via Donations! + * * @param member the User of the current Guild to check. * @return true if the User has supported Ree6 via Donations, false if not. */ public static boolean isSupporter(User member) { + if (member.getId().equalsIgnoreCase(BotConfig.getBotOwner())) return true; + if (!member.getJDA().retrieveEntitlements().excludeEnded(true).skuIds(1165934495447384144L).complete().isEmpty()) { return true; } diff --git a/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java b/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java index 05529c25d..e80fafa53 100644 --- a/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java +++ b/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java @@ -2,6 +2,7 @@ import de.presti.ree6.sql.SQLSession; import de.presti.ree6.bot.BotConfig; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.Arrays; @@ -27,7 +28,7 @@ private ModerationUtil() { * @param guildId the ID of the Guild. * @return an {@link ArrayList} with every Blacklisted word from the Guild. */ - public static List getBlacklist(long guildId) { + public static Mono> getBlacklist(long guildId) { return SQLSession.getSqlConnector().getSqlWorker().getChatProtectorWords(guildId); } @@ -38,8 +39,9 @@ public static List getBlacklist(long guildId) { * @param message the Message-Content. * @return true, if there is a blacklisted for contained. */ - public static boolean checkMessage(long guildId, String message) { - return Arrays.stream(message.toLowerCase().split(" ")).anyMatch(word -> checkBlacklist(guildId, word)); + public static Mono checkMessage(long guildId, String message) { + return getBlacklist(guildId).map(blacklist -> + Arrays.stream(message.toLowerCase().split(" ")).anyMatch(blacklist::contains)); } /** @@ -47,9 +49,9 @@ public static boolean checkMessage(long guildId, String message) { * * @param guildId the ID of the Guild. * @param word the word to check. - * @return true, if there is a blacklisted for contained. + * @return true, if the word is in the blacklist. */ - public static boolean checkBlacklist(long guildId, String word) { + public static Mono checkBlacklist(long guildId, String word) { return SQLSession.getSqlConnector().getSqlWorker().isChatProtectorSetup(guildId, word); } @@ -59,8 +61,9 @@ public static boolean checkBlacklist(long guildId, String word) { * @param guildId the ID of the Guild. * @return true, if the Server should be moderated. */ - public static boolean shouldModerate(long guildId) { - return BotConfig.isModuleActive("moderation") && SQLSession.getSqlConnector().getSqlWorker().isChatProtectorSetup(guildId); + public static Mono shouldModerate(long guildId) { + if (!BotConfig.isModuleActive("moderation")) return Mono.just(false); + return SQLSession.getSqlConnector().getSqlWorker().isChatProtectorSetup(guildId); } /** @@ -70,9 +73,10 @@ public static boolean shouldModerate(long guildId) { * @param word the Word you want to blacklist. */ public static void blacklist(long guildId, String word) { - if (!checkBlacklist(guildId, word)) { + checkBlacklist(guildId, word).subscribe(x -> { + if (x) return; SQLSession.getSqlConnector().getSqlWorker().addChatProtectorWord(guildId, word); - } + }); } /**