Search in sources :

Example 11 with GuildWrapper

use of stream.flarebot.flarebot.objects.GuildWrapper in project FlareBot by FlareBot.

the class Events method handleOfficialGuildStuff.

private boolean handleOfficialGuildStuff(GuildMessageReceivedEvent event, Command command) {
    Guild guild = event.getGuild();
    GuildWrapper wrapper = FlareBotManager.instance().getGuild(guild.getId());
    if (event.getChannel().getIdLong() == 226785954537406464L && !event.getMember().hasPermission(Permission.MESSAGE_MANAGE)) {
        event.getChannel().sendMessage("Heyo " + event.getAuthor().getAsMention() + " please use me in <#226786507065786380>!").queue();
        return false;
    }
    return true;
}
Also used : GuildWrapper(stream.flarebot.flarebot.objects.GuildWrapper) Guild(net.dv8tion.jda.core.entities.Guild)

Example 12 with GuildWrapper

use of stream.flarebot.flarebot.objects.GuildWrapper in project FlareBot by FlareBot.

the class ModlogHandler method handleAction.

/**
 * Handle a ModAction, this will do a bunch of checks and if they pass it will handle said action. For example if
 * you want to ban someone it will do checks like if you can ban that user, ig they're the owner, if you're trying
 * to ban yourself etc. After those pass it will then do the actual banning, post to the modlog and handle any tmp
 * stuff if needed.<br />
 * See also {@link #handleAction(GuildWrapper, TextChannel, User, User, ModAction, String)}
 *
 * @param wrapper   The GuildWrapper of the guild this is being done in.
 * @param channel   The channel this was executed, this is used for failire messages in the checks.
 * @param sender    The person who sent that said action, the user responsible.
 * @param target    The target user to have the action taken against.
 * @param modAction The ModAction to be performed.
 * @param reason    The reason this was done, if this is null it will default to "No Reason Given".
 * @param duration  The duration of said action, this only applies to temp actions, -1 should be passed otherwise.
 */
public void handleAction(GuildWrapper wrapper, TextChannel channel, User sender, User target, ModAction modAction, String reason, long duration) {
    String rsn = (reason == null ? "No reason given!" : "(`" + reason.replaceAll("`", "'") + "`)");
    Member member = null;
    if (target != null) {
        member = wrapper.getGuild().getMember(target);
    }
    if (channel == null)
        return;
    if (member == null && modAction != ModAction.FORCE_BAN && modAction != ModAction.UNBAN) {
        MessageUtils.sendErrorMessage("That user isn't in this server!" + (modAction == ModAction.KICK ? " You can forceban with `{%}forceban <id>` to keep them from coming back." : ""), channel);
        return;
    }
    // Make sure the target user isn't the guild owner
    if (member != null && member.isOwner()) {
        MessageUtils.sendErrorMessage(String.format("Cannot %s **%s** because they're the guild owner!", modAction.getLowercaseName(), MessageUtils.getTag(target)), channel);
        return;
    }
    // Make sure the target user isn't themselves
    if (target != null && sender != null && target.getIdLong() == sender.getIdLong()) {
        MessageUtils.sendErrorMessage(String.format("You cannot %s yourself you daft person!", modAction.getLowercaseName()), channel);
        return;
    }
    if (target != null && target.getIdLong() == FlareBot.instance().getClient().getSelfUser().getIdLong()) {
        if (modAction == ModAction.UNBAN || modAction == ModAction.UNMUTE)
            MessageUtils.sendWarningMessage("W-why would you want to do that in the first place. Meanie :(", channel);
        else
            MessageUtils.sendWarningMessage(String.format("T-that's meannnnnnn :( I can't %s myself and I hope you don't want to either :(", modAction.getLowercaseName()), channel);
        return;
    }
    // Check if the person is below the target in role hierarchy
    if (member != null && sender != null && !canInteract(wrapper.getGuild().getMember(sender), member, wrapper)) {
        MessageUtils.sendErrorMessage(String.format("You cannot %s a user who is higher than you in the role hierarchy!", modAction.getLowercaseName()), channel);
        return;
    }
    // not just kick, ban etc.
    if (member != null && !wrapper.getGuild().getSelfMember().canInteract(member)) {
        MessageUtils.sendErrorMessage(String.format("Cannot " + modAction.getLowercaseName() + " %s! " + "Their highest role is higher than my highest role or they're the guild owner.", MessageUtils.getTag(target)), channel);
        return;
    }
    try {
        // BAN
        switch(modAction) {
            case BAN:
                channel.getGuild().getController().ban(target, 7, reason).queue(aVoid -> channel.sendMessage(new EmbedBuilder().setColor(Color.GREEN).setDescription("The ban hammer has been struck on " + target.getName() + " <:banhammer:368861419602575364>\nReason: " + rsn).setImage(channel.getGuild().getIdLong() == Constants.OFFICIAL_GUILD ? "https://flarebot.stream/img/banhammer.png" : null).build()).queue());
                break;
            case FORCE_BAN:
                channel.getGuild().getController().ban(target.getId(), 7, reason).queue(aVoid -> channel.sendMessage(new EmbedBuilder().setColor(Color.GREEN).setDescription("The ban hammer has been forcefully struck on " + target.getName() + " <:banhammer:368861419602575364>\nReason: " + rsn).setImage(channel.getGuild().getIdLong() == Constants.OFFICIAL_GUILD ? "https://flarebot.stream/img/banhammer.png" : null).build()).queue());
                break;
            case TEMP_BAN:
                {
                    Period period = new Period(duration);
                    channel.getGuild().getController().ban(channel.getGuild().getMember(target), 7, reason).queue(aVoid -> {
                        channel.sendMessage(new EmbedBuilder().setDescription("The ban hammer has been struck on " + target.getName() + " for " + FormatUtils.formatJodaTime(period) + "\nReason: " + rsn).setImage(channel.getGuild().getIdLong() == Constants.OFFICIAL_GUILD ? "https://flarebot.stream/img/banhammer.png" : null).setColor(Color.WHITE).build()).queue();
                        Scheduler.queueFutureAction(channel.getGuild().getIdLong(), channel.getIdLong(), sender.getIdLong(), target.getIdLong(), reason, period, FutureAction.Action.TEMP_BAN);
                    });
                    break;
                }
            case UNBAN:
                wrapper.getGuild().getController().unban(target).queue();
                MessageUtils.sendSuccessMessage("Unbanned " + target.getAsMention() + "!", channel, sender);
                // MUTE
                break;
            case MUTE:
                try {
                    wrapper.getModeration().muteUser(wrapper, wrapper.getGuild().getMember(target));
                } catch (HierarchyException e) {
                    MessageUtils.sendErrorMessage("Cannot apply the mute role, make sure it is below FlareBot in the " + "role hierarchy.", channel);
                    return;
                }
                MessageUtils.sendSuccessMessage("Muted " + target.getAsMention() + "\nReason: " + rsn, channel, sender);
                break;
            case TEMP_MUTE:
                {
                    try {
                        wrapper.getModeration().muteUser(wrapper, wrapper.getGuild().getMember(target));
                    } catch (HierarchyException e) {
                        MessageUtils.sendErrorMessage("Cannot apply the mute role, make sure it is below FlareBot in the " + "role hierarchy.", channel);
                        return;
                    }
                    Period period = new Period(duration);
                    Scheduler.queueFutureAction(channel.getGuild().getIdLong(), channel.getIdLong(), sender.getIdLong(), target.getIdLong(), reason, period, FutureAction.Action.TEMP_MUTE);
                    MessageUtils.sendSuccessMessage("Temporarily Muted " + target.getAsMention() + " for " + FormatUtils.formatJodaTime(period) + "\nReason: " + rsn, channel, sender);
                    break;
                }
            case UNMUTE:
                if (wrapper.getMutedRole() != null && wrapper.getGuild().getMember(target).getRoles().contains(wrapper.getMutedRole())) {
                    wrapper.getModeration().unmuteUser(wrapper, member);
                    MessageUtils.sendSuccessMessage("Unmuted " + target.getAsMention(), channel, sender);
                } else {
                    MessageUtils.sendErrorMessage("That user isn't muted!!", channel);
                }
                // KICK and WARN
                break;
            case KICK:
                channel.getGuild().getController().kick(member, reason).queue(aVoid -> MessageUtils.sendSuccessMessage(target.getName() + " has been kicked from the server!\nReason: " + rsn, channel, sender));
                break;
            case WARN:
                wrapper.addWarning(target, (reason != null ? reason : "No reason provided - action done by " + sender.getName()));
                EmbedBuilder eb = new EmbedBuilder();
                eb.appendDescription("\u26A0 Warned " + MessageUtils.getTag(target) + "\nReason: " + rsn).setColor(Color.WHITE);
                channel.sendMessage(eb.build()).queue();
                break;
            default:
                throw new IllegalArgumentException("An illegal ModAction was attempted to be handled - " + modAction.toString());
        }
    } catch (PermissionException e) {
        MessageUtils.sendErrorMessage(String.format("Cannot " + modAction.getLowercaseName() + " %s! " + "I do not have the `" + e.getPermission().getName() + "` permission!", MessageUtils.getTag(target)), channel);
        return;
    }
    // TODO: Infraction
    postToModlog(wrapper, modAction.getEvent(), target, sender, rsn);
}
Also used : Color(java.awt.Color) Period(org.joda.time.Period) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) FlareBot(stream.flarebot.flarebot.FlareBot) HierarchyException(net.dv8tion.jda.core.exceptions.HierarchyException) GuildWrapper(stream.flarebot.flarebot.objects.GuildWrapper) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) FormatUtils(stream.flarebot.flarebot.util.general.FormatUtils) Permission(net.dv8tion.jda.core.Permission) Scheduler(stream.flarebot.flarebot.scheduler.Scheduler) FutureAction(stream.flarebot.flarebot.scheduler.FutureAction) Constants(stream.flarebot.flarebot.util.Constants) MessageUtils(stream.flarebot.flarebot.util.MessageUtils) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) HierarchyException(net.dv8tion.jda.core.exceptions.HierarchyException) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Period(org.joda.time.Period)

Example 13 with GuildWrapper

use of stream.flarebot.flarebot.objects.GuildWrapper in project FlareBot by FlareBot.

the class EvalCommand method onCommand.

@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 0) {
        channel.sendMessage("Eval something at least smh!").queue();
        return;
    }
    String imports = IMPORTS.stream().map(s -> "import " + s + ".*;").collect(Collectors.joining("\n"));
    ScriptEngine engine = manager.getEngineByName("groovy");
    engine.put("channel", channel);
    engine.put("guild", guild);
    engine.put("message", message);
    engine.put("jda", sender.getJDA());
    engine.put("sender", sender);
    String msg = MessageUtils.getMessage(args);
    final String[] code = { getCode(args) };
    boolean silent = hasOption(Options.SILENT, msg);
    if (hasOption(Options.SNIPPET, msg)) {
        String snippetName = MessageUtils.getNextArgument(msg, Options.SNIPPET.getAsArgument());
        if (snippetName == null) {
            MessageUtils.sendErrorMessage("Please specify the snippet you wish to run! Do `-snippet (name)`", channel);
            return;
        }
        CassandraController.runTask(session -> {
            ResultSet set = session.execute("SELECT encoded_code FROM flarebot.eval_snippets WHERE snippet_name = '" + snippetName + "'");
            Row row = set.one();
            if (row != null) {
                code[0] = StringUtils.newStringUtf8(Base64.getDecoder().decode(row.getString("encoded_code").getBytes()));
            } else {
                MessageUtils.sendErrorMessage("That eval snippet does not exist!", channel);
                code[0] = null;
            }
        });
    }
    if (hasOption(Options.SAVE, msg)) {
        String base64 = Base64.getEncoder().encodeToString(code[0].getBytes());
        CassandraController.runTask(session -> {
            String snippetName = MessageUtils.getNextArgument(msg, Options.SAVE.getAsArgument());
            if (snippetName == null) {
                MessageUtils.sendErrorMessage("Please specify the name of the snippet to save! Do `-save (name)`", channel);
                return;
            }
            if (insertSnippet == null)
                insertSnippet = session.prepare("UPDATE flarebot.eval_snippets SET encoded_code = ? WHERE snippet_name = ?");
            session.execute(insertSnippet.bind().setString(0, base64).setString(1, snippetName));
            MessageUtils.sendSuccessMessage("Saved the snippet `" + snippetName + "`!", channel);
        });
        return;
    }
    if (hasOption(Options.LIST, msg)) {
        ResultSet set = CassandraController.execute("SELECT snippet_name FROM flarebot.eval_snippets");
        if (set == null)
            return;
        MessageUtils.sendInfoMessage("**Available eval snippets**\n" + set.all().stream().map(row -> "`" + row.getString("snippet_name") + "`").collect(Collectors.joining(", ")), channel);
        return;
    }
    if (code[0] == null)
        return;
    final String finalCode = code[0];
    POOL.submit(() -> {
        try {
            String eResult = String.valueOf(engine.eval(imports + '\n' + finalCode));
            if (eResult.length() > 2000) {
                eResult = String.format("Eval too large, result pasted: %s", MessageUtils.paste(eResult));
            }
            if (!silent)
                channel.sendMessage(eResult).queue();
        } catch (Exception e) {
            // FlareBot.LOGGER.error("Error occurred in the evaluator thread pool! " + e.getMessage(), e, Markers.NO_ANNOUNCE);
            channel.sendMessage(MessageUtils.getEmbed(sender).addField("Result: ", "```bf\n" + e.getMessage() + "```", false).build()).queue();
        }
    });
}
Also used : Arrays(java.util.Arrays) Member(net.dv8tion.jda.core.entities.Member) Row(com.datastax.driver.core.Row) TextChannel(net.dv8tion.jda.core.entities.TextChannel) ScriptEngineManager(javax.script.ScriptEngineManager) GuildWrapper(stream.flarebot.flarebot.objects.GuildWrapper) Collectors(java.util.stream.Collectors) Message(net.dv8tion.jda.core.entities.Message) InternalCommand(stream.flarebot.flarebot.commands.InternalCommand) Executors(java.util.concurrent.Executors) PreparedStatement(com.datastax.driver.core.PreparedStatement) Base64(java.util.Base64) List(java.util.List) ResultSet(com.datastax.driver.core.ResultSet) CassandraController(stream.flarebot.flarebot.database.CassandraController) Matcher(java.util.regex.Matcher) User(net.dv8tion.jda.core.entities.User) ScriptEngine(javax.script.ScriptEngine) StringUtils(org.apache.commons.codec.binary.StringUtils) MessageUtils(stream.flarebot.flarebot.util.MessageUtils) Pattern(java.util.regex.Pattern) CommandType(stream.flarebot.flarebot.commands.CommandType) ExecutorService(java.util.concurrent.ExecutorService) ResultSet(com.datastax.driver.core.ResultSet) Row(com.datastax.driver.core.Row) ScriptEngine(javax.script.ScriptEngine)

Example 14 with GuildWrapper

use of stream.flarebot.flarebot.objects.GuildWrapper in project FlareBot by FlareBot.

the class GuildCommand method onCommand.

@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 0) {
        MessageUtils.sendUsage(this, channel, sender, args);
    } else {
        if (args[0].equalsIgnoreCase("block")) {
            if (args.length == 1) {
                handleBlock(channel, channel.getGuild().getId(), null);
            } else if (args.length == 2) {
                handleBlock(channel, args[1], null);
            } else {
                handleBlock(channel, args[1], MessageUtils.getMessage(args, 2));
            }
        } else if (args[0].equalsIgnoreCase("unblock")) {
            if (args.length == 1) {
                handleUnblock(channel, channel.getGuild().getId());
            } else if (args.length == 2) {
                handleUnblock(channel, args[1]);
            }
        } else if (args[0].equalsIgnoreCase("status")) {
            GuildWrapper wrapper = guild;
            if (args.length == 2) {
                if (Getters.getGuildById(args[1]) == null) {
                    MessageUtils.sendErrorMessage("That guild ID is not valid!", channel);
                    return;
                }
                wrapper = FlareBotManager.instance().getGuild(args[1]);
            }
            Guild g = wrapper.getGuild();
            EmbedBuilder embedBuilder = MessageUtils.getEmbed(sender).setColor(guild.isBlocked() ? Color.RED : Color.GREEN);
            embedBuilder.setTitle(g.getName(), null).addField("Beta", String.valueOf(wrapper.getBetaAccess()), true).addField("Blocked", guild.isBlocked() + (guild.isBlocked() ? " (`" + wrapper.getBlockReason() + "`)" : ""), true);
            channel.sendMessage(embedBuilder.build()).queue();
        } else if (args[0].equalsIgnoreCase("beta")) {
            if (args.length == 1) {
                guild.setBetaAccess(!guild.getBetaAccess());
                channel.sendMessage(MessageUtils.getEmbed(sender).setColor(guild.getBetaAccess() ? Color.GREEN : Color.RED).setDescription("This guild has successfully been " + (guild.getBetaAccess() ? "given" : "removed from") + " beta access!").build()).queue();
            } else if (args.length == 2) {
                GuildWrapper guildWrapper = FlareBotManager.instance().getGuild(args[1]);
                if (guildWrapper.getGuild() == null) {
                    MessageUtils.sendErrorMessage("That guild does not exist!", channel);
                } else {
                    guildWrapper.setBetaAccess(!guildWrapper.getBetaAccess());
                    channel.sendMessage(MessageUtils.getEmbed(sender).setColor(guildWrapper.getBetaAccess() ? Color.GREEN : Color.RED).setDescription("The guild `" + guildWrapper.getGuild().getName() + "` has successfully " + "been " + (guildWrapper.getBetaAccess() ? "given" : "removed from") + " beta access!").build()).queue();
                }
            }
        } else if (args[0].equalsIgnoreCase("data")) {
            GuildWrapper wrapper = guild;
            if (args.length == 2)
                wrapper = FlareBotManager.instance().getGuild(args[1]);
            if (wrapper.getGuild() == null) {
                MessageUtils.sendErrorMessage("That guild does not exist!", channel);
            } else {
                try {
                    PrintWriter out = new PrintWriter("data.json");
                    out.println(FlareBot.GSON.toJson(wrapper));
                    out.close();
                } catch (FileNotFoundException e) {
                    FlareBot.LOGGER.error("Failed to write data", e);
                }
                sender.openPrivateChannel().complete().sendFile(new File("data.json"), new MessageBuilder().append('\u200B').build()).queue();
            }
        } else if (args[0].equalsIgnoreCase("save")) {
            GuildWrapper wrapper = guild;
            if (args.length >= 2) {
                wrapper = FlareBotManager.instance().getGuild(Getters.getGuildById(args[1]).getId());
            }
            if (wrapper.getGuild() == null) {
                MessageUtils.sendErrorMessage("Invalid guild ID!", channel);
                return;
            }
            FlareBotManager.instance().saveGuild(wrapper.getGuildId(), wrapper, -1);
            MessageUtils.sendSuccessMessage("Saved " + wrapper.getGuildId() + "'s guild data!", channel);
        } else
            MessageUtils.sendUsage(this, channel, sender, args);
    }
}
Also used : GuildWrapper(stream.flarebot.flarebot.objects.GuildWrapper) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) FileNotFoundException(java.io.FileNotFoundException) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 15 with GuildWrapper

use of stream.flarebot.flarebot.objects.GuildWrapper in project FlareBot by FlareBot.

the class NINOListener method onGuildMessageReceived.

private void onGuildMessageReceived(GuildMessageReceivedEvent event) {
    if (event.getAuthor().isBot())
        return;
    if (event.getMember().hasPermission(event.getChannel(), Permission.MESSAGE_MANAGE))
        return;
    GuildWrapper wrapper = FlareBotManager.instance().getGuild(event.getGuild().getId());
    if (wrapper.getNINO().isEnabled()) {
        // This event is deprecated and will be removed fully soon!
        if (!wrapper.getModeration().isEventEnabled(wrapper, ModlogEvent.INVITE_POSTED) && !wrapper.getModeration().isEventEnabled(wrapper, ModlogEvent.NINO))
            return;
        if (wrapper.getModeration().isEventEnabled(wrapper, ModlogEvent.NINO)) {
            AtomicReference<String> msg = new AtomicReference<>(FormatUtils.stripMentions(event.getMessage().getContentDisplay()));
            URLChecker.instance().checkMessage(wrapper, msg.get(), (flag, url) -> {
                if (flag == null || url == null)
                    return;
                event.getMessage().delete().queue();
                msg.set(FormatUtils.truncate(500, event.getMessage().getContentDisplay()));
                EmbedBuilder eb = new EmbedBuilder().addField("Message", msg.get(), false).addField("Check", flag.toString(), true).addField("Site", url, true);
                if (flag == URLCheckFlag.SUSPICIOUS) {
                    eb.addField(MessageUtils.ZERO_WIDTH_SPACE, "Message was removed due to a suspicious TLD, " + "we delete ones which are commonly known to be used by spammers/scammers. " + "Check this out for more info: https://www.spamhaus.org/statistics/tlds/" + "\nIf you know this URL is perfectly fine and want us to whitelist it globally " + "come to our " + Constants.INVITE_MARKDOWN + " otherwise you can just whitelist for your guild. " + "Check out the NINO command for mor info.", false);
                } else if (flag == URLCheckFlag.PHISHING) {
                    eb.addField(MessageUtils.ZERO_WIDTH_SPACE, "These are sites which we have found to phish for " + "users personal information such as users account info or other. These are mainly " + "ones we know about and have been seen used around Discord. If you wish to report a " + "new one please join our " + Constants.INVITE_MARKDOWN, false);
                }
                ModlogHandler.getInstance().postToModlog(wrapper, ModlogEvent.NINO, event.getAuthor(), eb.getFields().toArray(new MessageEmbed.Field[] {}));
            });
        }
    }
}
Also used : GuildWrapper(stream.flarebot.flarebot.objects.GuildWrapper) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Aggregations

GuildWrapper (stream.flarebot.flarebot.objects.GuildWrapper)23 MessageUtils (stream.flarebot.flarebot.util.MessageUtils)11 TextChannel (net.dv8tion.jda.core.entities.TextChannel)10 CommandType (stream.flarebot.flarebot.commands.CommandType)10 Permission (stream.flarebot.flarebot.permissions.Permission)9 List (java.util.List)8 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)8 Member (net.dv8tion.jda.core.entities.Member)8 Message (net.dv8tion.jda.core.entities.Message)8 User (net.dv8tion.jda.core.entities.User)8 Command (stream.flarebot.flarebot.commands.Command)8 Collectors (java.util.stream.Collectors)7 ArrayList (java.util.ArrayList)6 ButtonGroupConstants (stream.flarebot.flarebot.util.buttons.ButtonGroupConstants)6 Track (com.arsenarsen.lavaplayerbridge.player.Track)5 FlareBot (stream.flarebot.flarebot.FlareBot)5 GeneralUtils (stream.flarebot.flarebot.util.general.GeneralUtils)5 Color (java.awt.Color)4 Pattern (java.util.regex.Pattern)4 net.dv8tion.jda.core.entities (net.dv8tion.jda.core.entities)4