Search in sources :

Example 16 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class ChopCommand method onCommand.

public void onCommand(Sx4CommandEvent event) {
    EmbedBuilder embed = new EmbedBuilder();
    event.getMongo().withTransaction(session -> {
        Bson filter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.type", ItemType.AXE.getId()));
        Document data = event.getMongo().getItems().find(session, filter).first();
        if (data == null) {
            event.replyFailure("You do not have a axe").queue();
            session.abortTransaction();
            return;
        }
        CooldownItemStack<Axe> axeStack = new CooldownItemStack<>(event.getBot().getEconomyManager(), data);
        long usableAmount = axeStack.getUsableAmount();
        if (usableAmount == 0) {
            event.reply("Slow down! You can chop some trees down again in " + TimeUtility.LONG_TIME_FORMATTER.parse(axeStack.getTimeRemaining()) + " :stopwatch:").queue();
            session.abortTransaction();
            return;
        }
        Axe axe = axeStack.getItem();
        List<ItemStack<Wood>> materialStacks = axe.getWoodYield();
        String materials = materialStacks.stream().map(ItemStack::toString).collect(Collectors.joining(", "));
        embed.setAuthor(event.getAuthor().getName(), null, event.getAuthor().getEffectiveAvatarUrl()).setColor(event.getMember().getColorRaw()).setDescription(String.format("You chopped down some trees :axe:\nWood found: %s", materialStacks.isEmpty() ? "Nothing" : materials));
        if (axe.getDurability() == 2) {
            embed.appendDescription("\n\nYour axe will break the next time you use it :warning:");
        } else if (axe.getDurability() == 1) {
            embed.appendDescription("\n\nYour axe broke in the process");
        }
        Bson itemFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", axe.getId()));
        if (axe.getDurability() == 1) {
            event.getMongo().getItems().deleteOne(session, itemFilter);
        } else {
            List<Bson> update = List.of(EconomyUtility.getResetsUpdate(usableAmount, ChopCommand.COOLDOWN), Operators.set("item.durability", Operators.subtract("$item.durability", 1)));
            event.getMongo().getItems().updateOne(session, itemFilter, update);
        }
        for (ItemStack<?> stack : materialStacks) {
            Item item = stack.getItem();
            List<Bson> update = List.of(Operators.set("item", item.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), stack.getAmount())));
            Bson materialFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", item.getId()));
            event.getMongo().getItems().updateOne(session, materialFilter, update, new UpdateOptions().upsert(true));
        }
    }).whenComplete((updated, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (updated) {
            event.reply(embed.build()).queue();
        }
    });
}
Also used : Document(org.bson.Document) Operators(com.sx4.bot.database.mongo.model.Operators) EconomyUtility(com.sx4.bot.utility.EconomyUtility) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) com.sx4.bot.entities.economy.item(com.sx4.bot.entities.economy.item) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) UpdateOptions(com.mongodb.client.model.UpdateOptions) Document(org.bson.Document) UpdateOptions(com.mongodb.client.model.UpdateOptions) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) List(java.util.List)

Example 17 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class CrateCommand method buy.

@Command(value = "buy", description = "Buy a crate from the `crate shop`")
@CommandId(412)
@Examples({ "crate buy 2 Shoe Crate", "crate buy Shoe Crate", "crate buy 5 Shoe" })
public void buy(Sx4CommandEvent event, @Argument(value = "crates", endless = true) ItemStack<Crate> stack) {
    long amount = stack.getAmount();
    if (amount < 1) {
        event.replyFailure("You need to buy at least 1 crate").queue();
        return;
    }
    long price = stack.getTotalPrice();
    Crate crate = stack.getItem();
    event.getMongo().withTransaction(session -> {
        UpdateResult result = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), List.of(EconomyUtility.decreaseBalanceUpdate(price)));
        if (result.getModifiedCount() == 0) {
            event.replyFormat("You do not have **$%,d** %s", price, event.getConfig().getFailureEmote()).queue();
            session.abortTransaction();
            return;
        }
        Bson filter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", crate.getId()));
        List<Bson> update = List.of(Operators.set("item", crate.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), amount)));
        event.getMongo().getItems().updateOne(session, filter, update, new UpdateOptions().upsert(true));
    }).whenComplete((updated, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception) || !updated) {
            return;
        }
        event.replyFormat("You just bought `%,d %s` for **$%,d** %s", amount, crate.getName(), price, event.getConfig().getSuccessEmote()).queue();
    });
}
Also used : Document(org.bson.Document) EconomyUtility(com.sx4.bot.utility.EconomyUtility) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) PagedResult(com.sx4.bot.paged.PagedResult) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) ItemStack(com.sx4.bot.entities.economy.item.ItemStack) UpdateResult(com.mongodb.client.result.UpdateResult) Item(com.sx4.bot.entities.economy.item.Item) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) UpdateOptions(com.mongodb.client.model.UpdateOptions) Argument(com.jockie.bot.core.argument.Argument) Operators(com.sx4.bot.database.mongo.model.Operators) Sx4Command(com.sx4.bot.core.Sx4Command) Predicate(java.util.function.Predicate) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Examples(com.sx4.bot.annotations.command.Examples) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) StringJoiner(java.util.StringJoiner) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) Crate(com.sx4.bot.entities.economy.item.Crate) Comparator(java.util.Comparator) Collections(java.util.Collections) Crate(com.sx4.bot.entities.economy.item.Crate) List(java.util.List) UpdateResult(com.mongodb.client.result.UpdateResult) UpdateOptions(com.mongodb.client.model.UpdateOptions) Bson(org.bson.conversions.Bson) 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)

Example 18 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class RPSCommand method stats.

@Command(value = "stats", description = "View some stats about your personal rps record")
@CommandId(296)
@Examples({ "rps stats", "rps stats @Shea#6653" })
public void stats(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
    User user = member == null ? event.getAuthor() : member.getUser();
    Bson filter = Filters.and(Filters.eq("userId", user.getIdLong()), Filters.eq("type", GameType.ROCK_PAPER_SCISSORS.getId()));
    List<Document> games = event.getMongo().getGames(filter, Projections.include("state")).into(new ArrayList<>());
    if (games.isEmpty()) {
        event.replyFailure("That user has not played rock paper scissors yet").queue();
        return;
    }
    int wins = 0, draws = 0, losses = 0, total = 0;
    for (Document game : games) {
        GameState state = GameState.fromId(game.getInteger("state"));
        if (state == GameState.WIN) {
            wins++;
        } else if (state == GameState.DRAW) {
            draws++;
        } else if (state == GameState.LOSS) {
            losses++;
        }
        total++;
    }
    EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()).setDescription(String.format("Wins: %,d\nDraws: %,d\nLosses: %,d\n\nWin Percentage: %s%%", wins, draws, losses, NumberUtility.DEFAULT_DECIMAL_FORMAT.format(((double) wins / total) * 100)));
    event.reply(embed.build()).queue();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) User(net.dv8tion.jda.api.entities.User) GameState(com.sx4.bot.entities.games.GameState) Document(org.bson.Document) Bson(org.bson.conversions.Bson) 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)

Example 19 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class SteamEndpoint method getSteam.

@GET
@Path("steam")
@Produces(MediaType.TEXT_HTML)
public void getSteam(@Context UriInfo info, @QueryParam("openid.identity") final String identity, @QueryParam("user_id") final long userId, @QueryParam("timestamp") long timestamp, @QueryParam("signature") String signature, @Suspended final AsyncResponse response) {
    Document failureCopy = this.failure.clone();
    long timestampNow = Instant.now().getEpochSecond();
    if (timestampNow - timestamp >= 300) {
        response.resume(Response.status(401).entity(this.setText(failureCopy, "Authorization link timed out")).build());
        return;
    }
    String hash;
    try {
        hash = HmacUtility.getSignatureHex(this.bot.getConfig().getSteam(), Long.toString(userId) + timestamp, HmacUtility.HMAC_MD5);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        response.resume(Response.status(500).entity(this.setText(failureCopy, "Something went wrong while authenticating your account")).build());
        return;
    }
    if (!hash.equals(signature)) {
        response.resume(Response.status(401).entity(this.setText(failureCopy, "Unauthorized")).build());
    }
    StringBuilder url = new StringBuilder("https://steamcommunity.com/openid/login");
    MultivaluedMap<String, String> parameters = info.getQueryParameters();
    boolean first = true;
    for (String key : parameters.keySet()) {
        if (first) {
            url.append("?");
            first = false;
        } else {
            url.append("&");
        }
        url.append(key).append("=").append(URLEncoder.encode(key.equals("openid.mode") ? "check_authentication" : parameters.get(key).get(0), StandardCharsets.UTF_8));
    }
    Request request = new Request.Builder().url(url.toString()).build();
    this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) steamResponse -> {
        String body = steamResponse.body().string();
        String[] lines = body.split("\n");
        for (String line : lines) {
            String[] keyValue = line.split(":");
            if (keyValue[0].equals("is_valid") && !keyValue[1].equals("true")) {
                response.resume(Response.status(401).entity(this.setText(failureCopy, "Unauthorized")).build());
                return;
            }
        }
        long steamId = Long.parseLong(identity.substring(identity.lastIndexOf('/') + 1));
        Request steamRequest = new Request.Builder().url("https://steamcommunity.com/profiles/" + steamId + "?xml=1").build();
        this.bot.getHttpClient().newCall(steamRequest).enqueue((HttpCallback) profileResponse -> {
            JSONObject data = XML.toJSONObject(profileResponse.body().string());
            JSONObject profile = data.getJSONObject("profile");
            org.bson.Document connection = new org.bson.Document("id", steamId).append("name", profile.getString("steamID"));
            List<Bson> update = List.of(Operators.set("connections.steam", Operators.concatArrays(List.of(connection), Operators.filter(Operators.ifNull("$connections.steam", Collections.EMPTY_LIST), Operators.ne("$$this.id", steamId)))));
            this.bot.getMongo().updateUserById(userId, update).whenComplete((result, exception) -> {
                if (ExceptionUtility.sendErrorMessage(exception)) {
                    response.resume(Response.status(500).entity(this.setText(failureCopy, "Something went wrong while authenticating your account")).build());
                    return;
                }
                Document successCopy = this.success.clone();
                response.resume(Response.ok(this.setText(successCopy, "Connected your steam account to Sx4")).build());
            });
        });
    });
}
Also used : Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Path(javax.ws.rs.Path) Bson(org.bson.conversions.Bson) JSONObject(org.json.JSONObject) QueryParam(javax.ws.rs.QueryParam) Sx4(com.sx4.bot.core.Sx4) XML(org.json.XML) Operators(com.sx4.bot.database.mongo.model.Operators) Request(okhttp3.Request) HmacUtility(com.sx4.bot.utility.HmacUtility) HttpCallback(com.sx4.bot.http.HttpCallback) AsyncResponse(javax.ws.rs.container.AsyncResponse) IOException(java.io.IOException) javax.ws.rs.core(javax.ws.rs.core) Instant(java.time.Instant) Suspended(javax.ws.rs.container.Suspended) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) URLEncoder(java.net.URLEncoder) List(java.util.List) Document(org.jsoup.nodes.Document) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) InvalidKeyException(java.security.InvalidKeyException) Jsoup(org.jsoup.Jsoup) Collections(java.util.Collections) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Document(org.jsoup.nodes.Document) InvalidKeyException(java.security.InvalidKeyException) Bson(org.bson.conversions.Bson) JSONObject(org.json.JSONObject) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 20 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class CommandStatsCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Option(value = "group", description = "What to group the data by, default is command") GroupType group, @Option(value = "command", description = "Provide a command filter") Sx4Command command, @Option(value = "server", aliases = { "guild" }, description = "Provide a server filter") Guild guild, @Option(value = "channel", description = "Provide a channel filter") TextChannel channel, @Option(value = "user", description = "Provide a user id argument") long userId, @Option(value = "from", description = "When the data should start in epoch seconds") long from, @Option(value = "to", description = "When the data should end in epoch seconds") long to) {
    List<Bson> filters = new ArrayList<>();
    if (command != null) {
        filters.add(Filters.eq("command.id", command.getId()));
    }
    if (group == GroupType.CHANNEL) {
        filters.add(Filters.eq("guildId", event.getGuild().getIdLong()));
    } else if (guild != null) {
        filters.add(Filters.eq("guildId", guild.getIdLong()));
    }
    if (userId != 0L) {
        filters.add(Filters.eq("authorId", userId));
    }
    if (channel != null) {
        filters.add(Filters.eq("channelId", channel.getIdLong()));
    }
    if (from != 0L) {
        filters.add(Filters.gte("_id", new ObjectId(Date.from(Instant.ofEpochSecond(from)))));
    }
    if (to != 0L) {
        filters.add(Filters.lte("_id", new ObjectId(Date.from(Instant.ofEpochSecond(to)))));
    }
    List<Bson> pipeline = List.of(Aggregates.match(filters.isEmpty() ? Filters.empty() : Filters.and(filters)), Aggregates.group("$" + (group == null ? GroupType.COMMAND : group).getField(), Accumulators.sum("count", 1L)), Aggregates.sort(Sorts.descending("count")));
    event.getMongo().aggregateCommands(pipeline).whenComplete((commands, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (commands.isEmpty()) {
            event.replyFailure("No data was found with those filters").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), commands).setIndexed(false).setSelect().setAuthor("Command Stats", null, event.getSelfUser().getEffectiveAvatarUrl()).setDisplayFunction(data -> {
            String prefix = null;
            if (group == null || group == GroupType.COMMAND) {
                prefix = "`" + data.getString("_id") + "`";
            } else if (group == GroupType.CHANNEL) {
                long id = data.getLong("_id");
                GuildMessageChannel messageChannel = event.getGuild().getChannelById(GuildMessageChannel.class, id);
                prefix = messageChannel == null ? "#deleted-channel (" + id + ")" : messageChannel.getAsMention();
            } else if (group == GroupType.USER) {
                long id = data.getLong("_id");
                User user = event.getShardManager().getUserById(id);
                prefix = "`" + (user == null ? "Anonymous#0000 (" + id + ")" : MarkdownSanitizer.escape(user.getAsTag())) + "`";
            } else if (group == GroupType.SERVER) {
                Long id = data.getLong("_id");
                if (id == null) {
                    prefix = "`Private Messages`";
                } else {
                    Guild guildGroup = event.getShardManager().getGuildById(id);
                    prefix = "`" + (guildGroup == null ? "Unknown Server (" + id + ")" : MarkdownSanitizer.escape(guildGroup.getName())) + "`";
                }
            }
            long count = data.getLong("count");
            return (prefix == null ? "Unknown" : prefix) + " - " + String.format("%,d", count) + " use" + (count == 1 ? "" : "s");
        });
        paged.execute(event);
    });
}
Also used : User(net.dv8tion.jda.api.entities.User) ObjectId(org.bson.types.ObjectId) ArrayList(java.util.ArrayList) Document(org.bson.Document) Guild(net.dv8tion.jda.api.entities.Guild) Bson(org.bson.conversions.Bson) GuildMessageChannel(net.dv8tion.jda.api.entities.GuildMessageChannel) PagedResult(com.sx4.bot.paged.PagedResult)

Aggregations

Document (org.bson.Document)46 Bson (org.bson.conversions.Bson)44 Sx4Command (com.sx4.bot.core.Sx4Command)36 Command (com.jockie.bot.core.command.Command)28 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)26 User (net.dv8tion.jda.api.entities.User)26 CommandId (com.sx4.bot.annotations.command.CommandId)25 Examples (com.sx4.bot.annotations.command.Examples)23 Operators (com.sx4.bot.database.mongo.model.Operators)23 List (java.util.List)21 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)20 Permission (net.dv8tion.jda.api.Permission)20 Member (net.dv8tion.jda.api.entities.Member)20 ModuleCategory (com.sx4.bot.category.ModuleCategory)18 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)18 PagedResult (com.sx4.bot.paged.PagedResult)14 Argument (com.jockie.bot.core.argument.Argument)13 com.mongodb.client.model (com.mongodb.client.model)13 ArrayList (java.util.ArrayList)13 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)12