Search in sources :

Example 1 with Context

use of me.shadorc.shadbot.core.command.Context in project Shadbot by Shadorc.

the class WallpaperCmd method execute.

@Override
public void execute(Context context) throws MissingArgumentException, IllegalCmdArgumentException {
    LoadingMessage loadingMsg = new LoadingMessage("Loading wallpaper...", context.getChannel());
    loadingMsg.send();
    if (wallhaven == null) {
        wallhaven = new Wallhaven(APIKeys.get(APIKey.WALLHAVEN_LOGIN), APIKeys.get(APIKey.WALLHAVEN_PASSWORD));
    }
    Options options = new Options();
    options.addOption("p", PURITY, true, FormatUtils.format(Purity.values(), purity -> purity.toString().toLowerCase(), ", "));
    options.addOption("c", CATEGORY, true, FormatUtils.format(Category.values(), cat -> cat.toString().toLowerCase(), ", "));
    Option ratioOpt = new Option("rat", RATIO, true, "image ratio");
    ratioOpt.setValueSeparator('x');
    options.addOption(ratioOpt);
    Option resOpt = new Option("res", RESOLUTION, true, "image resolution");
    resOpt.setValueSeparator('x');
    options.addOption(resOpt);
    Option keyOpt = new Option("k", KEYWORD, true, KEYWORD);
    keyOpt.setValueSeparator(',');
    options.addOption(keyOpt);
    CommandLine cmdLine;
    try {
        List<String> args = StringUtils.split(context.getArg());
        cmdLine = new DefaultParser().parse(options, args.toArray(new String[args.size()]));
    } catch (UnrecognizedOptionException | org.apache.commons.cli.MissingArgumentException err) {
        loadingMsg.delete();
        throw new IllegalCmdArgumentException(String.format("%s. Use `%shelp %s` for more information.", err.getMessage(), context.getPrefix(), this.getName()));
    } catch (ParseException err) {
        loadingMsg.delete();
        Utils.handle("getting a wallpaper", context, err);
        return;
    }
    Purity purity = this.parseEnum(loadingMsg, context, Purity.class, PURITY, cmdLine.getOptionValue(PURITY, Purity.SFW.toString()));
    if ((purity.equals(Purity.NSFW) || purity.equals(Purity.SKETCHY)) && !context.getChannel().isNSFW()) {
        loadingMsg.edit(TextUtils.mustBeNSFW(context.getPrefix()));
        return;
    }
    SearchQueryBuilder queryBuilder = new SearchQueryBuilder();
    queryBuilder.purity(purity);
    if (cmdLine.hasOption(CATEGORY)) {
        queryBuilder.categories(this.parseEnum(loadingMsg, context, Category.class, CATEGORY, cmdLine.getOptionValue(CATEGORY)));
    }
    if (cmdLine.hasOption(RATIO)) {
        Dimension dim = this.parseDim(loadingMsg, context, RATIO, cmdLine.getOptionValues(RATIO));
        queryBuilder.ratios(new Ratio((int) dim.getWidth(), (int) dim.getHeight()));
    }
    if (cmdLine.hasOption(RESOLUTION)) {
        Dimension dim = this.parseDim(loadingMsg, context, RESOLUTION, cmdLine.getOptionValues(RESOLUTION));
        queryBuilder.resolutions(new Resolution((int) dim.getWidth(), (int) dim.getHeight()));
    }
    if (cmdLine.hasOption(KEYWORD)) {
        queryBuilder.keywords(cmdLine.getOptionValues(KEYWORD));
    }
    try {
        List<Wallpaper> wallpapers = wallhaven.search(queryBuilder.pages(1).build());
        if (wallpapers.isEmpty()) {
            loadingMsg.edit(TextUtils.noResult(context.getMessage().getContent()));
            return;
        }
        Wallpaper wallpaper = wallpapers.get(ThreadLocalRandom.current().nextInt(wallpapers.size()));
        String tags = FormatUtils.format(wallpaper.getTags(), tag -> String.format("`%s`", StringUtils.remove(tag.toString(), "#")), " ");
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().withAuthorName("Wallpaper").withAuthorUrl(wallpaper.getUrl()).withImage(wallpaper.getImageUrl()).appendField("Resolution", wallpaper.getResolution().toString(), false).appendField("Tags", tags, false);
        loadingMsg.edit(embed.build());
    } catch (ConnectionException err) {
        loadingMsg.delete();
        Utils.handle("getting a wallpaper", context, err.getCause());
    }
}
Also used : HelpBuilder(me.shadorc.shadbot.utils.embed.HelpBuilder) Wallhaven(com.ivkos.wallhaven4j.Wallhaven) CommandCategory(me.shadorc.shadbot.core.command.CommandCategory) Options(org.apache.commons.cli.Options) Ratio(com.ivkos.wallhaven4j.models.misc.Ratio) Category(com.ivkos.wallhaven4j.models.misc.enums.Category) Purity(com.ivkos.wallhaven4j.models.misc.enums.Purity) DefaultParser(org.apache.commons.cli.DefaultParser) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) StringUtils(me.shadorc.shadbot.utils.StringUtils) Command(me.shadorc.shadbot.core.command.annotation.Command) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) TextUtils(me.shadorc.shadbot.utils.TextUtils) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) CommandLine(org.apache.commons.cli.CommandLine) Option(org.apache.commons.cli.Option) Utils(me.shadorc.shadbot.utils.Utils) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) Resolution(com.ivkos.wallhaven4j.models.misc.Resolution) RateLimited(me.shadorc.shadbot.core.command.annotation.RateLimited) UnrecognizedOptionException(org.apache.commons.cli.UnrecognizedOptionException) SearchQueryBuilder(com.ivkos.wallhaven4j.util.searchquery.SearchQueryBuilder) APIKeys(me.shadorc.shadbot.data.APIKeys) EmbedObject(sx.blah.discord.api.internal.json.objects.EmbedObject) FormatUtils(me.shadorc.shadbot.utils.FormatUtils) IllegalCmdArgumentException(me.shadorc.shadbot.exception.IllegalCmdArgumentException) CastUtils(me.shadorc.shadbot.utils.CastUtils) ConnectionException(com.ivkos.wallhaven4j.util.exceptions.ConnectionException) Dimension(java.awt.Dimension) List(java.util.List) Context(me.shadorc.shadbot.core.command.Context) ParseException(org.apache.commons.cli.ParseException) AbstractCommand(me.shadorc.shadbot.core.command.AbstractCommand) APIKey(me.shadorc.shadbot.data.APIKeys.APIKey) EmbedUtils(me.shadorc.shadbot.utils.embed.EmbedUtils) Wallpaper(com.ivkos.wallhaven4j.models.wallpaper.Wallpaper) Options(org.apache.commons.cli.Options) CommandCategory(me.shadorc.shadbot.core.command.CommandCategory) Category(com.ivkos.wallhaven4j.models.misc.enums.Category) Purity(com.ivkos.wallhaven4j.models.misc.enums.Purity) UnrecognizedOptionException(org.apache.commons.cli.UnrecognizedOptionException) IllegalCmdArgumentException(me.shadorc.shadbot.exception.IllegalCmdArgumentException) Ratio(com.ivkos.wallhaven4j.models.misc.Ratio) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) DefaultParser(org.apache.commons.cli.DefaultParser) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) Dimension(java.awt.Dimension) CommandLine(org.apache.commons.cli.CommandLine) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) SearchQueryBuilder(com.ivkos.wallhaven4j.util.searchquery.SearchQueryBuilder) Option(org.apache.commons.cli.Option) Wallpaper(com.ivkos.wallhaven4j.models.wallpaper.Wallpaper) Wallhaven(com.ivkos.wallhaven4j.Wallhaven) ParseException(org.apache.commons.cli.ParseException) ConnectionException(com.ivkos.wallhaven4j.util.exceptions.ConnectionException) Resolution(com.ivkos.wallhaven4j.models.misc.Resolution)

Example 2 with Context

use of me.shadorc.shadbot.core.command.Context in project Shadbot by Shadorc.

the class ThisDayCmd method execute.

@Override
public void execute(Context context) {
    LoadingMessage loadingMsg = new LoadingMessage("Loading information...", context.getChannel());
    loadingMsg.send();
    try {
        Document doc = NetUtils.getDoc(HOME_URL);
        String date = doc.getElementsByClass("date-large").first().attr("datetime");
        Elements eventsElmt = doc.getElementsByClass("event-list event-list--with-advert").first().getElementsByClass("event-list__item");
        String events = eventsElmt.stream().map(elmt -> Jsoup.parse(elmt.html().replaceAll("<b>|</b>", "**")).text()).collect(Collectors.joining("\n\n"));
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().withAuthorName(String.format("On This Day (%s)", date)).withAuthorUrl(HOME_URL).withThumbnail("http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/calendar-icon.png").appendDescription(StringUtils.truncate(events, EmbedBuilder.DESCRIPTION_CONTENT_LIMIT));
        loadingMsg.edit(embed.build());
    } catch (IOException err) {
        loadingMsg.delete();
        Utils.handle("getting events", context, err);
    }
}
Also used : RateLimited(me.shadorc.shadbot.core.command.annotation.RateLimited) HelpBuilder(me.shadorc.shadbot.utils.embed.HelpBuilder) CommandCategory(me.shadorc.shadbot.core.command.CommandCategory) IOException(java.io.IOException) EmbedObject(sx.blah.discord.api.internal.json.objects.EmbedObject) Collectors(java.util.stream.Collectors) StringUtils(me.shadorc.shadbot.utils.StringUtils) Command(me.shadorc.shadbot.core.command.annotation.Command) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) NetUtils(me.shadorc.shadbot.utils.NetUtils) Context(me.shadorc.shadbot.core.command.Context) Document(org.jsoup.nodes.Document) AbstractCommand(me.shadorc.shadbot.core.command.AbstractCommand) Jsoup(org.jsoup.Jsoup) Elements(org.jsoup.select.Elements) EmbedUtils(me.shadorc.shadbot.utils.embed.EmbedUtils) Utils(me.shadorc.shadbot.utils.Utils) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) IOException(java.io.IOException) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements)

Example 3 with Context

use of me.shadorc.shadbot.core.command.Context in project Shadbot by Shadorc.

the class BanCmd method execute.

@Override
public void execute(Context context) throws MissingArgumentException, IllegalCmdArgumentException {
    if (!context.hasArg()) {
        throw new MissingArgumentException();
    }
    List<IUser> mentionedUsers = context.getMessage().getMentions();
    if (mentionedUsers.isEmpty()) {
        throw new MissingArgumentException();
    }
    if (!PermissionUtils.hasPermissions(context.getChannel(), context.getAuthor(), Permissions.BAN)) {
        throw new IllegalArgumentException("You don't have permission to ban.");
    }
    if (!BotUtils.hasPermissions(context.getChannel(), Permissions.BAN)) {
        BotUtils.sendMessage(TextUtils.missingPerm(Permissions.BAN), context.getChannel());
        return;
    }
    if (mentionedUsers.contains(context.getAuthor())) {
        throw new IllegalCmdArgumentException("You cannot ban yourself.");
    }
    for (IUser mentionedUser : mentionedUsers) {
        if (!PermissionUtils.isUserHigher(context.getGuild(), context.getAuthor(), mentionedUser)) {
            throw new IllegalCmdArgumentException(String.format("You can't ban **%s** because he has the same or a higher role " + "position than you in the role hierarchy.", mentionedUser.getName()));
        }
        if (!BotUtils.canInteract(context.getGuild(), mentionedUser)) {
            throw new IllegalCmdArgumentException(String.format("I cannot ban **%s** because he has the same or a higher role " + "position than me in the role hierarchy.", mentionedUser.getName()));
        }
    }
    StringBuilder reason = new StringBuilder();
    reason.append(StringUtils.remove(context.getArg(), FormatUtils.format(mentionedUsers, user -> user.mention(false), " ")).trim());
    if (reason.length() > Ban.MAX_REASON_LENGTH) {
        throw new IllegalCmdArgumentException(String.format("Reason cannot exceed **%d characters**.", Ban.MAX_REASON_LENGTH));
    }
    if (reason.length() == 0) {
        reason.append("Reason not specified.");
    }
    for (IUser user : mentionedUsers) {
        if (!user.isBot()) {
            BotUtils.sendMessage(String.format(Emoji.INFO + " You were banned from the server **%s** by **%s**. Reason: `%s`", context.getGuild().getName(), context.getAuthorName(), reason), user.getOrCreatePMChannel());
        }
        RequestBuffer.request(() -> {
            context.getGuild().banUser(user, reason.toString(), 7);
        }).get();
    }
    BotUtils.sendMessage(String.format(Emoji.INFO + " (Requested by **%s**) **%s** got banned. Reason: `%s`", context.getAuthorName(), FormatUtils.format(mentionedUsers, IUser::getName, ", "), reason), context.getChannel());
}
Also used : IllegalCmdArgumentException(me.shadorc.shadbot.exception.IllegalCmdArgumentException) Ban(sx.blah.discord.util.Ban) RequestBuffer(sx.blah.discord.util.RequestBuffer) HelpBuilder(me.shadorc.shadbot.utils.embed.HelpBuilder) CommandCategory(me.shadorc.shadbot.core.command.CommandCategory) PermissionUtils(sx.blah.discord.util.PermissionUtils) EmbedObject(sx.blah.discord.api.internal.json.objects.EmbedObject) FormatUtils(me.shadorc.shadbot.utils.FormatUtils) BotUtils(me.shadorc.shadbot.utils.BotUtils) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) IllegalCmdArgumentException(me.shadorc.shadbot.exception.IllegalCmdArgumentException) StringUtils(me.shadorc.shadbot.utils.StringUtils) CommandPermission(me.shadorc.shadbot.core.command.CommandPermission) Command(me.shadorc.shadbot.core.command.annotation.Command) List(java.util.List) IUser(sx.blah.discord.handle.obj.IUser) Context(me.shadorc.shadbot.core.command.Context) TextUtils(me.shadorc.shadbot.utils.TextUtils) AbstractCommand(me.shadorc.shadbot.core.command.AbstractCommand) Emoji(me.shadorc.shadbot.utils.object.Emoji) Permissions(sx.blah.discord.handle.obj.Permissions) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) IUser(sx.blah.discord.handle.obj.IUser)

Example 4 with Context

use of me.shadorc.shadbot.core.command.Context in project Shadbot by Shadorc.

the class BlacklistSettingCmd method execute.

@Override
public void execute(Context context, String arg) throws MissingArgumentException, IllegalCmdArgumentException {
    if (arg == null) {
        throw new MissingArgumentException();
    }
    List<String> splitArgs = StringUtils.split(arg, 2);
    if (splitArgs.size() != 2) {
        throw new MissingArgumentException();
    }
    Action action = Utils.getValueOrNull(Action.class, splitArgs.get(0));
    if (action == null) {
        throw new IllegalCmdArgumentException(String.format("`%s` is not a valid action. %s", splitArgs.get(0), FormatUtils.formatOptions(Action.class)));
    }
    List<String> commands = StringUtils.split(splitArgs.get(1).toLowerCase());
    List<String> unknownCmds = commands.stream().filter(cmd -> CommandManager.getCommand(cmd) == null).collect(Collectors.toList());
    if (!unknownCmds.isEmpty()) {
        throw new IllegalCmdArgumentException(String.format("Command %s doesn't exist.", FormatUtils.format(unknownCmds, cmd -> String.format("`%s`", cmd), ", ")));
    }
    DBGuild dbGuild = Database.getDBGuild(context.getGuild());
    List<String> blacklist = dbGuild.getBlacklistedCmd();
    if (Action.ADD.equals(action)) {
        blacklist.addAll(commands);
        BotUtils.sendMessage(String.format(Emoji.CHECK_MARK + " Command(s) `%s` added to the blacklist.", FormatUtils.format(commands, cmd -> String.format("`%s`", cmd), ", ")), context.getChannel());
    } else if (Action.REMOVE.equals(action)) {
        blacklist.removeAll(commands);
        BotUtils.sendMessage(String.format(Emoji.CHECK_MARK + " Command(s) `%s` removed from the blacklist.", FormatUtils.format(commands, cmd -> String.format("`%s`", cmd), ", ")), context.getChannel());
    }
    dbGuild.setSetting(this.getSetting(), new JSONArray(blacklist));
}
Also used : IllegalCmdArgumentException(me.shadorc.shadbot.exception.IllegalCmdArgumentException) SettingEnum(me.shadorc.shadbot.command.admin.setting.core.SettingEnum) DBGuild(me.shadorc.shadbot.data.db.DBGuild) AbstractSetting(me.shadorc.shadbot.command.admin.setting.core.AbstractSetting) CommandManager(me.shadorc.shadbot.core.command.CommandManager) FormatUtils(me.shadorc.shadbot.utils.FormatUtils) Collectors(java.util.stream.Collectors) BotUtils(me.shadorc.shadbot.utils.BotUtils) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) IllegalCmdArgumentException(me.shadorc.shadbot.exception.IllegalCmdArgumentException) StringUtils(me.shadorc.shadbot.utils.StringUtils) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) List(java.util.List) Context(me.shadorc.shadbot.core.command.Context) Database(me.shadorc.shadbot.data.db.Database) Setting(me.shadorc.shadbot.command.admin.setting.core.Setting) Emoji(me.shadorc.shadbot.utils.object.Emoji) EmbedUtils(me.shadorc.shadbot.utils.embed.EmbedUtils) JSONArray(org.json.JSONArray) Utils(me.shadorc.shadbot.utils.Utils) DBGuild(me.shadorc.shadbot.data.db.DBGuild) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) JSONArray(org.json.JSONArray)

Example 5 with Context

use of me.shadorc.shadbot.core.command.Context in project Shadbot by Shadorc.

the class MessageListener method onMessageReceivedEvent.

private void onMessageReceivedEvent(MessageReceivedEvent event) {
    VariousStatsManager.log(VariousEnum.MESSAGES_RECEIVED);
    IMessage message = event.getMessage();
    try {
        if (message.getAuthor().isBot()) {
            return;
        }
        if (message.getChannel().isPrivate()) {
            this.privateMessageReceived(message);
            return;
        }
        ShardManager.getShadbotShard(message.getShard()).messageReceived();
        if (!BotUtils.isChannelAllowed(message.getGuild(), message.getChannel())) {
            return;
        }
        if (MessageManager.intercept(message)) {
            return;
        }
        String prefix = Database.getDBGuild(message.getGuild()).getPrefix();
        if (message.getContent().startsWith(prefix)) {
            CommandManager.execute(new Context(prefix, message));
        }
    } catch (MissingPermissionsException err) {
        BotUtils.sendMessage(TextUtils.missingPerm(err.getMissingPermissions()), message.getChannel());
        LogUtils.infof("{Guild ID: %d} %s", message.getGuild().getLongID(), err.getMessage());
    } catch (Exception err) {
        BotUtils.sendMessage(Emoji.RED_FLAG + " Sorry, an unknown error occurred. My developer has been warned.", message.getChannel());
        LogUtils.error(message.getContent(), err, String.format("{Guild ID: %d} An unknown error occurred while receiving a message.", message.getGuild().getLongID()));
    }
}
Also used : Context(me.shadorc.shadbot.core.command.Context) IMessage(sx.blah.discord.handle.obj.IMessage) MissingPermissionsException(sx.blah.discord.util.MissingPermissionsException) MissingPermissionsException(sx.blah.discord.util.MissingPermissionsException) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) IllegalCmdArgumentException(me.shadorc.shadbot.exception.IllegalCmdArgumentException)

Aggregations

Context (me.shadorc.shadbot.core.command.Context)12 MissingArgumentException (me.shadorc.shadbot.exception.MissingArgumentException)11 List (java.util.List)9 AbstractCommand (me.shadorc.shadbot.core.command.AbstractCommand)9 CommandCategory (me.shadorc.shadbot.core.command.CommandCategory)9 Command (me.shadorc.shadbot.core.command.annotation.Command)9 IllegalCmdArgumentException (me.shadorc.shadbot.exception.IllegalCmdArgumentException)9 FormatUtils (me.shadorc.shadbot.utils.FormatUtils)9 StringUtils (me.shadorc.shadbot.utils.StringUtils)9 HelpBuilder (me.shadorc.shadbot.utils.embed.HelpBuilder)9 EmbedObject (sx.blah.discord.api.internal.json.objects.EmbedObject)9 BotUtils (me.shadorc.shadbot.utils.BotUtils)8 EmbedUtils (me.shadorc.shadbot.utils.embed.EmbedUtils)8 EmbedBuilder (sx.blah.discord.util.EmbedBuilder)8 Utils (me.shadorc.shadbot.utils.Utils)7 Emoji (me.shadorc.shadbot.utils.object.Emoji)7 RateLimited (me.shadorc.shadbot.core.command.annotation.RateLimited)6 Collectors (java.util.stream.Collectors)5 TextUtils (me.shadorc.shadbot.utils.TextUtils)5 LoadingMessage (me.shadorc.shadbot.utils.object.LoadingMessage)5