Search in sources :

Example 6 with CommandModule

use of de.nikos410.discordbot.framework.CommandModule in project de-DiscordBot by DACH-Discord.

the class DiscordBot method makeCommandMap.

private void makeCommandMap() {
    this.commands.clear();
    for (final String key : this.loadedModules.keySet()) {
        Object module = this.loadedModules.get(key);
        for (Method method : module.getClass().getMethods()) {
            if (method.isAnnotationPresent(CommandSubscriber.class)) {
                final CommandSubscriber[] annotations = method.getDeclaredAnnotationsByType(CommandSubscriber.class);
                final String command = annotations[0].command();
                final String help = annotations[0].help();
                final boolean pmAllowed = annotations[0].pmAllowed();
                final int permissionLevel = annotations[0].permissionLevel();
                final int parameterCount = method.getParameterCount();
                final boolean passContext = annotations[0].passContext();
                // Mindestens 1 (message), max 6 (message + 5 parameter)
                if (parameterCount > 0 && parameterCount <= 6) {
                    final Command cmd = new Command(module, method, help, pmAllowed, permissionLevel, parameterCount - 1, passContext);
                    this.commands.put(command.toLowerCase(), cmd);
                } else {
                    System.err.println("Ungültige Anzahl Parameter bei Befehl " + command);
                }
            }
        }
        final CommandModule moduleAnnotation = module.getClass().getDeclaredAnnotationsByType(CommandModule.class)[0];
        if (!moduleAnnotation.commandOnly()) {
            try {
                this.client.getDispatcher().registerListener(module);
            } catch (NullPointerException e) {
                System.err.println("[Error] Could not get EventDispatcher: ");
                Util.error(e);
            }
        }
    }
}
Also used : CommandModule(de.nikos410.discordBot.util.modular.annotations.CommandModule) JSONObject(org.json.JSONObject) EmbedObject(sx.blah.discord.api.internal.json.objects.EmbedObject) Method(java.lang.reflect.Method) CommandSubscriber(de.nikos410.discordBot.util.modular.annotations.CommandSubscriber)

Example 7 with CommandModule

use of de.nikos410.discordbot.framework.CommandModule in project de-DiscordBot by DACH-Discord.

the class DiscordBot method unloadModule.

public String unloadModule(final String moduleName) throws NullPointerException {
    if (moduleName.isEmpty()) {
        return "Fehler! Kein Modul angegeben.";
    }
    if (!this.loadedModules.containsKey(moduleName)) {
        return "Fehler! Modul `" + moduleName + "` ist bereits deaktiviert oder existiert nicht.";
    }
    // Modul in andere Map übertragen und entfernen
    final Object module = this.loadedModules.get(moduleName);
    if (module.getClass().isAnnotationPresent(AlwaysLoaded.class)) {
        return "Dieses Modul kann nicht deaktiviert werden.";
    }
    this.unloadedModules.put(moduleName, module);
    this.loadedModules.remove(moduleName);
    this.makeCommandMap();
    // Modul in JSON-Array speichern
    final JSONArray jsonUnloadedModules = this.configJSON.getJSONArray("unloadedModules");
    jsonUnloadedModules.put(moduleName);
    this.saveJSON();
    // EventListener deaktivieren
    final CommandModule moduleAnnotation = module.getClass().getDeclaredAnnotationsByType(CommandModule.class)[0];
    if (!moduleAnnotation.commandOnly()) {
        try {
            this.client.getDispatcher().unregisterListener(module);
        } catch (NullPointerException e) {
            System.err.println("[Error] Could not get EventDispatcher!");
            throw e;
        }
    }
    return ":x: Modul `" + moduleName + "` deaktiviert.";
}
Also used : CommandModule(de.nikos410.discordBot.util.modular.annotations.CommandModule) JSONArray(org.json.JSONArray) JSONObject(org.json.JSONObject) EmbedObject(sx.blah.discord.api.internal.json.objects.EmbedObject)

Example 8 with CommandModule

use of de.nikos410.discordbot.framework.CommandModule in project de-DiscordBot by DACH-Discord.

the class DiscordBot method loadModule.

/**
 * Load a module from a class specified in a {@link ModuleWrapper}
 *
 * @param wrapper The
 */
private CommandModule loadModule(final ModuleWrapper wrapper) {
    LOG.debug("Loading module {}.", wrapper.getName());
    // Check if module is deactivated in config
    final JSONArray jsonUnloadedModules = this.configJSON.getJSONArray("unloadedModules");
    if (!wrapper.getModuleClass().equals(BotSetup.class) && jsonUnloadedModules.toList().contains(wrapper.getName())) {
        LOG.info("Module '{}' is deactivated. Skipping.", wrapper.getName());
        wrapper.setStatus(ModuleStatus.INACTIVE);
        return null;
    }
    LOG.debug("Loading module '{}'.", wrapper.getName());
    final CommandModule moduleInstance = instantiateModule(wrapper.getModuleClass());
    wrapper.setInstance(moduleInstance);
    if (moduleInstance == null) {
        // Module could not be created -> Add to failed modules
        wrapper.setStatus(ModuleStatus.FAILED);
        return null;
    }
    // Fill wrapper fields
    wrapper.setDisplayName(moduleInstance.getDisplayName());
    // Set bot field and run initialization for module
    moduleInstance.setBot(this);
    moduleInstance.init();
    // Register EventListener if needed
    if (moduleInstance.hasEvents()) {
        final EventDispatcher dispatcher = this.client.getDispatcher();
        dispatcher.registerListener(moduleInstance);
    }
    // Register all commands
    wrapper.setCommands(discoverCommands(wrapper));
    wrapper.setStatus(ModuleStatus.ACTIVE);
    LOG.info("Successfully loaded module '{}'.", wrapper.getName());
    return moduleInstance;
}
Also used : CommandModule(de.nikos410.discordbot.framework.CommandModule) EventDispatcher(sx.blah.discord.api.events.EventDispatcher) JSONArray(org.json.JSONArray)

Example 9 with CommandModule

use of de.nikos410.discordbot.framework.CommandModule in project de-DiscordBot by DACH-Discord.

the class DiscordBot method executeCommand.

/**
 * Invoke the method specified in a CommandWrapper with the parameters in a List
 *
 * @param command The instance containing the attributes of the command, specifically the method to invoke
 * @param parameters The parameters to use while invoking the method
 * @param message The message that triggered the command
 */
private void executeCommand(final CommandWrapper command, final List<String> parameters, final IMessage message) {
    LOG.debug("Executing command {} with {} parameters.", command.getName(), parameters.size());
    final Method method = command.getMethod();
    final CommandModule instance = command.getModule().getInstance();
    try {
        switch(parameters.size()) {
            case 0:
                method.invoke(instance, message);
                break;
            case 1:
                method.invoke(instance, message, parameters.get(0));
                break;
            case 2:
                method.invoke(instance, message, parameters.get(0), parameters.get(1));
                break;
            case 3:
                method.invoke(instance, message, parameters.get(0), parameters.get(1), parameters.get(2));
                break;
            case 4:
                method.invoke(instance, message, parameters.get(0), parameters.get(1), parameters.get(2), parameters.get(3));
                break;
            case 5:
                method.invoke(instance, message, parameters.get(0), parameters.get(1), parameters.get(2), parameters.get(3), parameters.get(4));
                break;
            default:
                throw new IllegalArgumentException("Command has an invalid number of arguments. This should never happen.");
        }
    } catch (IllegalAccessException | InvocationTargetException e) {
        final Throwable cause = e.getCause();
        LOG.error("Command '{}' could not be executed.", command.getName(), e.getCause());
        DiscordIO.errorNotify(cause.toString(), message.getChannel());
    }
}
Also used : CommandModule(de.nikos410.discordbot.framework.CommandModule) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 10 with CommandModule

use of de.nikos410.discordbot.framework.CommandModule in project de-DiscordBot by DACH-Discord.

the class DiscordBot method activateModule.

/**
 * Activate a module so the bot loads it
 *
 * @param moduleName The name of the module
 * @return true if everything went fine, false if the module does not exist or is already actived
 */
public ModuleWrapper activateModule(final String moduleName) {
    if (!modules.containsKey(moduleName)) {
        // Module does not exist
        return null;
    }
    final ModuleWrapper module = modules.get(moduleName);
    if (module.getStatus().equals(ModuleStatus.ACTIVE)) {
        // Module is already active
        return null;
    }
    LOG.debug("Removing module from unloaded JSON array");
    removeFromJSONArray(configJSON.getJSONArray("unloadedModules"), moduleName);
    this.saveConfig();
    LOG.info("Activating module '{}'.", moduleName);
    final CommandModule moduleInstance = loadModule(module);
    if (moduleInstance == null) {
        LOG.error("Module {} could not be loaded.", moduleName);
        return module;
    }
    // Run init tasks
    LOG.debug("Running init tasks.");
    moduleInstance.init();
    // This method can only be executed by a command, so we don't have to check if the bot is ready
    moduleInstance.initWhenReady();
    LOG.info("Rebuilding command map to include commands from module '{}'.", moduleName);
    makeCommandMap();
    // Everything went fine
    return module;
}
Also used : CommandModule(de.nikos410.discordbot.framework.CommandModule) ModuleWrapper(de.nikos410.discordbot.framework.ModuleWrapper)

Aggregations

CommandModule (de.nikos410.discordBot.util.modular.annotations.CommandModule)5 CommandModule (de.nikos410.discordbot.framework.CommandModule)5 JSONArray (org.json.JSONArray)4 JSONObject (org.json.JSONObject)4 EmbedObject (sx.blah.discord.api.internal.json.objects.EmbedObject)4 ModuleWrapper (de.nikos410.discordbot.framework.ModuleWrapper)3 Method (java.lang.reflect.Method)3 CommandSubscriber (de.nikos410.discordBot.util.modular.annotations.CommandSubscriber)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 InitializationException (de.nikos410.discordbot.exception.InitializationException)1 Reflections (org.reflections.Reflections)1 EventDispatcher (sx.blah.discord.api.events.EventDispatcher)1 DiscordException (sx.blah.discord.util.DiscordException)1 EmbedBuilder (sx.blah.discord.util.EmbedBuilder)1