Search in sources :

Example 11 with CommandSubscriber

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

the class ModStuff method command_setMuteRole.

@CommandSubscriber(command = "setMuteRole", help = "Mute Rolle einstellen", pmAllowed = false, passContext = false, permissionLevel = PermissionLevel.ADMIN)
public void command_setMuteRole(final IMessage message, final String roleParameter) {
    final IRole muteRole = GuildUtils.getRoleFromMessage(message, roleParameter);
    if (muteRole == null) {
        // No valid role specified
        DiscordIO.sendMessage(message.getChannel(), "Keine gültige Rolle angegeben!");
        return;
    }
    final IGuild guild = message.getGuild();
    final JSONObject guildJSON;
    if (modstuffJSON.has(guild.getStringID())) {
        guildJSON = modstuffJSON.getJSONObject(guild.getStringID());
    } else {
        guildJSON = new JSONObject();
        modstuffJSON.put(guild.getStringID(), guildJSON);
    }
    guildJSON.put("muteRole", muteRole.getLongID());
    saveJSON();
    // :white_check_mark:
    message.addReaction(ReactionEmoji.of("✅"));
}
Also used : JSONObject(org.json.JSONObject) CommandSubscriber(de.nikos410.discordbot.framework.annotations.CommandSubscriber)

Example 12 with CommandSubscriber

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

the class Roll method command_roll.

@CommandSubscriber(command = "roll", help = "Würfeln. Syntax: `roll AnzahlWuerfel;[AugenJeWuerfel=6]`")
public void command_roll(final IMessage commandMessage, final String diceArgsInput) {
    final IChannel channel = commandMessage.getChannel();
    final EmbedBuilder outputBuilder = new EmbedBuilder();
    if (diceArgsInput.matches("^[0-9]+;?[0-9]*")) {
        try {
            final String[] args = diceArgsInput.split(";");
            final int diceCount = Integer.parseInt(args[0]);
            final int dotCount = args.length > 1 ? Integer.parseInt(args[1]) : DEFAULT_DOT_COUNT;
            if (diceCount < 1 || dotCount < 1) {
                throw new NumberFormatException("Würfelanzahl und maximale Augenzahl muss größer als 0 sein!");
            }
            final StringBuilder resultBuilder = new StringBuilder();
            final int sum = IntStream.generate(() -> (rng.nextInt(dotCount) + 1)).limit(diceCount).reduce(0, (int acc, int number) -> {
                resultBuilder.append(number);
                resultBuilder.append("\n");
                return acc + number;
            });
            resultBuilder.append(MessageFormat.format("Sum: {0}", sum));
            outputBuilder.appendField(MessageFormat.format("Würfelt {0} Würfel mit einer maximalen Augenzahl von {1}!", diceCount, dotCount), resultBuilder.toString(), false);
            EmbedObject rollObject = outputBuilder.build();
            DiscordIO.sendEmbed(channel, rollObject);
        } catch (NumberFormatException ex) {
            DiscordIO.sendMessage(channel, MessageFormat.format("Konnte Eingabe '{0}' nicht verarbeiten." + "Bitte sicherstellen, dass sowohl die Würfelanzahl als auch die maximale Augenzahl Integer-Zahlen > 0 sind!", diceArgsInput));
        }
    } else {
        DiscordIO.sendMessage(channel, "Syntax: `roll AnzahlWürfel;[AugenJeWürfel=6]`");
    }
}
Also used : EmbedBuilder(sx.blah.discord.util.EmbedBuilder) IChannel(sx.blah.discord.handle.obj.IChannel) EmbedObject(sx.blah.discord.api.internal.json.objects.EmbedObject) CommandSubscriber(de.nikos410.discordbot.framework.annotations.CommandSubscriber)

Example 13 with CommandSubscriber

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

the class GeneralCommands method command_uptime.

@CommandSubscriber(command = "uptime", help = "Zeigt seit wann der Bot online ist")
public void command_uptime(final IMessage message) {
    final DateTimeFormatter timeStampFormatter = DateTimeFormatter.ofPattern("dd.MM. | HH:mm");
    DiscordIO.sendMessage(message.getChannel(), String.format("Online seit: %s", startupTimestamp.format(timeStampFormatter)));
}
Also used : DateTimeFormatter(java.time.format.DateTimeFormatter) CommandSubscriber(de.nikos410.discordbot.framework.annotations.CommandSubscriber)

Example 14 with CommandSubscriber

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

the class GeneralCommands method command_quote.

@CommandSubscriber(command = "quote", help = "Zitiert die Nachricht mit der angegebenen ID.", pmAllowed = false, passContext = false)
public void command_quote(final IMessage commandMessage, final String id) {
    if (id.isEmpty()) {
        DiscordIO.sendMessage(commandMessage.getChannel(), "Keine ID angegeben!");
        return;
    }
    final IUser commandAuthor = commandMessage.getAuthor();
    final IGuild guild = commandMessage.getGuild();
    if (!id.matches("^[0-9]{18}$")) {
        DiscordIO.sendMessage(commandMessage.getChannel(), "Keine gültige ID eingegeben!");
        return;
    }
    final long quoteMessageID = Long.parseLong(id);
    final Optional<IMessage> optQuoteMessage = guild.getChannels().parallelStream().map(c -> c.fetchMessage(quoteMessageID)).filter(Objects::nonNull).findFirst();
    if (!optQuoteMessage.isPresent()) {
        DiscordIO.sendMessage(commandMessage.getChannel(), String.format("Nachricht mit der ID `%s` nicht gefunden!", quoteMessageID));
        return;
    }
    final IMessage quoteMessage = optQuoteMessage.get();
    commandMessage.delete();
    final IUser quoteAuthor = quoteMessage.getAuthor();
    final IRole quoteAuthorTopRole = UserUtils.getTopRole(quoteAuthor, quoteMessage.getGuild());
    EmbedBuilder embedBuilder = new EmbedBuilder();
    embedBuilder.withAuthorIcon(quoteAuthor.getAvatarURL());
    embedBuilder.withAuthorName(UserUtils.makeUserString(quoteAuthor, guild));
    embedBuilder.withDesc(quoteMessage.getContent());
    embedBuilder.withColor(quoteAuthorTopRole.getColor());
    final DateTimeFormatter timestampFormatter = DateTimeFormatter.ofPattern("dd.MM.YYYY, HH:mm");
    final LocalDateTime timestamp = LocalDateTime.ofInstant(quoteMessage.getTimestamp(), ZoneOffset.UTC);
    final String timestampString = timestamp.format(timestampFormatter);
    embedBuilder.withFooterText(String.format("%s | Zitiert von: %s", timestampString, UserUtils.makeUserString(commandAuthor, guild)));
    DiscordIO.sendEmbed(commandMessage.getChannel(), embedBuilder.build());
}
Also used : LocalDateTime(java.time.LocalDateTime) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) IRole(sx.blah.discord.handle.obj.IRole) IMessage(sx.blah.discord.handle.obj.IMessage) IUser(sx.blah.discord.handle.obj.IUser) IGuild(sx.blah.discord.handle.obj.IGuild) DateTimeFormatter(java.time.format.DateTimeFormatter) CommandSubscriber(de.nikos410.discordbot.framework.annotations.CommandSubscriber)

Example 15 with CommandSubscriber

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

the class DiscordBot method discoverCommands.

private List<CommandWrapper> discoverCommands(final ModuleWrapper moduleWrapper) {
    LOG.debug("Registering command(s) for module '{}'.", moduleWrapper.getName());
    final List<CommandWrapper> commands = new LinkedList<>();
    final Method[] allMethods = moduleWrapper.getModuleClass().getMethods();
    final List<Method> commandMethods = Arrays.stream(allMethods).filter(module -> module.isAnnotationPresent(CommandSubscriber.class)).collect(Collectors.toList());
    for (final Method method : commandMethods) {
        // Register methods with the @CommandSubscriber as commands
        // All annotations of type CommandSubscriber declared for that Method. Should be exactly 1
        final CommandSubscriber annotation = method.getDeclaredAnnotationsByType(CommandSubscriber.class)[0];
        // Get command properties from annotation
        final String commandName = annotation.command();
        final String commandHelp = annotation.help();
        final boolean pmAllowed = annotation.pmAllowed();
        final PermissionLevel permissionLevel = annotation.permissionLevel();
        final boolean passContext = annotation.passContext();
        final boolean ignoreParameterCount = annotation.ignoreParameterCount();
        final int parameterCount = method.getParameterCount() - 1;
        if ((parameterCount >= 0 && parameterCount <= 5) || ignoreParameterCount) {
            final CommandWrapper commandWrapper = new CommandWrapper(commandName, commandHelp, moduleWrapper, method, pmAllowed, permissionLevel, parameterCount, passContext, ignoreParameterCount);
            commands.add(commandWrapper);
            LOG.debug("Saved command '{}'.", commandName);
        } else {
            LOG.warn("Method '{}' has an invalid number of arguments. Skipping", commandName);
        }
    }
    return commands;
}
Also used : java.util(java.util) Authorization(de.nikos410.discordbot.util.discord.Authorization) LoggerFactory(org.slf4j.LoggerFactory) MessageUpdateEvent(sx.blah.discord.handle.impl.events.guild.channel.message.MessageUpdateEvent) Reflections(org.reflections.Reflections) DiscordIO(de.nikos410.discordbot.util.discord.DiscordIO) ModuleWrapper(de.nikos410.discordbot.framework.ModuleWrapper) ReadyEvent(sx.blah.discord.handle.impl.events.ReadyEvent) MessageReceivedEvent(sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent) JSONObject(org.json.JSONObject) ModuleStatus(de.nikos410.discordbot.framework.ModuleWrapper.ModuleStatus) InitializationException(de.nikos410.discordbot.exception.InitializationException) CommandWrapper(de.nikos410.discordbot.framework.CommandWrapper) Method(java.lang.reflect.Method) Path(java.nio.file.Path) Logger(org.slf4j.Logger) PermissionLevel(de.nikos410.discordbot.framework.PermissionLevel) Files(java.nio.file.Files) CommandModule(de.nikos410.discordbot.framework.CommandModule) EventSubscriber(sx.blah.discord.api.events.EventSubscriber) Instant(java.time.Instant) UserUtils(de.nikos410.discordbot.util.discord.UserUtils) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) TimeUnit(java.util.concurrent.TimeUnit) IDiscordClient(sx.blah.discord.api.IDiscordClient) sx.blah.discord.handle.obj(sx.blah.discord.handle.obj) ChronoUnit(java.time.temporal.ChronoUnit) BotSetup(de.nikos410.discordbot.modules.BotSetup) IOUtil(de.nikos410.discordbot.util.io.IOUtil) Paths(java.nio.file.Paths) DiscordException(sx.blah.discord.util.DiscordException) EventDispatcher(sx.blah.discord.api.events.EventDispatcher) CommandSubscriber(de.nikos410.discordbot.framework.annotations.CommandSubscriber) JSONArray(org.json.JSONArray) CommandWrapper(de.nikos410.discordbot.framework.CommandWrapper) Method(java.lang.reflect.Method) PermissionLevel(de.nikos410.discordbot.framework.PermissionLevel) CommandSubscriber(de.nikos410.discordbot.framework.annotations.CommandSubscriber)

Aggregations

CommandSubscriber (de.nikos410.discordbot.framework.annotations.CommandSubscriber)30 JSONObject (org.json.JSONObject)23 IGuild (sx.blah.discord.handle.obj.IGuild)14 CommandSubscriber (de.nikos410.discordBot.util.modular.annotations.CommandSubscriber)12 EmbedBuilder (sx.blah.discord.util.EmbedBuilder)11 ChronoUnit (java.time.temporal.ChronoUnit)5 EmbedObject (sx.blah.discord.api.internal.json.objects.EmbedObject)5 LocalDateTime (java.time.LocalDateTime)4 DateTimeFormatter (java.time.format.DateTimeFormatter)4 IChannel (sx.blah.discord.handle.obj.IChannel)4 ModuleWrapper (de.nikos410.discordbot.framework.ModuleWrapper)3 CommandUtils (de.nikos410.discordbot.util.CommandUtils)3 Method (java.lang.reflect.Method)3 ScheduledFuture (java.util.concurrent.ScheduledFuture)3 JSONArray (org.json.JSONArray)3 IUser (sx.blah.discord.handle.obj.IUser)3 CommandModule (de.nikos410.discordBot.util.modular.annotations.CommandModule)2 CommandWrapper (de.nikos410.discordbot.framework.CommandWrapper)2 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2