use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class AxeCommand method upgrade.
@Command(value = "upgrade", description = "Upgrade your axe by a certain attribute")
@CommandId(429)
@Examples({ "axe upgrade multiplier", "axe upgrade durability 5" })
public void upgrade(Sx4CommandEvent event, @Argument(value = "upgrade") Upgrade upgrade, @Argument(value = "upgrades") @DefaultNumber(1) @Limit(min = 1, max = 100) int upgrades) {
if (!upgrade.containsType(ItemType.AXE)) {
event.replyFailure("You can not use that upgrade on a axe").queue();
return;
}
event.getMongo().withTransaction(session -> {
Document data = event.getMongo().getItems().find(session, Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.type", ItemType.AXE.getId()))).first();
if (data == null) {
event.replyFailure("You do not have a axe").queue();
session.abortTransaction();
return null;
}
Document item = data.get("item", Document.class);
Axe defaultAxe = event.getBot().getEconomyManager().getItemById(item.getInteger("id"), Axe.class);
Axe axe = new Axe(item, defaultAxe);
int currentUpgrades = axe.getUpgrades();
long price = 0;
for (int i = 0; i < upgrades; i++) {
price += Math.round(0.015D * defaultAxe.getPrice() * currentUpgrades++ + 0.025D * defaultAxe.getPrice());
}
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 null;
}
List<Bson> update = new ArrayList<>();
update.add(Operators.set("item.upgrades", Operators.add(Operators.ifNull("$item.upgrades", 0), upgrades)));
update.add(Operators.set("item.price", Operators.add("$item.price", Math.round(defaultAxe.getPrice() * 0.015D) * upgrades)));
if (upgrade == Upgrade.DURABILITY) {
int increase = (int) upgrade.getValue() * upgrades;
update.add(Operators.set("item.durability", Operators.add("$item.durability", increase)));
update.add(Operators.set("item.maxDurability", Operators.add("$item.maxDurability", increase)));
} else if (upgrade == Upgrade.MULTIPLIER) {
double increase = defaultAxe.getMultiplier() * upgrade.getValue() * upgrades;
update.add(Operators.set("item.multiplier", Operators.add("$item.multiplier", increase)));
}
event.getMongo().getItems().updateOne(session, Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", axe.getId())), update);
return String.format("You just upgraded %s %d time%s for your `%s` for **$%,d**", upgrade.getName().toLowerCase(), upgrades, (upgrades == 1 ? "" : "s"), axe.getName(), price);
}).whenComplete((message, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception) || message == null) {
return;
}
event.replySuccess(message).queue();
});
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class GiveItemCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "user") Member member, @Argument(value = "item", endless = true) ItemStack<Item> stack) {
User user = member.getUser();
if (user.isBot()) {
event.replyFailure("You can not give items to bots").queue();
return;
}
if (user.getIdLong() == event.getAuthor().getIdLong()) {
event.replyFailure("You can not give items to yourself").queue();
return;
}
long amount = stack.getAmount();
if (amount < 1) {
event.replyFailure("You need to give at least 1 item").queue();
return;
}
Item item = stack.getItem();
if (item instanceof Tool) {
event.replyFailure("You cannot give tools").queue();
return;
}
long price = stack.getTotalPrice();
long tax = (long) Math.ceil(price * 0.05D);
event.getMongo().withTransaction(session -> {
UpdateResult balanceResult = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), List.of(EconomyUtility.decreaseBalanceUpdate(tax)));
if (balanceResult.getModifiedCount() == 0) {
event.replyFormat("You do not have enough to pay the tax for this item (**$%,d**) %s", tax, event.getConfig().getFailureEmote()).queue();
session.abortTransaction();
return null;
}
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("amount", "resets"));
Bson authorFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", item.getId()));
List<Bson> authorUpdate = List.of(Operators.set("amount", Operators.let(new Document("amount", Operators.ifNull("$amount", 0L)), Operators.cond(Operators.lt(Operators.subtract("$$amount", Operators.sum(Operators.map(Operators.filter(Operators.ifNull("$resets", Collections.EMPTY_LIST), Operators.gt("$$this.time", Operators.nowEpochSecond())), "$$this.amount"))), amount), "$$amount", Operators.subtract("$$amount", amount)))));
Document authorData = event.getMongo().getItems().findOneAndUpdate(session, authorFilter, authorUpdate, options);
long authorAmount = authorData == null ? 0L : authorData.get("amount", 0L);
if (authorAmount < amount) {
event.replyFailure("You do not have `" + amount + " " + item.getName() + "`").queue();
session.abortTransaction();
return null;
}
CooldownItemStack<Item> cooldownStack = new CooldownItemStack<>(item, authorData);
long cooldownAmount = cooldownStack.getCooldownAmount();
if (authorAmount - cooldownAmount < amount) {
event.replyFormat("You have `%,d %s` but **%,d** %s on cooldown %s", authorAmount, item.getName(), cooldownAmount, cooldownAmount == 1 ? "is" : "are", event.getConfig().getFailureEmote()).queue();
session.abortTransaction();
return null;
}
Bson userFilter = Filters.and(Filters.eq("userId", member.getIdLong()), Filters.eq("item.id", item.getId()));
List<Bson> userUpdate = List.of(Operators.set("item", item.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), stack.getAmount())));
Document userData = event.getMongo().getItems().findOneAndUpdate(session, userFilter, userUpdate, options.upsert(true));
event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getSelfUser().getIdLong()), Updates.inc("economy.balance", tax));
EmbedBuilder embed = new EmbedBuilder().setColor(event.getMember().getColor()).setAuthor(event.getAuthor().getName() + " → " + member.getUser().getName(), null, "https://cdn0.iconfinder.com/data/icons/social-messaging-ui-color-shapes/128/money-circle-green-3-512.png").setDescription(String.format("You have gifted **%,d %s** to **%s**\n\n%s's new %s amount: **%,d %s**\n%s's new %s amount: **%,d %s**", amount, item.getName(), user.getName(), event.getAuthor().getName(), item.getName(), authorAmount - amount, item.getName(), user.getName(), item.getName(), (userData == null ? 0L : userData.getLong("amount")) + amount, item.getName())).setFooter(String.format("$%,d (%d%%) tax was taken", tax, Math.round((double) tax / price * 100)), null);
return embed.build();
}).whenComplete((embed, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception) || embed == null) {
return;
}
event.reply(embed).queue();
});
}
use of com.jockie.bot.core.argument.Argument 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();
});
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class SuggestionCommand method remove.
@Command(value = "remove", aliases = { "delete" }, description = "Removes a suggestion, can be your own or anyones if you have the manage server permission")
@CommandId(85)
@Examples({ "suggestion remove 5e45ce6d3688b30ee75201ae", "suggestion remove all" })
public void remove(Sx4CommandEvent event, @Argument(value = "id | message | all", acceptEmpty = true) @AlternativeOptions("all") Alternative<Or<MessageArgument, ObjectId>> option) {
User author = event.getAuthor();
if (option.isAlternative()) {
if (!event.hasPermission(event.getMember(), Permission.MANAGE_SERVER)) {
event.replyFailure("You are missing the permission " + Permission.MANAGE_SERVER.getName() + " to execute this, you can remove your own suggestions only").queue();
return;
}
List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
event.reply(author.getName() + ", are you sure you want to delete **all** the suggestions in this server?").setActionRow(buttons).submit().thenCompose(message -> {
return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, event.getAuthor())).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, event.getAuthor())).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
}).whenComplete((e, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof CancelException) {
GenericEvent cancelEvent = ((CancelException) cause).getEvent();
if (cancelEvent != null) {
((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
}
return;
} else if (cause instanceof TimeoutException) {
event.reply("Timed out :stopwatch:").queue();
return;
} else if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.getMongo().deleteManySuggestions(Filters.eq("guildId", event.getGuild().getIdLong())).whenComplete((result, databaseException) -> {
if (ExceptionUtility.sendExceptionally(event, databaseException)) {
return;
}
if (result.getDeletedCount() == 0) {
e.reply("This server has no suggestions " + event.getConfig().getFailureEmote()).queue();
return;
}
e.reply("All suggestions have been deleted in this server " + event.getConfig().getSuccessEmote()).queue();
});
});
} else {
Or<MessageArgument, ObjectId> argument = option.getValue();
boolean hasPermission = event.hasPermission(event.getMember(), Permission.MANAGE_SERVER);
Bson filter = Filters.and(argument.hasFirst() ? Filters.eq("messageId", argument.getFirst().getMessageId()) : Filters.eq("_id", argument.getSecond()), Filters.eq("guildId", event.getGuild().getIdLong()));
if (!hasPermission) {
filter = Filters.and(Filters.eq("authorId", author.getIdLong()), filter);
}
event.getMongo().findAndDeleteSuggestion(filter).whenComplete((data, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (data == null) {
event.replyFailure("I could not find that suggestion").queue();
return;
}
if (data.getLong("authorId") != author.getIdLong() && !hasPermission) {
event.replyFailure("You do not own that suggestion").queue();
return;
}
WebhookClient webhook = event.getBot().getSuggestionManager().getWebhook(data.getLong("channelId"));
if (webhook != null) {
webhook.delete(data.getLong("messageId"));
}
event.replySuccess("That suggestion has been removed").queue();
});
}
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class HelpCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "command | module", endless = true, nullDefault = true) String commandName) {
boolean embed = !event.isFromGuild() || event.getGuild().getSelfMember().hasPermission(event.getTextChannel(), Permission.MESSAGE_EMBED_LINKS);
if (commandName == null) {
List<Sx4Category> categories = Arrays.stream(ModuleCategory.ALL_ARRAY).filter(category -> !category.getCommands(event.isAuthorDeveloper()).isEmpty()).collect(Collectors.toList());
PagedResult<Sx4Category> paged = new PagedResult<>(event.getBot(), categories).setPerPage(categories.size()).setSelect(SelectType.OBJECT).setSelectablePredicate((content, category) -> category.getName().equalsIgnoreCase(content) || Arrays.stream(category.getAliases()).anyMatch(content::equalsIgnoreCase)).setCustomFunction(page -> {
MessageBuilder builder = new MessageBuilder();
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setAuthor("Help", null, event.getSelfUser().getEffectiveAvatarUrl());
embedBuilder.setFooter(event.getPrefix() + "help <module> or respond below with a name of a module", event.getAuthor().getEffectiveAvatarUrl());
embedBuilder.setDescription("All commands are put in a set category also known as a module, use `" + event.getPrefix() + "help <module>` on the module of your choice, The bot will then " + "list all the commands in that module. If you need further help feel free to join the [support server](https://discord.gg/PqJNcfB).");
embedBuilder.addField("Modules", "`" + categories.stream().map(Sx4Category::getName).collect(Collectors.joining("`, `")) + "`", false);
return builder.setEmbeds(embedBuilder.build());
});
paged.onSelect(select -> {
Sx4Category category = select.getSelected();
List<Sx4Command> categoryCommands = category.getCommands(event.isAuthorDeveloper()).stream().map(Sx4Command.class::cast).sorted(Comparator.comparing(Sx4Command::getCommandTrigger)).collect(Collectors.toList());
PagedResult<Sx4Command> categoryPaged = HelpUtility.getCommandsPaged(event.getBot(), categoryCommands).setAuthor(category.getName(), null, event.getAuthor().getEffectiveAvatarUrl());
categoryPaged.onSelect(categorySelect -> event.reply(HelpUtility.getHelpMessage(categorySelect.getSelected(), embed)).queue());
categoryPaged.execute(event);
});
paged.execute(event);
} else {
Sx4Category category = SearchUtility.getModule(commandName);
List<Sx4Command> commands = SearchUtility.getCommands(event.getCommandListener(), commandName, event.isAuthorDeveloper());
if (category != null) {
List<Sx4Command> categoryCommands = category.getCommands(event.isAuthorDeveloper()).stream().map(Sx4Command.class::cast).sorted(Comparator.comparing(Sx4Command::getCommandTrigger)).collect(Collectors.toList());
PagedResult<Sx4Command> paged = HelpUtility.getCommandsPaged(event.getBot(), categoryCommands).setAuthor(category.getName(), null, event.getAuthor().getEffectiveAvatarUrl());
paged.onSelect(select -> event.reply(HelpUtility.getHelpMessage(select.getSelected(), embed)).queue());
paged.execute(event);
} else if (!commands.isEmpty()) {
PagedResult<Sx4Command> paged = new PagedResult<>(event.getBot(), commands).setAuthor(commandName, null, event.getAuthor().getEffectiveAvatarUrl()).setAutoSelect(true).setPerPage(15).setSelectablePredicate((content, command) -> command.getCommandTrigger().equals(content)).setDisplayFunction(Sx4Command::getUsage);
paged.onSelect(select -> event.reply(HelpUtility.getHelpMessage(select.getSelected(), embed)).queue());
paged.execute(event);
} else {
event.replyFailure("I could not find that command/module").queue();
}
}
}
Aggregations