Search in sources :

Example 61 with Subscribe

use of com.google.common.eventbus.Subscribe in project MantaroBot by Mantaro.

the class GameCmds method game.

@Subscribe
public void game(CommandRegistry cr) {
    final NewRateLimiter rateLimiter = new NewRateLimiter(Executors.newSingleThreadScheduledExecutor(), 4, 6, TimeUnit.SECONDS, 450, true) {

        @Override
        protected void onSpamDetected(String key, int times) {
            log.warn("[Game] Spam detected for {} ({} times)!", key, times);
        }
    };
    SimpleTreeCommand gameCommand = (SimpleTreeCommand) cr.register("game", new SimpleTreeCommand(Category.GAMES) {

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Guessing games.").addField("Games", "`~>game character` - **Starts an instance of Guess the character (anime)**.\n" + "`~>game pokemon` - **Starts an instance of who's that pokemon?**\n" + "`~>game number` - **Starts an instance of Guess The Number**`\n" + "`~>game lobby` - **Starts a chunk of different games, for example `~>game lobby pokemon, trivia` will start pokemon and then trivia.**\n" + "`~>game multiple` - **Starts multiple instances of one game, for example `~>game multiple trivia 5` will start trivia 5 times.**\n" + "`~>game wins` - **Shows how many times you've won in games**", false).addField("Considerations", "The pokemon guessing game has around *900 different pokemon* to guess, " + "where the anime guessing game has around 60. The number in the number guessing game is a random number between 0 and 150.\n" + "To start multiple trivia sessions please use `~>game trivia multiple`, not `~>trivia multiple`", false).build();
        }
    }.addSubCommand("character", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            startGame(new Character(), event);
        }
    }).addSubCommand("pokemon", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            startGame(new Pokemon(), event);
        }
    }).addSubCommand("number", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            startGame(new GuessTheNumber(), event);
        }
    }));
    gameCommand.setPredicate(event -> Utils.handleDefaultNewRatelimit(rateLimiter, event.getAuthor(), event));
    gameCommand.createSubCommandAlias("pokemon", "pokémon");
    gameCommand.createSubCommandAlias("number", "guessthatnumber");
    gameCommand.addSubCommand("wins", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            Member member = Utils.findMember(event, event.getMember(), content);
            if (member == null)
                return;
            event.getChannel().sendMessage(EmoteReference.POPPER + member.getEffectiveName() + " has won " + MantaroData.db().getPlayer(member).getData().getGamesWon() + " games").queue();
        }
    });
    gameCommand.addSubCommand("lobby", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            if (content.isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You didn't specify anything to play!").queue();
                return;
            }
            // Stripe all mentions from this.
            String[] split = mentionPattern.matcher(content).replaceAll("").split(", ");
            if (split.length < 1 || split.length == 1) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify two games at least!").queue();
                return;
            }
            LinkedList<Game> gameList = new LinkedList<>();
            for (String s : split) {
                switch(s.replace(" ", "")) {
                    case "pokemon":
                        gameList.add(new Pokemon());
                        break;
                    case "trivia":
                        gameList.add(new Trivia(null));
                        break;
                    case "number":
                        gameList.add(new GuessTheNumber());
                        break;
                    case "character":
                        gameList.add(new Character());
                        break;
                }
            }
            if (gameList.isEmpty() || gameList.size() == 1) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify two games at least (Valid games: character, pokemon, number, trivia)!").queue();
                return;
            }
            startMultipleGames(gameList, event);
        }
    });
    gameCommand.addSubCommand("multiple", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            String[] values = SPLIT_PATTERN.split(content, 2);
            if (values.length < 2) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the game and the number of times to run it").queue();
                return;
            }
            int number;
            try {
                number = Integer.parseInt(values[1]);
            } catch (Exception e) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid number of times!").queue();
                return;
            }
            if (number > 10) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You can only start a maximum of 10 games of the same type at a time!").queue();
                return;
            }
            LinkedList<Game> gameList = new LinkedList<>();
            for (int i = 0; i < number; i++) {
                switch(values[0].replace(" ", "")) {
                    case "pokemon":
                        gameList.add(new Pokemon());
                        break;
                    case "trivia":
                        gameList.add(new Trivia(null));
                        break;
                    case "number":
                        gameList.add(new GuessTheNumber());
                        break;
                    case "character":
                        gameList.add(new Character());
                        break;
                }
            }
            if (gameList.isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a valid game! (Valid games: character, pokemon, number, trivia)").queue();
                return;
            }
            startMultipleGames(gameList, event);
        }
    });
}
Also used : MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Character(net.kodehawa.mantarobot.commands.game.Character) Trivia(net.kodehawa.mantarobot.commands.game.Trivia) LinkedList(java.util.LinkedList) GuessTheNumber(net.kodehawa.mantarobot.commands.game.GuessTheNumber) NewRateLimiter(net.kodehawa.mantarobot.utils.commands.NewRateLimiter) SimpleTreeCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleTreeCommand) Pokemon(net.kodehawa.mantarobot.commands.game.Pokemon) Member(net.dv8tion.jda.core.entities.Member) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 62 with Subscribe

use of com.google.common.eventbus.Subscribe in project MantaroBot by Mantaro.

the class InfoCmds method guildinfo.

@Subscribe
public void guildinfo(CommandRegistry cr) {
    cr.register("serverinfo", new SimpleCommand(Category.INFO) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            Guild guild = event.getGuild();
            TextChannel channel = event.getChannel();
            String roles = guild.getRoles().stream().filter(role -> !guild.getPublicRole().equals(role)).map(Role::getName).collect(Collectors.joining(", "));
            if (roles.length() > 1024)
                roles = roles.substring(0, 1024 - 4) + "...";
            channel.sendMessage(new EmbedBuilder().setAuthor("Server Information", null, guild.getIconUrl()).setColor(guild.getOwner().getColor() == null ? Color.ORANGE : guild.getOwner().getColor()).setDescription("Server information for " + guild.getName()).setThumbnail(guild.getIconUrl()).addField("Users (Online/Unique)", (int) guild.getMembers().stream().filter(u -> !u.getOnlineStatus().equals(OnlineStatus.OFFLINE)).count() + "/" + guild.getMembers().size(), true).addField("Creation Date", guild.getCreationTime().format(DateTimeFormatter.ISO_DATE_TIME).replaceAll("[^0-9.:-]", " "), true).addField("Voice/Text Channels", guild.getVoiceChannels().size() + "/" + guild.getTextChannels().size(), true).addField("Owner", guild.getOwner().getUser().getName() + "#" + guild.getOwner().getUser().getDiscriminator(), true).addField("Region", guild.getRegion() == null ? "Unknown." : guild.getRegion().getName(), true).addField("Roles (" + guild.getRoles().size() + ")", roles, false).setFooter("Server ID: " + String.valueOf(guild.getId()), null).build()).queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Server Info Command").setDescription("**See your server's current stats.**").setColor(event.getGuild().getOwner().getColor() == null ? Color.ORANGE : event.getGuild().getOwner().getColor()).build();
        }
    });
    cr.registerAlias("serverinfo", "guildinfo");
}
Also used : MantaroInfo(net.kodehawa.mantarobot.MantaroInfo) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) DefaultCommandProcessor(net.kodehawa.mantarobot.core.processor.DefaultCommandProcessor) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) Utils(net.kodehawa.mantarobot.utils.Utils) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) MantaroBot(net.kodehawa.mantarobot.MantaroBot) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Permission(net.dv8tion.jda.core.Permission) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) SnowflakeCacheView(net.dv8tion.jda.core.utils.cache.SnowflakeCacheView) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) net.kodehawa.mantarobot.commands.info.stats.manager(net.kodehawa.mantarobot.commands.info.stats.manager) SimpleFileDataManager(net.kodehawa.mantarobot.utils.data.SimpleFileDataManager) ManagementFactory(java.lang.management.ManagementFactory) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) CommandListener(net.kodehawa.mantarobot.core.listeners.command.CommandListener) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) AsyncInfoMonitor(net.kodehawa.mantarobot.commands.info.AsyncInfoMonitor) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) OnlineStatus(net.dv8tion.jda.core.OnlineStatus) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) StatsHelper.calculateInt(net.kodehawa.mantarobot.commands.info.stats.StatsHelper.calculateInt) BLUE_SMALL_MARKER(net.kodehawa.mantarobot.utils.commands.EmoteReference.BLUE_SMALL_MARKER) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) DateTimeFormatter(java.time.format.DateTimeFormatter) MantaroData(net.kodehawa.mantarobot.data.MantaroData) HelpUtils.forType(net.kodehawa.mantarobot.commands.info.HelpUtils.forType) StatsHelper.calculateDouble(net.kodehawa.mantarobot.commands.info.stats.StatsHelper.calculateDouble) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 63 with Subscribe

use of com.google.common.eventbus.Subscribe in project MantaroBot by Mantaro.

the class InfoCmds method stats.

@Subscribe
public void stats(CommandRegistry cr) {
    TreeCommand statsCommand = (TreeCommand) cr.register("stats", new TreeCommand(Category.INFO) {

        @Override
        public Command defaultTrigger(GuildMessageReceivedEvent event, String currentCommand, String attemptedCommand) {
            return new SubCommand() {

                @Override
                protected void call(GuildMessageReceivedEvent event, String content) {
                    if (content.isEmpty()) {
                        event.getChannel().sendMessage(EmoteReference.MEGA + "**[Stats]** Y-Yeah... gathering them, hold on for a bit...").queue(message -> {
                            GuildStatsManager.MILESTONE = (((int) (MantaroBot.getInstance().getGuildCache().size() + 99) / 100) * 100) + 100;
                            List<Guild> guilds = MantaroBot.getInstance().getGuilds();
                            List<VoiceChannel> voiceChannels = MantaroBot.getInstance().getVoiceChannels();
                            List<VoiceChannel> musicChannels = voiceChannels.parallelStream().filter(vc -> vc.getMembers().contains(vc.getGuild().getSelfMember())).collect(Collectors.toList());
                            IntSummaryStatistics usersPerGuild = calculateInt(guilds, value -> value.getMembers().size());
                            IntSummaryStatistics onlineUsersPerGuild = calculateInt(guilds, value -> (int) value.getMembers().stream().filter(member -> !member.getOnlineStatus().equals(OnlineStatus.OFFLINE)).count());
                            DoubleSummaryStatistics onlineUsersPerUserPerGuild = calculateDouble(guilds, value -> (double) value.getMembers().stream().filter(member -> !member.getOnlineStatus().equals(OnlineStatus.OFFLINE)).count() / (double) value.getMembers().size() * 100);
                            DoubleSummaryStatistics listeningUsersPerUsersPerGuilds = calculateDouble(musicChannels, value -> (double) value.getMembers().size() / (double) value.getGuild().getMembers().size() * 100);
                            DoubleSummaryStatistics listeningUsersPerOnlineUsersPerGuilds = calculateDouble(musicChannels, value -> (double) value.getMembers().size() / (double) value.getGuild().getMembers().stream().filter(member -> !member.getOnlineStatus().equals(OnlineStatus.OFFLINE)).count() * 100);
                            IntSummaryStatistics textChannelsPerGuild = calculateInt(guilds, value -> value.getTextChannels().size());
                            IntSummaryStatistics voiceChannelsPerGuild = calculateInt(guilds, value -> value.getVoiceChannels().size());
                            int musicConnections = (int) voiceChannels.stream().filter(voiceChannel -> voiceChannel.getMembers().contains(voiceChannel.getGuild().getSelfMember())).count();
                            long exclusiveness = MantaroBot.getInstance().getGuildCache().stream().filter(g -> g.getMembers().stream().filter(member -> member.getUser().isBot()).count() == 1).count();
                            double musicConnectionsPerServer = (double) musicConnections / (double) guilds.size() * 100;
                            double exclusivenessPercent = (double) exclusiveness / (double) guilds.size() * 100;
                            long bigGuilds = MantaroBot.getInstance().getGuildCache().stream().filter(g -> g.getMembers().size() > 500).count();
                            message.editMessage(new EmbedBuilder().setColor(Color.PINK).setAuthor("Mantaro Statistics", "https://github.com/Kodehawa/MantaroBot/", event.getJDA().getSelfUser().getAvatarUrl()).setThumbnail(event.getJDA().getSelfUser().getAvatarUrl()).setDescription("Well... I did my math!").addField("Users per Guild", String.format(Locale.ENGLISH, "Min: %d\nAvg: %.1f\nMax: %d", usersPerGuild.getMin(), usersPerGuild.getAverage(), usersPerGuild.getMax()), true).addField("Online Users per Server", String.format(Locale.ENGLISH, "Min: %d\nAvg: %.1f\nMax: %d", onlineUsersPerGuild.getMin(), onlineUsersPerGuild.getAverage(), onlineUsersPerGuild.getMax()), true).addField("Online Users per Users per Server", String.format(Locale.ENGLISH, "Min: %.1f%%\nAvg: %.1f%%\nMax: %.1f%%", onlineUsersPerUserPerGuild.getMin(), onlineUsersPerUserPerGuild.getAverage(), onlineUsersPerUserPerGuild.getMax()), true).addField("Text Channels per Server", String.format(Locale.ENGLISH, "Min: %d\nAvg: %.1f\nMax: %d", textChannelsPerGuild.getMin(), textChannelsPerGuild.getAverage(), textChannelsPerGuild.getMax()), true).addField("Voice Channels per Server", String.format(Locale.ENGLISH, "Min: %d\nAvg: %.1f\nMax: %d", voiceChannelsPerGuild.getMin(), voiceChannelsPerGuild.getAverage(), voiceChannelsPerGuild.getMax()), true).addField("Music Listeners per Users per Server", String.format(Locale.ENGLISH, "Min: %.1f%%\nAvg: %.1f%%\nMax: %.1f%%", listeningUsersPerUsersPerGuilds.getMin(), listeningUsersPerUsersPerGuilds.getAverage(), listeningUsersPerUsersPerGuilds.getMax()), true).addField("Music Listeners per Online Users per Server", String.format(Locale.ENGLISH, "Min: %.1f%%\nAvg: %.1f%%\nMax: %.1f%%", listeningUsersPerOnlineUsersPerGuilds.getMin(), listeningUsersPerOnlineUsersPerGuilds.getAverage(), listeningUsersPerOnlineUsersPerGuilds.getMax()), true).addField("Music Connections per Server", String.format(Locale.ENGLISH, "%.1f%% (%d Connections)", musicConnectionsPerServer, musicConnections), true).addField("Total queue size", Long.toString(MantaroBot.getInstance().getAudioManager().getTotalQueueSize()), true).addField("Total commands (including custom)", String.valueOf(DefaultCommandProcessor.REGISTRY.commands().size()), true).addField("Exclusiveness in Total Servers", Math.round(exclusivenessPercent) + "% (" + exclusiveness + ")", false).addField("Big Servers", String.valueOf(bigGuilds), true).setFooter("! Guilds to next milestone (" + GuildStatsManager.MILESTONE + "): " + (GuildStatsManager.MILESTONE - MantaroBot.getInstance().getGuildCache().size()), event.getJDA().getSelfUser().getAvatarUrl()).build()).override(true).queue();
                            TextChannelGround.of(event).dropItemWithChance(4, 5);
                        });
                    } else {
                        onError(event);
                    }
                }
            };
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Statistics command").setDescription("**See the bot, usage or vps statistics**").addField("Usage", "`~>stats <usage/server/cmds/guilds>` - **Returns statistical information**", true).build();
        }
    });
    statsCommand.addSubCommand("usage", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Mantaro's usage information", null, "https://puu.sh/sMsVC/576856f52b.png").setDescription("Hardware and usage information.").setThumbnail("https://puu.sh/suxQf/e7625cd3cd.png").addField("Threads:", getThreadCount() + " Threads", true).addField("Memory Usage:", getTotalMemory() - getFreeMemory() + "MB/" + getMaxMemory() + "MB", true).addField("CPU Cores:", getAvailableProcessors() + " Cores", true).addField("CPU Usage:", String.format("%.2f", getVpsCPUUsage()) + "%", true).addField("Assigned Memory:", getTotalMemory() + "MB", true).addField("Remaining from assigned:", getFreeMemory() + "MB", true).build()).queue();
            TextChannelGround.of(event).dropItemWithChance(4, 5);
        }
    });
    statsCommand.addSubCommand("server", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            TextChannelGround.of(event).dropItemWithChance(4, 5);
            EmbedBuilder embedBuilder = new EmbedBuilder().setAuthor("Mantaro's server usage information", null, "https://puu.sh/sMsVC/576856f52b.png").setThumbnail("https://puu.sh/suxQf/e7625cd3cd.png").addField("CPU Usage", String.format("%.2f", getVpsCPUUsage()) + "%", true).addField("RAM (TOTAL/FREE/USED)", String.format("%.2f", getVpsMaxMemory()) + "GB/" + String.format("%.2f", getVpsFreeMemory()) + "GB/" + String.format("%.2f", getVpsUsedMemory()) + "GB", false);
            event.getChannel().sendMessage(embedBuilder.build()).queue();
        }
    });
    statsCommand.addSubCommand("cmds", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            String[] args = content.split(" ");
            if (args.length > 0) {
                String what = args[0];
                if (what.equals("total")) {
                    event.getChannel().sendMessage(commandStatsManager.fillEmbed(CommandStatsManager.TOTAL_CMDS, baseEmbed(event, "Command Stats | Total")).build()).queue();
                    return;
                }
                if (what.equals("daily")) {
                    event.getChannel().sendMessage(commandStatsManager.fillEmbed(CommandStatsManager.DAY_CMDS, baseEmbed(event, "Command Stats | Daily")).build()).queue();
                    return;
                }
                if (what.equals("hourly")) {
                    event.getChannel().sendMessage(commandStatsManager.fillEmbed(CommandStatsManager.HOUR_CMDS, baseEmbed(event, "Command Stats | Hourly")).build()).queue();
                    return;
                }
                if (what.equals("now")) {
                    event.getChannel().sendMessage(commandStatsManager.fillEmbed(CommandStatsManager.MINUTE_CMDS, baseEmbed(event, "Command Stats | Now")).build()).queue();
                    return;
                }
            }
            // Default
            event.getChannel().sendMessage(baseEmbed(event, "Command Stats").addField("Now", commandStatsManager.resume(CommandStatsManager.MINUTE_CMDS), false).addField("Hourly", commandStatsManager.resume(CommandStatsManager.HOUR_CMDS), false).addField("Daily", commandStatsManager.resume(CommandStatsManager.DAY_CMDS), false).addField("Total", commandStatsManager.resume(CommandStatsManager.TOTAL_CMDS), false).build()).queue();
        }
    });
    statsCommand.addSubCommand("guilds", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            String[] args = content.split(" ");
            if (args.length > 0) {
                String what = args[0];
                if (what.equals("total")) {
                    event.getChannel().sendMessage(guildStatsManager.fillEmbed(GuildStatsManager.TOTAL_EVENTS, baseEmbed(event, "Guild Stats | Total")).build()).queue();
                    return;
                }
                if (what.equals("daily")) {
                    event.getChannel().sendMessage(guildStatsManager.fillEmbed(GuildStatsManager.DAY_EVENTS, baseEmbed(event, "Guild Stats | Daily")).build()).queue();
                    return;
                }
                if (what.equals("hourly")) {
                    event.getChannel().sendMessage(guildStatsManager.fillEmbed(GuildStatsManager.HOUR_EVENTS, baseEmbed(event, "Guild Stats | Hourly")).build()).queue();
                    return;
                }
                if (what.equals("now")) {
                    event.getChannel().sendMessage(guildStatsManager.fillEmbed(GuildStatsManager.MINUTE_EVENTS, baseEmbed(event, "Guild Stats | Now")).build()).queue();
                    return;
                }
            }
            // Default
            event.getChannel().sendMessage(baseEmbed(event, "Guild Stats").addField("Now", guildStatsManager.resume(GuildStatsManager.MINUTE_EVENTS), false).addField("Hourly", guildStatsManager.resume(GuildStatsManager.HOUR_EVENTS), false).addField("Daily", guildStatsManager.resume(GuildStatsManager.DAY_EVENTS), false).addField("Total", guildStatsManager.resume(GuildStatsManager.TOTAL_EVENTS), false).setFooter("Guilds: " + MantaroBot.getInstance().getGuildCache().size(), null).build()).queue();
        }
    });
    statsCommand.addSubCommand("category", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            String[] args = content.split(" ");
            if (args.length > 0) {
                String what = args[0];
                if (what.equals("total")) {
                    event.getChannel().sendMessage(categoryStatsManager.fillEmbed(CategoryStatsManager.TOTAL_CATS, baseEmbed(event, "Category Stats | Total")).build()).queue();
                    return;
                }
                if (what.equals("daily")) {
                    event.getChannel().sendMessage(categoryStatsManager.fillEmbed(CategoryStatsManager.DAY_CATS, baseEmbed(event, "Category Stats | Daily")).build()).queue();
                    return;
                }
                if (what.equals("hourly")) {
                    event.getChannel().sendMessage(categoryStatsManager.fillEmbed(CategoryStatsManager.HOUR_CATS, baseEmbed(event, "Category Stats | Hourly")).build()).queue();
                    return;
                }
                if (what.equals("now")) {
                    event.getChannel().sendMessage(categoryStatsManager.fillEmbed(CategoryStatsManager.MINUTE_CATS, baseEmbed(event, "Category Stats | Now")).build()).queue();
                    return;
                }
            }
            // Default
            event.getChannel().sendMessage(baseEmbed(event, "Category Stats").addField("Now", categoryStatsManager.resume(CategoryStatsManager.MINUTE_CATS), false).addField("Hourly", categoryStatsManager.resume(CategoryStatsManager.HOUR_CATS), false).addField("Daily", categoryStatsManager.resume(CategoryStatsManager.DAY_CATS), false).addField("Total", categoryStatsManager.resume(CategoryStatsManager.TOTAL_CATS), false).build()).queue();
        }
    });
    statsCommand.addSubCommand("custom", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            event.getChannel().sendMessage(customCommandStatsManager.fillEmbed(CustomCommandStatsManager.TOTAL_CUSTOM_CMDS, baseEmbed(event, "CCS Stats | Total")).build()).queue();
        }
    });
    statsCommand.addSubCommand("game", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            event.getChannel().sendMessage(baseEmbed(event, "Game Stats").setDescription(gameStatsManager.resume(GameStatsManager.TOTAL_GAMES)).build()).queue();
        }
    });
}
Also used : MantaroInfo(net.kodehawa.mantarobot.MantaroInfo) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) DefaultCommandProcessor(net.kodehawa.mantarobot.core.processor.DefaultCommandProcessor) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) Utils(net.kodehawa.mantarobot.utils.Utils) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) MantaroBot(net.kodehawa.mantarobot.MantaroBot) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Permission(net.dv8tion.jda.core.Permission) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) SnowflakeCacheView(net.dv8tion.jda.core.utils.cache.SnowflakeCacheView) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) net.kodehawa.mantarobot.commands.info.stats.manager(net.kodehawa.mantarobot.commands.info.stats.manager) SimpleFileDataManager(net.kodehawa.mantarobot.utils.data.SimpleFileDataManager) ManagementFactory(java.lang.management.ManagementFactory) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) CommandListener(net.kodehawa.mantarobot.core.listeners.command.CommandListener) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) AsyncInfoMonitor(net.kodehawa.mantarobot.commands.info.AsyncInfoMonitor) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) OnlineStatus(net.dv8tion.jda.core.OnlineStatus) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) StatsHelper.calculateInt(net.kodehawa.mantarobot.commands.info.stats.StatsHelper.calculateInt) BLUE_SMALL_MARKER(net.kodehawa.mantarobot.utils.commands.EmoteReference.BLUE_SMALL_MARKER) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) DateTimeFormatter(java.time.format.DateTimeFormatter) MantaroData(net.kodehawa.mantarobot.data.MantaroData) HelpUtils.forType(net.kodehawa.mantarobot.commands.info.HelpUtils.forType) StatsHelper.calculateDouble(net.kodehawa.mantarobot.commands.info.stats.StatsHelper.calculateDouble) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 64 with Subscribe

use of com.google.common.eventbus.Subscribe in project MantaroBot by Mantaro.

the class MiscCmds method createPoll.

@Subscribe
public void createPoll(CommandRegistry registry) {
    registry.register("createpoll", new SimpleCommand(Category.MISC) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            Map<String, Optional<String>> opts = StringUtils.parse(args);
            PollBuilder builder = Poll.builder();
            if (!opts.containsKey("time") || !opts.get("time").isPresent()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You didn't include either the `-time` argument or it was empty!\n" + "Example: `~>poll -options \"hi there\",\"wew\",\"owo what's this\" -time 10m20s -name \"test poll\"").queue();
                return;
            }
            if (!opts.containsKey("options") || !opts.get("options").isPresent()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You didn't include either the `-options` argument or it was empty!\n" + "Example: ~>poll -options \"hi there\",\"wew\",\"owo what's this\" -time 10m20s -name \"test poll\"").queue();
                return;
            }
            if (!opts.containsKey("name") || !opts.get("name").isPresent()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You didn't include either the `-name` argument or it was empty!\n" + "Example: ~>poll -options \"hi there\",\"wew\",\"owo what's this\" -time 10m20s -name \"test poll\"").queue();
                return;
            }
            if (opts.containsKey("name") || opts.get("name").isPresent()) {
                builder.setName(opts.get("name").get().replaceAll(String.valueOf('"'), ""));
            }
            String[] options = opts.get("options").get().replaceAll(String.valueOf('"'), "").split(",");
            long timeout = Utils.parseTime(opts.get("time").get());
            builder.setEvent(event).setTimeout(timeout).setOptions(options).build().startPoll();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Poll Command").setDescription("**Creates a poll**").addField("Usage", "`~>poll [-options <options>] [-time <time>] [-name <name>]`", false).addField("Parameters", "`-options` The options to add. Minimum is 2 and maximum is 9. For instance: `Pizza,Spaghetti,Pasta,\"Spiral Nudels\"` (Enclose options with multiple words in double quotes).\n" + "`-time` The time the operation is gonna take. The format is as follows `1m29s` for 1 minute and 21 seconds. Maximum poll runtime is 45 minutes.\n" + "`-name` The name of the poll for reference.", false).addField("Considerations", "To cancel the running poll type &cancelpoll. Only the person who started it or an Admin can cancel it.", false).addField("Example", "~>poll -options \"hi there\",\"wew\",\"owo what's this\" -time 10m20s -name \"test poll\"", false).build();
        }
    });
    registry.registerAlias("createpoll", "poll");
}
Also used : MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) PollBuilder(net.kodehawa.mantarobot.commands.interaction.polls.PollBuilder) Map(java.util.Map) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 65 with Subscribe

use of com.google.common.eventbus.Subscribe in project MantaroBot by Mantaro.

the class ModerationCmds method tempban.

@Subscribe
public void tempban(CommandRegistry cr) {
    cr.register("tempban", new SimpleCommand(Category.MODERATION) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            String reason = content;
            Guild guild = event.getGuild();
            User author = event.getAuthor();
            TextChannel channel = event.getChannel();
            Message receivedMessage = event.getMessage();
            if (!guild.getMember(author).hasPermission(net.dv8tion.jda.core.Permission.BAN_MEMBERS)) {
                channel.sendMessage(EmoteReference.ERROR + "Cannot ban: You have no Ban Members permission.").queue();
                return;
            }
            if (event.getMessage().getMentionedUsers().isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to mention an user!").queue();
                return;
            }
            for (User user : event.getMessage().getMentionedUsers()) {
                reason = reason.replaceAll("(\\s+)?<@!?" + user.getId() + ">(\\s+)?", "");
            }
            int index = reason.indexOf("time:");
            if (index < 0) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot temp ban an user without giving me the time!").queue();
                return;
            }
            String time = reason.substring(index);
            reason = reason.replace(time, "").trim();
            time = time.replaceAll("time:(\\s+)?", "");
            if (reason.isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot temp ban someone without a reason.!").queue();
                return;
            }
            if (time.isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot temp ban someone without giving me the time!").queue();
                return;
            }
            final DBGuild db = MantaroData.db().getGuild(event.getGuild());
            long l = Utils.parseTime(time);
            String finalReason = String.format("Temporally banned by %#s: %s", event.getAuthor(), reason);
            String sTime = StringUtils.parseTime(l);
            receivedMessage.getMentionedUsers().forEach(user -> guild.getController().ban(user, 7).queue(success -> user.openPrivateChannel().queue(privateChannel -> {
                if (!user.isBot()) {
                    privateChannel.sendMessage(String.format("%sYou were **temporarily banned** by %s#%s with reason: %s on server **%s**.", EmoteReference.MEGA, event.getAuthor().getName(), event.getAuthor().getDiscriminator(), finalReason, event.getGuild().getName())).queue();
                }
                db.getData().setCases(db.getData().getCases() + 1);
                db.saveAsync();
                channel.sendMessage(String.format("%s%s (%s got temporarly banned)", EmoteReference.ZAP, modActionQuotes[r.nextInt(modActionQuotes.length)], user.getName())).queue();
                ModLog.log(event.getMember(), user, finalReason, ModLog.ModAction.TEMP_BAN, db.getData().getCases(), sTime);
                MantaroBot.getTempBanManager().addTempban(guild.getId() + ":" + user.getId(), l + System.currentTimeMillis());
                TextChannelGround.of(event).dropItemWithChance(1, 2);
            }), error -> {
                if (error instanceof PermissionException) {
                    channel.sendMessage(String.format("%sError banning %s: (I need the permission %s)", EmoteReference.ERROR, user.getName(), ((PermissionException) error).getPermission())).queue();
                } else {
                    channel.sendMessage(String.format("%sI encountered an unknown error while banning %s", EmoteReference.ERROR, user.getName())).queue();
                    log.warn("Encountered an unexpected error while trying to ban someone.", error);
                }
            }));
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Tempban Command").setDescription("**Temporarily bans an user**").addField("Usage", "`~>tempban <user> <reason> time:<time>`", false).addField("Example", "`~>tempban @Kodehawa example time:1d`", false).addField("Extended usage", "`time` - can be used with the following parameters: " + "d (days), s (second), m (minutes), h (hour). **For example time:1d1h will give a day and an hour.**", false).build();
        }
    });
}
Also used : Module(net.kodehawa.mantarobot.core.modules.Module) StringUtils(net.kodehawa.mantarobot.utils.StringUtils) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) Utils(net.kodehawa.mantarobot.utils.Utils) Random(java.util.Random) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) MantaroBot(net.kodehawa.mantarobot.MantaroBot) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Slf4j(lombok.extern.slf4j.Slf4j) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) ModLog(net.kodehawa.mantarobot.commands.moderation.ModLog) Permission(net.dv8tion.jda.core.Permission) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Aggregations

Subscribe (com.google.common.eventbus.Subscribe)179 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)46 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)44 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)29 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)26 MantaroData (net.kodehawa.mantarobot.data.MantaroData)25 List (java.util.List)23 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)22 Utils (net.kodehawa.mantarobot.utils.Utils)22 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)21 Module (net.kodehawa.mantarobot.core.modules.Module)21 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)18 TimeUnit (java.util.concurrent.TimeUnit)16 Collectors (java.util.stream.Collectors)16 MantaroBot (net.kodehawa.mantarobot.MantaroBot)15 Player (net.kodehawa.mantarobot.db.entities.Player)15 DiscordUtils (net.kodehawa.mantarobot.utils.DiscordUtils)15 RateLimiter (net.kodehawa.mantarobot.utils.commands.RateLimiter)14 SubCommand (net.kodehawa.mantarobot.core.modules.commands.SubCommand)13 DBGuild (net.kodehawa.mantarobot.db.entities.DBGuild)13