Search in sources :

Example 86 with Sx4CommandEvent

use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.

the class FreeGamesCommand method toggle.

@Command(value = "toggle", description = "Enables/disables a free game channel")
@CommandId(484)
@Examples({ "free games toggle", "free games toggle #channel" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void toggle(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true, endless = true) BaseGuildMessageChannel channel) {
    MessageChannel messageChannel = event.getChannel();
    if (channel == null && !(messageChannel instanceof BaseGuildMessageChannel)) {
        event.replyFailure("You cannot use this channel type").queue();
        return;
    }
    BaseGuildMessageChannel effectiveChannel = channel == null ? (BaseGuildMessageChannel) messageChannel : channel;
    List<Bson> update = List.of(Operators.set("enabled", Operators.cond(Operators.exists("$enabled"), Operators.REMOVE, false)));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().projection(Projections.include("enabled")).returnDocument(ReturnDocument.AFTER);
    event.getMongo().findAndUpdateFreeGameChannel(Filters.eq("channelId", effectiveChannel.getIdLong()), update, options).whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        event.replySuccess("The free game channel in " + effectiveChannel.getAsMention() + " is now **" + (data.get("enabled", true) ? "enabled" : "disabled") + "**").queue();
    });
}
Also used : MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 87 with Sx4CommandEvent

use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.

the class FreeGamesCommand method avatar.

@Command(value = "avatar", description = "Set the avatar of the webhook that sends free game notifications")
@CommandId(480)
@Examples({ "free games avatar Shea#6653", "free games avatar https://i.imgur.com/i87lyNO.png" })
@Premium
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void avatar(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) BaseGuildMessageChannel channel, @Argument(value = "avatar", endless = true, acceptEmpty = true) @ImageUrl String url) {
    MessageChannel messageChannel = event.getChannel();
    if (channel == null && !(messageChannel instanceof BaseGuildMessageChannel)) {
        event.replyFailure("You cannot use this channel type").queue();
        return;
    }
    BaseGuildMessageChannel effectiveChannel = channel == null ? (BaseGuildMessageChannel) messageChannel : channel;
    event.getMongo().updateFreeGameChannel(Filters.eq("channelId", effectiveChannel.getIdLong()), Updates.set("webhook.avatar", url), new UpdateOptions()).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (result.getMatchedCount() == 0) {
            event.replyFailure("You don't have a free game channel setup").queue();
            return;
        }
        if (result.getModifiedCount() == 0) {
            event.replyFailure("Your webhook avatar for free game notifications was already set to that").queue();
            return;
        }
        event.replySuccess("Your webhook avatar has been updated for that free game notifications, this only works with premium <https://patreon.com/Sx4>").queue();
    });
}
Also used : MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 88 with Sx4CommandEvent

use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.

the class GoogleCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
    MessageChannel channel = event.getChannel();
    boolean nsfw = channel instanceof BaseGuildMessageChannel && ((BaseGuildMessageChannel) channel).isNSFW();
    event.getBot().getGoogleCache().retrieveResultsByQuery(query, nsfw).whenComplete((results, exception) -> {
        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
        if (cause instanceof ForbiddenException) {
            event.replyFailure(cause.getMessage()).queue();
            return;
        }
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        String googleUrl = "https://www.google.co.uk/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + (nsfw ? "" : "&safe=active");
        PagedResult<GoogleSearchResult> paged = new PagedResult<>(event.getBot(), results).setIndexed(false).setPerPage(3).setAuthor("Google", googleUrl, "http://i.imgur.com/G46fm8J.png").setDisplayFunction(result -> {
            String title = result.getTitle(), link = result.getLink(), snippet = result.getSnippet();
            return "**[" + StringUtility.limit(title, 32) + "](" + link + ")**\n" + StringUtility.limit(snippet, 246, " ...") + "\n";
        });
        paged.execute(event);
    });
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) CompletionException(java.util.concurrent.CompletionException) GoogleSearchResult(com.sx4.bot.cache.GoogleSearchCache.GoogleSearchResult) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) PagedResult(com.sx4.bot.paged.PagedResult)

Example 89 with Sx4CommandEvent

use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.

the class IGDBCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "game", endless = true, nullDefault = true) String game, @Option(value = "sort", description = "Sort results by `name` (default), `rating` and `release`") IGDBSort sort, @Option(value = "reverse", description = "Reverses sorting order") boolean reverse) {
    IGDBParser parser = new IGDBParser().setFilter("category = 0").limit(500).addFields("name", "total_rating", "total_rating_count", "first_release_date", "genres.name", "url", "summary", "cover.image_id", "platforms.name");
    if (game != null && sort == null && !reverse) {
        parser.search(String.format("\"%s\"", game));
    } else {
        parser.sort(sort == null ? "name" : sort.getName(), !reverse).appendFilter(filter -> IGDBFilter.and(filter, (sort == null ? "name" : sort.getName()) + " != n"));
        if (game != null) {
            parser.appendFilter(filter -> IGDBFilter.and(filter, String.format("name ~ \"%s\"*", game)));
        }
    }
    Request request = new Request.Builder().url("https://api.igdb.com/v4/games/").post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), parser.parse())).addHeader("Client-ID", event.getConfig().getTwitchClientId()).addHeader("Authorization", "Bearer " + event.getBot().getTwitchConfig().getToken()).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        String body = String.format("{\"data\":%s}", response.body().string());
        List<Document> results = Document.parse(body).getList("data", Document.class);
        if (results.isEmpty()) {
            event.replyFailure("I could not find any games with that filter").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), results).setAutoSelect(true).setIncreasedIndex(true).setAuthor("IGDB Search", null, "http://bit.ly/2NXGwMz").setDisplayFunction(data -> data.getString("name"));
        paged.onSelect(select -> {
            Document data = select.getSelected();
            EmbedBuilder embed = new EmbedBuilder();
            embed.setAuthor(data.getString("name"), data.getString("url"), "http://bit.ly/2NXGwMz");
            embed.setDescription(StringUtility.limit(data.get("summary", "This game has no description :("), MessageEmbed.DESCRIPTION_MAX_LENGTH, "... [Read More](" + data.getString("url") + ")"));
            embed.setThumbnail(data.containsKey("cover") ? String.format("https://images.igdb.com/igdb/image/upload/t_thumb/%s.jpg", data.getEmbedded(List.of("cover", "image_id"), String.class)) : null);
            int ratings = data.get("total_rating_count", 0);
            embed.addField("Rating", data.containsKey("total_rating") ? String.format("%.2f out of %,d rating%s", data.getDouble("total_rating"), ratings, ratings == 1 ? "" : "s") : "Unknown", true);
            embed.addField("Release Date", data.containsKey("first_release_date") ? Instant.ofEpochSecond(data.getInteger("first_release_date")).atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("dd LLLL yyyy")) : "Unknown", true);
            embed.addField("Genres", data.containsKey("genres") ? data.getList("genres", Document.class).stream().map(genre -> genre.getString("name")).collect(Collectors.joining("\n")) : "None", true);
            embed.addField("Platforms", data.containsKey("platforms") ? data.getList("platforms", Document.class).stream().map(platform -> platform.getString("name")).collect(Collectors.joining("\n")) : "None", true);
            event.reply(embed.build()).queue();
        });
        paged.execute(event);
    });
}
Also used : Document(org.bson.Document) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) IGDBFilter(com.sx4.bot.entities.info.IGDBFilter) IGDBSort(com.sx4.bot.entities.info.IGDBSort) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) PagedResult(com.sx4.bot.paged.PagedResult) Collectors(java.util.stream.Collectors) RequestBody(okhttp3.RequestBody) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) IGDBParser(com.sx4.bot.entities.info.IGDBParser) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) DateTimeFormatter(java.time.format.DateTimeFormatter) Option(com.jockie.bot.core.option.Option) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) ZoneOffset(java.time.ZoneOffset) StringUtility(com.sx4.bot.utility.StringUtility) MediaType(okhttp3.MediaType) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) List(java.util.List) IGDBParser(com.sx4.bot.entities.info.IGDBParser) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult)

Example 90 with Sx4CommandEvent

use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.

the class MuteCommand method defaultTime.

@Command(value = "default time", aliases = { "default duration" }, description = "Sets the default time to be used when a duration argument isn't given")
@CommandId(342)
@Examples({ "mute default time 10m", "mute default time 5d", "mute default time 1h 30m" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void defaultTime(Sx4CommandEvent event, @Argument(value = "duration", endless = true) Duration duration) {
    long seconds = duration.toSeconds();
    Bson update = seconds == ModUtility.DEFAULT_MUTE_DURATION ? Updates.unset("mute.defaultTime") : Updates.set("mute.defaultTime", seconds);
    event.getMongo().updateGuildById(event.getGuild().getIdLong(), update).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (result.getModifiedCount() == 0 && result.getUpsertedId() == null) {
            event.replyFailure("Your mute default time was already set to that").queue();
            return;
        }
        event.replySuccess("Your mute default time has been set to **" + TimeUtility.LONG_TIME_FORMATTER.parse(seconds) + "**").queue();
    });
}
Also used : Bson(org.bson.conversions.Bson) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)255 Command (com.jockie.bot.core.command.Command)181 Document (org.bson.Document)153 ModuleCategory (com.sx4.bot.category.ModuleCategory)130 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)130 CommandId (com.sx4.bot.annotations.command.CommandId)121 Argument (com.jockie.bot.core.argument.Argument)119 Examples (com.sx4.bot.annotations.command.Examples)119 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)119 Permission (net.dv8tion.jda.api.Permission)119 Bson (org.bson.conversions.Bson)111 PagedResult (com.sx4.bot.paged.PagedResult)90 HttpCallback (com.sx4.bot.http.HttpCallback)69 Request (okhttp3.Request)68 AuthorPermissions (com.sx4.bot.annotations.command.AuthorPermissions)60 User (net.dv8tion.jda.api.entities.User)57 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)55 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)54 Operators (com.sx4.bot.database.mongo.model.Operators)50 List (java.util.List)50