Search in sources :

Example 81 with Sx4CommandEvent

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

the class ConvertCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "amount") @DefaultNumber(1) double amount, @Argument(value = "currency from") @Uppercase String from, @Argument(value = "currency to") @Uppercase String to) {
    if (to.equals(from)) {
        event.replyFormat("**%,.2f** %s \\➡ **%,.2f** %s", amount, from, amount, to).queue();
        return;
    }
    Request request = new Request.Builder().url(String.format("https://free.currconv.com/api/v7/convert?q=%s_%s&apiKey=%s&compact=y", from, to, event.getConfig().getCurrencyConvertor())).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        if (!response.isSuccessful()) {
            event.replyFailure("Failed to convert, try again if this repeats it's likely due to the API being down").queue();
            return;
        }
        Document json = Document.parse(response.body().string());
        Document result = json.get(from + "_" + to, Document.class);
        if (result == null) {
            event.replyFailure("I could not find one or both of those currencies").queue();
            return;
        }
        event.replyFormat("**%,.2f** %s \\➡ **%,.2f** %s", amount, from, amount * result.getDouble("val"), to).queue();
    });
}
Also used : Document(org.bson.Document) ModuleCategory(com.sx4.bot.category.ModuleCategory) Request(okhttp3.Request) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) Uppercase(com.sx4.bot.annotations.argument.Uppercase) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Argument(com.jockie.bot.core.argument.Argument) Request(okhttp3.Request) Document(org.bson.Document)

Example 82 with Sx4CommandEvent

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

the class DictionaryCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
    Request request = new Request.Builder().url(event.getConfig().getSearchWebserverUrl("dictionary") + "?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8)).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        Document document = Document.parse(response.body().string());
        if (!response.isSuccessful()) {
            StringBuilder builder = new StringBuilder("Command failed with status " + response.code());
            if (document.containsKey("message")) {
                builder.append(" with message `").append(document.getString("message")).append("`");
            }
            event.replyFailure(builder.toString()).queue();
            return;
        }
        List<Document> definitions = document.getList("definitions", Document.class);
        if (definitions.isEmpty()) {
            event.replyFailure("I could not find a definition for that word").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), definitions).setPerPage(1).setCustomFunction(page -> {
            EmbedBuilder embed = new EmbedBuilder();
            embed.setAuthor(StringUtility.title(query) + " (" + document.getString("type") + ")", document.getString("url"), null);
            embed.setTitle("Page " + page.getPage() + "/" + page.getMaxPage());
            embed.setFooter(PagedResult.DEFAULT_FOOTER_TEXT);
            page.forEach((data, index) -> {
                StringBuilder definition = new StringBuilder();
                for (Document node : data.getList("nodes", Document.class)) {
                    if (node.containsKey("url")) {
                        definition.append("[").append(node.getString("text")).append("](").append(node.getString("url")).append(")");
                    } else {
                        definition.append(node.getString("text"));
                    }
                }
                List<String> examples = data.getList("examples", String.class);
                embed.addField("Definition", definition + (examples.isEmpty() ? "" : "\n\n*" + String.join("*\n*", examples.subList(0, Math.min(3, examples.size()))) + "*"), false);
            });
            if (document.containsKey("pronunciation")) {
                embed.addField("Pronunciation", String.format("[Listen Here](%s)", document.getString("pronunciation")), false);
            }
            return new MessageBuilder().setEmbeds(embed.build());
        });
        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) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) List(java.util.List) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) StringUtility(com.sx4.bot.utility.StringUtility) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Request(okhttp3.Request) List(java.util.List) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult)

Example 83 with Sx4CommandEvent

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

the class FreeGamesCommand method preview.

@Command(value = "preview", description = "Preview your free game notification message")
@CommandId(481)
@Examples({ "free games preview" })
public void preview(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = 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;
    Document data = event.getMongo().getFreeGameChannel(Filters.eq("channelId", effectiveChannel.getIdLong()), Projections.include("message"));
    if (data == null) {
        event.replyFailure("You don't have a free game channel setup").queue();
        return;
    }
    FreeGameUtility.retrieveFreeGames(event.getHttpClient(), freeGames -> {
        Formatter<Document> formatter = new JsonFormatter(data.get("message", FreeGameManager.DEFAULT_MESSAGE)).addVariable("game", freeGames.get(0));
        MessageUtility.fromWebhookMessage(event.getChannel(), MessageUtility.fromJson(formatter.parse()).build()).queue();
    });
}
Also used : JsonFormatter(com.sx4.bot.formatter.JsonFormatter) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 84 with Sx4CommandEvent

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

the class FreeGamesCommand method remove.

@Command(value = "remove", description = "Remove a channel from getting free game notifications from Epic Games")
@CommandId(475)
@Examples({ "free games remove", "free games remove #channel" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void remove(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;
    FindOneAndDeleteOptions options = new FindOneAndDeleteOptions().projection(Projections.include("webhook"));
    event.getMongo().findAndDeleteFreeGameChannel(Filters.eq("channelId", effectiveChannel.getIdLong()), options).whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        event.getBot().getFreeGameManager().removeWebhook(effectiveChannel.getIdLong());
        Document webhook = data.get("webhook", Document.class);
        if (webhook != null) {
            effectiveChannel.deleteWebhookById(Long.toString(webhook.getLong("id"))).queue(null, ErrorResponseException.ignore(ErrorResponse.UNKNOWN_WEBHOOK));
        }
        event.replySuccess("Free game notifications will no longer be sent in " + effectiveChannel.getAsMention()).queue();
    });
}
Also used : MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 85 with Sx4CommandEvent

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

the class FreeGamesCommand method platforms.

@Command(value = "platforms", description = "Select what platforms you want notifications from")
@CommandId(491)
@Examples({ "free games platforms #channel STEAM", "free games platforms STEAM EPIC_GAMES" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void platforms(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) BaseGuildMessageChannel channel, @Argument(value = "platforms") FreeGameType... types) {
    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;
    long raw = FreeGameType.getRaw(types);
    event.getMongo().updateFreeGameChannel(Filters.eq("channelId", effectiveChannel.getIdLong()), Updates.set("platforms", raw), new UpdateOptions()).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (result.getMatchedCount() == 0) {
            event.replyFailure("You do not have a free game channel in " + effectiveChannel.getAsMention()).queue();
            return;
        }
        if (result.getModifiedCount() == 0) {
            event.replyFailure("That free game channel already uses those platforms").queue();
            return;
        }
        event.replySuccess("That free game channel will now send notifications from those platforms").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)

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