Search in sources :

Example 1 with Permission

use of net.dv8tion.jda.core.Permission in project MantaroBot by Mantaro.

the class ModerationCmds method tempban.

@Command
public static 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 = AudioCmdUtils.parseTime(time);
            String finalReason = reason;
            String sTime = StringUtils.parseTime(l);
            receivedMessage.getMentionedUsers().forEach(user -> guild.getController().ban(user, 7).queue(success -> {
                user.openPrivateChannel().complete().sendMessage(EmoteReference.MEGA + "You were **temporarly banned** by " + event.getAuthor().getName() + "#" + event.getAuthor().getDiscriminator() + " with reason: " + finalReason + ".").queue();
                db.getData().setCases(db.getData().getCases() + 1);
                db.saveAsync();
                channel.sendMessage(EmoteReference.ZAP + "You will be missed... or not " + 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(EmoteReference.ERROR + "Error banning " + user.getName() + ": " + "(I need the permission " + ((PermissionException) error).getPermission() + ")").queue();
                } else {
                    channel.sendMessage(EmoteReference.ERROR + "I encountered an unknown error while banning " + user.getName() + ": " + "<" + error.getClass().getSimpleName() + ">: " + error.getMessage()).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 : SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) StringUtils(net.kodehawa.mantarobot.utils.StringUtils) Utils(net.kodehawa.mantarobot.utils.Utils) Module(net.kodehawa.mantarobot.modules.Module) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) AudioCmdUtils(net.kodehawa.mantarobot.commands.music.AudioCmdUtils) MantaroBot(net.kodehawa.mantarobot.MantaroBot) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Permission(net.dv8tion.jda.core.Permission) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) Map(java.util.Map) ManagedDatabase(net.kodehawa.mantarobot.data.db.ManagedDatabase) CommandRegistry(net.kodehawa.mantarobot.modules.CommandRegistry) Command(net.kodehawa.mantarobot.modules.Command) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) PostLoadEvent(net.kodehawa.mantarobot.modules.events.PostLoadEvent) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) Category(net.kodehawa.mantarobot.modules.commands.base.Category) Collectors(java.util.stream.Collectors) Slf4j(lombok.extern.slf4j.Slf4j) ModLog(net.kodehawa.mantarobot.commands.moderation.ModLog) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) GuildData(net.kodehawa.mantarobot.data.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) CommandPermission(net.kodehawa.mantarobot.modules.commands.CommandPermission) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Optional(java.util.Optional) Queue(java.util.Queue) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Command(net.kodehawa.mantarobot.modules.Command)

Example 2 with Permission

use of net.dv8tion.jda.core.Permission in project Ardent by adamint.

the class CommandFactory method pass.

/**
     * Handles generic message events, parses message content
     * and creates a new AsyncCommandExecutor that will execute the command
     *
     * @param event the MessageReceivedEvent to be handled
     */
public void pass(MessageReceivedEvent event, String prefix) {
    try {
        Guild guild = event.getGuild();
        User ardent = guild.getSelfMember().getUser();
        User user = event.getAuthor();
        if (user.isBot())
            return;
        Message message = event.getMessage();
        MessageChannel channel = event.getChannel();
        String[] args = message.getContent().split(" ");
        String rawContent = message.getRawContent();
        if (rawContent.startsWith(guild.getSelfMember().getUser().getAsMention())) {
            rawContent = rawContent.replaceFirst(ardent.getAsMention(), "");
            if (rawContent.length() == 0)
                channel.sendMessage("Type @Ardent [msg] to talk to me or /help to see a list of commands").queue();
            else {
                if (!Ardent.disabledCommands.contains("cleverbot")) {
                    channel.sendMessage(Unirest.post("https://cleverbot.io/1.0/ask").field("user", Ardent.cleverbotUser).field("key", Ardent.cleverbotKey).field("nick", "ardent").field("text", rawContent).asJson().getBody().getObject().getString("response")).queue();
                } else
                    channel.sendMessage("Cleverbot is currently disabled, sorry.").queue();
            }
            return;
        }
        if (!args[0].startsWith(prefix))
            return;
        String cmd = args[0].replaceFirst(prefix, "");
        final boolean[] ranCommand = { false };
        String pre = StringEscapeUtils.escapeJava(prefix);
        if (args[0].startsWith(pre)) {
            args[0] = args[0].replaceFirst(pre, "");
            baseCommands.forEach(command -> {
                if (command.getBotCommand().containsAlias(args[0])) {
                    command.botCommand.usages++;
                    if (!Ardent.disabledCommands.contains(command.getName())) {
                        EntityGuild entityGuild = EntityGuild.get(guild);
                        for (RestrictedUser u : entityGuild.getRestrictedUsers()) {
                            if (u.getUserId().equalsIgnoreCase(user.getId())) {
                                command.sendRestricted(user);
                                return;
                            }
                        }
                        GuildModel guildModel = BaseCommand.asPojo(r.table("guilds").get(guild.getId()).run(connection), GuildModel.class);
                        if (guildModel == null) {
                            guildModel = new GuildModel(guild.getId(), "english", "/");
                            r.table("guilds").insert(r.json(shard.gson.toJson(guildModel))).runNoReply(connection);
                        }
                        if (guildModel.role_permissions != null) {
                            for (RolePermission rolePermission : guildModel.role_permissions) {
                                Member member = guild.getMember(user);
                                Role r = guild.getRoleById(rolePermission.getId());
                                if (r != null && member.getRoles().contains(r) && !member.hasPermission(Permission.MANAGE_SERVER)) {
                                    if (!rolePermission.getCanUseArdentCommands()) {
                                        user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One of " + "your roles, **" + r.getName() + "**, cannot send Ardent commands!").queue());
                                        return;
                                    }
                                    if (!message.getRawContent().toLowerCase().contains("discord.gg") && !rolePermission.getCanSendDiscordInvites()) {
                                        message.delete().queue();
                                        user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One of " + "your roles, **" + r.getName() + "**, cannot send Discord server invite " + "links!").queue());
                                        return;
                                    }
                                    if (!rolePermission.getCanSendLinks()) {
                                        if (message.getContent().toLowerCase().contains("http://") || message.getContent().toLowerCase().contains("https://")) {
                                            message.delete().queue();
                                            user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One" + " of " + "your roles, **" + r.getName() + "**, cannot send websiet links!").queue());
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                        new AsyncCommandExecutor(command.botCommand, guild, channel, event.getAuthor(), message, args, user).run();
                        commandsReceived++;
                        ranCommand[0] = true;
                        UserUtils.addMoney(user, 1);
                    } else {
                        command.sendTranslatedMessage("Sorry, this command is currently disabled and will be re-enabled soon.", channel, user);
                        ranCommand[0] = true;
                    }
                }
            });
        }
        if (!ranCommand[0]) {
            if (!prefix.equalsIgnoreCase("/")) {
                pass(event, "/");
            }
        }
    } catch (Throwable ex) {
        if (ex instanceof PermissionException) {
            event.getAuthor().openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("I don't have permission to " + "send a message in this channel, please tell a server administrator").queue());
        } else {
            new BotException(ex);
        }
    }
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) GuildModel(tk.ardentbot.rethink.models.GuildModel) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) UserUtils(tk.ardentbot.utils.discord.UserUtils) RestrictedUser(tk.ardentbot.utils.models.RestrictedUser) Database.r(tk.ardentbot.rethink.Database.r) HashMap(java.util.HashMap) ChatterBotSession(com.google.code.chatterbotapi.ChatterBotSession) BotException(tk.ardentbot.core.misc.logging.BotException) Shard(tk.ardentbot.main.Shard) RolePermission(tk.ardentbot.rethink.models.RolePermission) EntityGuild(tk.ardentbot.utils.rpg.EntityGuild) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Unirest(com.mashape.unirest.http.Unirest) Permission(net.dv8tion.jda.core.Permission) Database.connection(tk.ardentbot.rethink.Database.connection) MessageReceivedEvent(net.dv8tion.jda.core.events.message.MessageReceivedEvent) StringEscapeUtils(org.apache.commons.lang3.StringEscapeUtils) Ardent(tk.ardentbot.main.Ardent) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) GuildModel(tk.ardentbot.rethink.models.GuildModel) RestrictedUser(tk.ardentbot.utils.models.RestrictedUser) EntityGuild(tk.ardentbot.utils.rpg.EntityGuild) EntityGuild(tk.ardentbot.utils.rpg.EntityGuild) BotException(tk.ardentbot.core.misc.logging.BotException) RolePermission(tk.ardentbot.rethink.models.RolePermission) RestrictedUser(tk.ardentbot.utils.models.RestrictedUser)

Example 3 with Permission

use of net.dv8tion.jda.core.Permission in project Ardent by adamint.

the class Roles method setupSubcommands.

@Override
public void setupSubcommands() throws Exception {
    subcommands.add(new Subcommand("Adds the specified role to a user", "add @User [Role name]", "add") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            if (args.length > 2) {
                Member userMember = guild.getMember(user);
                if (userMember.hasPermission(Permission.MANAGE_SERVER)) {
                    List<User> mentionedUsers = message.getMentionedUsers();
                    if (mentionedUsers.size() > 0) {
                        User mentioned = mentionedUsers.get(0);
                        Member mentionedMember = guild.getMember(mentioned);
                        if (!mentionedMember.hasPermission(userMember.getPermissions())) {
                            String[] split = message.getRawContent().split(" ");
                            StringBuilder role = new StringBuilder();
                            for (int i = 3; i < split.length; i++) {
                                role.append(split[i]);
                                if (i < (split.length - 1))
                                    role.append(" ");
                            }
                            List<Role> roles = guild.getRolesByName(role.toString(), true);
                            if (roles.size() > 0) {
                                try {
                                    Role r = roles.get(0);
                                    guild.getController().addRolesToMember(mentionedMember, r).queue(aVoid -> {
                                        try {
                                            String reply = "Added **{0}** to {1}".replace("{0}", r.getName()).replace("{1}", mentioned.getAsMention());
                                            sendTranslatedMessage(reply, channel, user);
                                        } catch (Exception e) {
                                            new BotException(e);
                                        }
                                    });
                                } catch (PermissionException ex) {
                                    sendTranslatedMessage("I don't have permission to do this", channel, user);
                                }
                            } else
                                sendTranslatedMessage("No roles with that name were found", channel, user);
                        } else
                            sendTranslatedMessage("You cannot modify this user!", channel, user);
                    } else
                        sendTranslatedMessage("You need to mention a user", channel, user);
                } else
                    sendTranslatedMessage("You need the Manage Roles permission", channel, user);
            } else
                sendTranslatedMessage("Please mention a user and type a role name", channel, user);
        }
    });
    subcommands.add(new Subcommand("Removes the specified role from a user", "remove @user [Role name]", "remove") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            if (args.length > 2) {
                Member userMember = guild.getMember(user);
                if (userMember.hasPermission(Permission.MANAGE_SERVER)) {
                    List<User> mentionedUsers = message.getMentionedUsers();
                    if (mentionedUsers.size() > 0) {
                        User mentioned = mentionedUsers.get(0);
                        Member mentionedMember = guild.getMember(mentioned);
                        if (!mentionedMember.hasPermission(userMember.getPermissions())) {
                            String[] split = message.getRawContent().split(" ");
                            StringBuilder role = new StringBuilder();
                            for (int i = 3; i < split.length; i++) {
                                role.append(split[i]);
                                if (i < (split.length - 1))
                                    role.append(" ");
                            }
                            List<Role> roles = guild.getRolesByName(role.toString(), true);
                            if (roles.size() > 0) {
                                try {
                                    Role r = roles.get(0);
                                    guild.getController().removeRolesFromMember(mentionedMember, r).queue(aVoid -> {
                                        try {
                                            String reply = "Successfully removed role {0} from {1}".replace("{0}", r.getName()).replace("{1}", mentioned.getAsMention());
                                            sendTranslatedMessage(reply, channel, user);
                                        } catch (Exception e) {
                                            new BotException(e);
                                        }
                                    });
                                } catch (PermissionException ex) {
                                    sendTranslatedMessage("I don't have permission to do this", channel, user);
                                }
                            } else
                                sendTranslatedMessage("No roles with that name were found", channel, user);
                        } else
                            sendTranslatedMessage("You cannot modify this user!", channel, user);
                    } else
                        sendTranslatedMessage("You need to mention a user", channel, user);
                } else
                    sendTranslatedMessage("You need the Manage Roles permission", channel, user);
            } else
                sendTranslatedMessage("Please mention a user and type a role name", channel, user);
        }
    });
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) List(java.util.List) Permission(net.dv8tion.jda.core.Permission) Command(tk.ardentbot.core.executor.Command) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) Subcommand(tk.ardentbot.core.executor.Subcommand) BotException(tk.ardentbot.core.misc.logging.BotException) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Subcommand(tk.ardentbot.core.executor.Subcommand) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) BotException(tk.ardentbot.core.misc.logging.BotException) BotException(tk.ardentbot.core.misc.logging.BotException) List(java.util.List)

Example 4 with Permission

use of net.dv8tion.jda.core.Permission in project Ardent by adamint.

the class Restrict method setupSubcommands.

@Override
public void setupSubcommands() throws Exception {
    subcommands.add(new Subcommand("Prevent a user from using Ardent commands", "block @User", "block") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            Member member = guild.getMember(user);
            if (member.hasPermission(Permission.MANAGE_SERVER)) {
                List<User> mentionedUsers = message.getMentionedUsers();
                if (mentionedUsers.size() > 0) {
                    for (User mentioned : mentionedUsers) {
                        Member mentionedMember = guild.getMember(mentioned);
                        if (mentionedMember.hasPermission(member.getPermissions()) || mentionedMember.hasPermission(Permission.MANAGE_SERVER) || mentionedMember.getUser().getId().equalsIgnoreCase(guild.getSelfMember().getUser().getId())) {
                            sendTranslatedMessage("You cannot modify this user because they have the same or higher permissions than " + "you.", channel, user);
                            return;
                        }
                        EntityGuild entityGuild = EntityGuild.get(guild);
                        boolean isRestricted = entityGuild.isRestricted(mentioned);
                        if (isRestricted) {
                            sendTranslatedMessage("This user has already been blocked from using commands!", channel, user);
                        } else {
                            RestrictedUser restrictedUser = new RestrictedUser(mentioned.getId(), user.getId(), guild);
                            entityGuild.addRestricted(restrictedUser);
                            r.db("data").table("restricted").insert(r.json(gson.toJson(new RestrictedUserModel(guild.getId(), mentioned.getId(), user.getId())))).run(connection);
                            sendEditedTranslation("{1} has blocked {0} from sending commands", user, channel, mentioned.getName(), user.getName());
                        }
                    }
                } else
                    sendTranslatedMessage("You need to mention one or more users", channel, user);
            } else
                sendTranslatedMessage("You need the Manage Server permission to use this command", channel, user);
        }
    });
    subcommands.add(new Subcommand("Allow a blocked user to run Ardent commands again", "unblock @User", "unblock") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            if (guild.getMember(user).hasPermission(Permission.MANAGE_SERVER)) {
                List<User> mentionedUsers = message.getMentionedUsers();
                if (mentionedUsers.size() > 0) {
                    for (User mentioned : mentionedUsers) {
                        EntityGuild entityGuild = EntityGuild.get(guild);
                        boolean isRestricted = entityGuild.isRestricted(mentioned);
                        if (!isRestricted) {
                            sendEditedTranslation("{0} isn't restricted from sending commands!", user, channel, mentioned.getName());
                        } else {
                            entityGuild.removeRestricted(mentioned.getId());
                            r.db("data").table("restricted").filter(row -> row.g("user_id").eq(mentioned.getId()).and(row.g("guild_id").eq(guild.getId()))).delete().run(connection);
                            sendEditedTranslation("{0} unrestricted {1}, allowing them to use commands again", user, channel, mentioned.getName(), user.getName());
                        }
                    }
                } else
                    sendTranslatedMessage("You need to mention one or more users", channel, user);
            } else
                sendTranslatedMessage("You need the Manage Server permission to use this command", channel, user);
        }
    });
    subcommands.add(new Subcommand("View all the users who have been blocked in your server", "view") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            EntityGuild entityGuild = EntityGuild.get(guild);
            ArrayList<RestrictedUser> restrictedUsers = entityGuild.getRestrictedUsers();
            String title = "Restricted users";
            String restrictedBy = "restricted by";
            StringBuilder response = new StringBuilder();
            response.append("**" + title + "**");
            if (restrictedUsers.size() == 0) {
                response.append("\nNo one");
            } else {
                restrictedUsers.forEach(restrictedUser -> response.append("\n - " + guild.getMemberById(restrictedUser.getUserId()).getUser().getName() + ", " + restrictedBy + " " + guild.getMemberById(restrictedUser.getRestrictedById()).getUser().getName()));
            }
            EmbedBuilder builder = MessageUtils.getDefaultEmbed(user);
            builder.setAuthor(title, getShard().url, guild.getSelfMember().getUser().getAvatarUrl());
            builder.setDescription(response.toString());
            sendEmbed(builder, channel, user);
        }
    });
}
Also used : MessageUtils(tk.ardentbot.utils.discord.MessageUtils) Command(tk.ardentbot.core.executor.Command) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) Subcommand(tk.ardentbot.core.executor.Subcommand) RestrictedUserModel(tk.ardentbot.rethink.models.RestrictedUserModel) RestrictedUser(tk.ardentbot.utils.models.RestrictedUser) Database.r(tk.ardentbot.rethink.Database.r) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) ArrayList(java.util.ArrayList) EntityGuild(tk.ardentbot.utils.rpg.EntityGuild) List(java.util.List) Permission(net.dv8tion.jda.core.Permission) Database.connection(tk.ardentbot.rethink.Database.connection) RestrictedUser(tk.ardentbot.utils.models.RestrictedUser) Subcommand(tk.ardentbot.core.executor.Subcommand) ArrayList(java.util.ArrayList) EntityGuild(tk.ardentbot.utils.rpg.EntityGuild) EntityGuild(tk.ardentbot.utils.rpg.EntityGuild) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) ArrayList(java.util.ArrayList) List(java.util.List) RestrictedUserModel(tk.ardentbot.rethink.models.RestrictedUserModel) RestrictedUser(tk.ardentbot.utils.models.RestrictedUser)

Example 5 with Permission

use of net.dv8tion.jda.core.Permission in project Ardent by adamint.

the class Trivia method setupSubcommands.

@Override
public void setupSubcommands() throws Exception {
    subcommands.add(new Subcommand("Start a new trivia game", "start", "start") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            for (TriviaGame triviaGame : gamesInSession) {
                if (triviaGame.getGuildId().equalsIgnoreCase(guild.getId())) {
                    sendTranslatedMessage("There's already a game in session in this server!", channel, user);
                    return;
                }
            }
            if (gamesSettingUp.contains(guild.getId())) {
                sendTranslatedMessage("There's already a game in session in this server!", channel, user);
                return;
            }
            gamesSettingUp.add(guild.getId());
            sendTranslatedMessage("Do you want to play this solo? Type `yes` if so, or `no` if not", channel, user);
            interactiveOperation(channel, message, (soloMessage) -> {
                String content = soloMessage.getContent();
                boolean solo;
                solo = content.equalsIgnoreCase("yes");
                TriviaGame currentGame = new TriviaGame(user, solo, (TextChannel) channel, 15);
                gamesInSession.add(currentGame);
                sendTranslatedMessage("The game is starting! Type your answers in this channel. You have **15** seconds to answer " + "each question.", channel, user);
                commenceRounds(guild, (TextChannel) channel, user, currentGame);
                gamesSettingUp.remove(guild.getId());
            });
        }
    });
    subcommands.add(new Subcommand("Stop a currently active trivia game", "stop", "stop") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            if (guild.getMember(user).hasPermission(Permission.MANAGE_SERVER)) {
                if (gamesInSession.stream().filter(game -> game.getGuildId().equals(guild.getId())).count() > 0 || gamesSettingUp.contains(guild.getId())) {
                    gamesSettingUp.remove(guild.getId());
                    gamesInSession.removeIf(g -> g.getGuildId().equals(guild.getId()));
                    sendTranslatedMessage("Stopped the trivia game in session.", channel, user);
                } else {
                    sendTranslatedMessage("There isn't a trivia game running!", channel, user);
                }
            } else
                sendTranslatedMessage("You need the Manage Server permission to use this command", channel, user);
        }
    });
}
Also used : Command(tk.ardentbot.core.executor.Command) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) Subcommand(tk.ardentbot.core.executor.Subcommand) BotException(tk.ardentbot.core.misc.logging.BotException) Shard(tk.ardentbot.main.Shard) TriviaQuestion(tk.ardentbot.utils.models.TriviaQuestion) Executors(java.util.concurrent.Executors) ArrayList(java.util.ArrayList) SecureRandom(java.security.SecureRandom) TimeUnit(java.util.concurrent.TimeUnit) GuildUtils(tk.ardentbot.utils.discord.GuildUtils) Permission(net.dv8tion.jda.core.Permission) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TriviaGame(tk.ardentbot.utils.rpg.TriviaGame) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Subcommand(tk.ardentbot.core.executor.Subcommand) TriviaGame(tk.ardentbot.utils.rpg.TriviaGame) BotException(tk.ardentbot.core.misc.logging.BotException)

Aggregations

Permission (net.dv8tion.jda.core.Permission)6 net.dv8tion.jda.core.entities (net.dv8tion.jda.core.entities)6 List (java.util.List)4 Command (tk.ardentbot.core.executor.Command)4 Subcommand (tk.ardentbot.core.executor.Subcommand)4 BotException (tk.ardentbot.core.misc.logging.BotException)4 PermissionException (net.dv8tion.jda.core.exceptions.PermissionException)3 Database.connection (tk.ardentbot.rethink.Database.connection)3 Database.r (tk.ardentbot.rethink.Database.r)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 RestrictedUser (tk.ardentbot.utils.models.RestrictedUser)2 EntityGuild (tk.ardentbot.utils.rpg.EntityGuild)2 ChatterBotSession (com.google.code.chatterbotapi.ChatterBotSession)1 Unirest (com.mashape.unirest.http.Unirest)1 Cursor (com.rethinkdb.net.Cursor)1 SecureRandom (java.security.SecureRandom)1 OffsetDateTime (java.time.OffsetDateTime)1 Map (java.util.Map)1 Optional (java.util.Optional)1