Search in sources :

Example 11 with PermissionLevel

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

the class Rules method command_setWelcome.

@CommandSubscriber(command = "setWelcome", help = "Begrüßungsnachricht ändern", permissionLevel = PermissionLevel.ADMIN, pmAllowed = false)
public void command_setWelcome(final IMessage message, final String welcomeMessage) {
    final IGuild guild = message.getGuild();
    final JSONObject guildJSON = getJSONForGuild(guild);
    guildJSON.put("welcome", welcomeMessage);
    saveJSON();
    DiscordIO.sendMessage(message.getChannel(), ":white_check_mark: Begrüßungs-Nachricht geändert:");
    DiscordIO.sendMessage(message.getChannel(), welcomeMessage);
}
Also used : JSONObject(org.json.JSONObject) IGuild(sx.blah.discord.handle.obj.IGuild) CommandSubscriber(de.nikos410.discordbot.framework.annotations.CommandSubscriber)

Example 12 with PermissionLevel

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

the class Rules method command_welcomeTest.

@CommandSubscriber(command = "welcomeTest", help = "Begrüßungsnachricht testen", permissionLevel = PermissionLevel.ADMIN, pmAllowed = false)
public void command_welcomeTest(final IMessage message) {
    final IGuild guild = message.getGuild();
    final JSONObject guildJSON = getJSONForGuild(guild);
    if (guildJSON.has("welcome") && guildJSON.has("rulesDE") && guildJSON.has("footer")) {
        DiscordIO.sendMessage(message.getChannel(), guildJSON.getString("welcome") + "\n\n" + guildJSON.getString("rulesDE") + "\n\n\n" + guildJSON.getString("footer"));
    }
}
Also used : JSONObject(org.json.JSONObject) IGuild(sx.blah.discord.handle.obj.IGuild) CommandSubscriber(de.nikos410.discordbot.framework.annotations.CommandSubscriber)

Example 13 with PermissionLevel

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

the class ModStuff method command_Mute.

@CommandSubscriber(command = "mute", help = "Einen Nutzer für eine bestimmte Zeit muten", pmAllowed = false, permissionLevel = CommandPermissions.MODERATOR)
public void command_Mute(final IMessage message, final String muteUserString, final String muteDurationInput) {
    final List<IUser> mentions = message.getMentions();
    if (mentions.size() < 1) {
        Util.sendMessage(message.getChannel(), ":x: Fehler: Kein Nutzer angegeben!");
        return;
    } else if (mentions.size() > 1) {
        Util.sendMessage(message.getChannel(), ":x: Fehler: mehrere Nutzer erwähnt");
        return;
    }
    final IUser muteUser = mentions.get(0);
    if (muteUser == null) {
        Util.sendMessage(message.getChannel(), ":x: Fehler: Nutzer nicht gefunden!");
        return;
    }
    Pattern pattern = Pattern.compile("(\\d+)\\s?([smhd])\\s?(.*)");
    Matcher matcher = pattern.matcher(muteDurationInput);
    if (!matcher.matches()) {
        Util.sendMessage(message.getChannel(), "Ungültige Eingabe! Mögliche Zeitformate sind s, m, h und d.");
        return;
    }
    IRole muteRole = message.getGuild().getRoleByID(muteRoleID);
    // Wird ausgeführt, um Nutzer wieder zu entmuten
    Runnable unmuteTask = () -> {
        mutedUsers.remove(muteUser.getStringID());
        muteUser.removeRole(muteRole);
        System.out.println("Unmuted user " + Util.makeUserString(muteUser, message.getGuild()) + ".");
    };
    final int muteDuration = Integer.parseInt(matcher.group(1));
    final String muteDurationUnitString = matcher.group(2);
    ChronoUnit muteDurationUnit = parseChronoUnit(muteDurationUnitString);
    if (mutedUsers.containsKey(muteUser.getStringID())) {
        // Überprüfen, ob angegebener Zeitpunkt nach dem bisherigen Zeitpunkt liegt
        ScheduledFuture oldFuture = mutedUsers.get(muteUser.getStringID());
        LocalDateTime oldDateTime = LocalDateTime.now().plusSeconds(oldFuture.getDelay(TimeUnit.SECONDS));
        LocalDateTime newDateTime = LocalDateTime.now().plus(muteDuration, muteDurationUnit);
        if (newDateTime.isBefore(oldDateTime)) {
            // neuer Zeitpunkt ist vor altem -> nichts tun (längerer Mute bleibt bestehen)
            Util.sendMessage(message.getChannel(), "Nutzer ist bereits für einen längeren Zeitraum gemuted!");
            return;
        } else {
            // neuer Zeitpunkt ist nach altem -> neu schedulen
            mutedUsers.remove(muteUser.getStringID(), oldFuture);
            oldFuture.cancel(false);
        }
    } else {
        muteUser.addRole(muteRole);
        System.out.println("Muted user " + Util.makeUserString(muteUser, message.getGuild()) + ".");
    }
    ScheduledFuture newFuture = scheduler.schedule(unmuteTask, muteDuration, chronoUnitToTimeUnit(muteDurationUnit));
    mutedUsers.put(muteUser.getStringID(), newFuture);
    // :mute:
    message.addReaction(ReactionEmoji.of("\uD83D\uDD07"));
    String customMessage = matcher.group(3);
    if (customMessage.isEmpty()) {
        customMessage = "kein";
    }
    final String muteMessage = "**Du wurdest für " + muteDuration + ' ' + muteDurationUnitString + " gemuted!** \nHinweis: _" + customMessage + " _";
    if (!muteUser.isBot()) {
        Util.sendPM(muteUser, muteMessage);
    }
    // Modlog
    IChannel modLogChannel = message.getGuild().getChannelByID(this.modlogChannelID);
    final String modLogMessage = String.format("**%s** hat Nutzer **%s** für %s %s **gemuted**. \nHinweis: _%s _", Util.makeUserString(message.getAuthor(), message.getGuild()), Util.makeUserString(muteUser, message.getGuild()), muteDuration, muteDurationUnitString, customMessage);
    Util.sendMessage(modLogChannel, modLogMessage);
}
Also used : LocalDateTime(java.time.LocalDateTime) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ScheduledFuture(java.util.concurrent.ScheduledFuture) ChronoUnit(java.time.temporal.ChronoUnit) CommandSubscriber(de.nikos410.discordBot.util.modular.annotations.CommandSubscriber)

Example 14 with PermissionLevel

use of de.nikos410.discordbot.framework.PermissionLevel 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 15 with PermissionLevel

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

the class DiscordBot method handleMessage.

/**
 * Process a received or edited message. Check if it contains a command and execute the corresponding method.
 *
 * @param message The received/edited message
 */
private void handleMessage(final IMessage message) {
    final String messageContent = message.getContent();
    // Check if the message starts with the configured prefix
    if (!messageContent.startsWith(this.prefix)) {
        return;
    }
    // Get only the command in lower case without prefix/parameters
    final String commandName = (messageContent.contains(" ") ? // Message contains parameters
    messageContent.substring(this.prefix.length(), messageContent.indexOf(' ')) : // Message doesn't contain parameters
    messageContent.substring(this.prefix.length())).toLowerCase();
    // Check if a command with that name is known
    if (!commands.containsKey(commandName)) {
        return;
    }
    final CommandWrapper command = commands.get(commandName);
    LOG.info("User {} used command {}", UserUtils.makeUserString(message.getAuthor(), message.getGuild()), commandName);
    // The command was received in a PM but is only available on guilds
    if (message.getChannel().isPrivate() && !command.isPmAllowed()) {
        DiscordIO.sendMessage(message.getChannel(), "Dieser Befehl ist nicht in Privatnachrichten verfügbar!");
        LOG.info("CommandWrapper {} is not available in PMs.", commandName);
        return;
    }
    // Check if the user is allowed to use that command
    final PermissionLevel userPermissionLevel = this.getUserPermissionLevel(message.getAuthor(), message.getGuild());
    LOG.debug("Checking permissions. User: {} | Required: {}", userPermissionLevel, command.getPermissionLevel());
    if (userPermissionLevel.getLevel() < command.getPermissionLevel().getLevel()) {
        DiscordIO.sendMessage(message.getChannel(), String.format("Dieser Befehl ist für deine Gruppe (%s) nicht verfügbar.", userPermissionLevel.getName()));
        LOG.info("User {} doesn't have the required permissions for using the command {}.", UserUtils.makeUserString(message.getAuthor(), message.getGuild()), commandName);
        return;
    }
    final int expectedParameterCount = command.getExpectedParameterCount();
    final List<String> parameters = parseParameters(messageContent, commandName, expectedParameterCount, command.isPassContext());
    // Check if the user used the correct number of parameters
    if (parameters.size() < expectedParameterCount) {
        if (command.isIgnoreParameterCount()) {
            while (parameters.size() < expectedParameterCount) {
                parameters.add(null);
            }
        } else {
            DiscordIO.sendMessage(message.getChannel(), String.format("Dieser Befehl benötigt mindestens %s Parameter! (Gegeben: %s)", expectedParameterCount, parameters.size()));
            LOG.info("Wrong number of arguments. Expected number: {} Actual number: {}", expectedParameterCount, parameters.size());
            return;
        }
    }
    executeCommand(command, parameters, message);
}
Also used : CommandWrapper(de.nikos410.discordbot.framework.CommandWrapper) PermissionLevel(de.nikos410.discordbot.framework.PermissionLevel)

Aggregations

CommandSubscriber (de.nikos410.discordbot.framework.annotations.CommandSubscriber)19 JSONObject (org.json.JSONObject)17 IGuild (sx.blah.discord.handle.obj.IGuild)11 CommandSubscriber (de.nikos410.discordBot.util.modular.annotations.CommandSubscriber)4 ChronoUnit (java.time.temporal.ChronoUnit)4 CommandWrapper (de.nikos410.discordbot.framework.CommandWrapper)2 PermissionLevel (de.nikos410.discordbot.framework.PermissionLevel)2 CommandUtils (de.nikos410.discordbot.util.CommandUtils)2 Method (java.lang.reflect.Method)2 ScheduledFuture (java.util.concurrent.ScheduledFuture)2 IChannel (sx.blah.discord.handle.obj.IChannel)2 IUser (sx.blah.discord.handle.obj.IUser)2 CommandModule (de.nikos410.discordBot.util.modular.annotations.CommandModule)1 InitializationException (de.nikos410.discordbot.exception.InitializationException)1 CommandModule (de.nikos410.discordbot.framework.CommandModule)1 ModuleWrapper (de.nikos410.discordbot.framework.ModuleWrapper)1 ModuleStatus (de.nikos410.discordbot.framework.ModuleWrapper.ModuleStatus)1 BotSetup (de.nikos410.discordbot.modules.BotSetup)1 Authorization (de.nikos410.discordbot.util.discord.Authorization)1 DiscordIO (de.nikos410.discordbot.util.discord.DiscordIO)1