use of com.sx4.bot.annotations.argument.DefaultNumber 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.sx4.bot.annotations.argument.DefaultNumber in project Sx4 by sx4-discord-bot.
the class TemporaryBanCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "user") String userArgument, @Argument(value = "time", nullDefault = true) Duration time, @Argument(value = "reason", endless = true, nullDefault = true) Reason reason, @Option(value = "days", description = "Set how many days of messages should be deleted from the user") @DefaultNumber(1) @Limit(min = 0, max = 7) int days) {
SearchUtility.getUser(event.getShardManager(), userArgument).thenAccept(user -> {
if (user == null) {
event.replyFailure("I could not find that user").queue();
return;
}
if (user.getIdLong() == event.getSelfUser().getIdLong()) {
event.replyFailure("You cannot ban me, that is illegal").queue();
return;
}
Guild guild = event.getGuild();
Member member = guild.getMember(user);
if (member != null) {
if (!event.getMember().canInteract(member)) {
event.replyFailure("You cannot ban someone higher or equal than your top role").queue();
return;
}
if (!event.getSelfMember().canInteract(member)) {
event.replyFailure("I cannot ban someone higher or equal than my top role").queue();
return;
}
}
event.getGuild().retrieveBan(user).submit().whenComplete((ban, exception) -> {
if (exception instanceof ErrorResponseException && ((ErrorResponseException) exception).getErrorResponse() == ErrorResponse.UNKNOWN_BAN) {
Document data = event.getMongo().getGuildById(guild.getIdLong(), Projections.include("temporaryBan.defaultTime")).get("temporaryBan", MongoDatabase.EMPTY_DOCUMENT);
long duration = time == null ? data.get("defaultTime", ModUtility.DEFAULT_TEMPORARY_BAN_DURATION) : time.toSeconds();
List<Bson> update = List.of(Operators.set("unbanAt", Operators.add(Operators.nowEpochSecond(), duration)));
Bson filter = Filters.and(Filters.eq("userId", event.getMember().getIdLong()), Filters.eq("guildId", event.getGuild().getIdLong()));
event.getMongo().updateTemporaryBan(filter, update, new UpdateOptions().upsert(true)).whenComplete((result, resultException) -> {
if (ExceptionUtility.sendExceptionally(event, resultException)) {
return;
}
event.getGuild().ban(user, days).reason(ModUtility.getAuditReason(reason, event.getAuthor())).queue($ -> {
event.replySuccess("**" + user.getAsTag() + "** has been temporarily banned for " + TimeUtility.LONG_TIME_FORMATTER.parse(duration)).queue();
event.getBot().getModActionManager().onModAction(new TemporaryBanEvent(event.getMember(), user, reason, member != null, duration));
event.getBot().getTemporaryBanManager().putBan(event.getGuild().getIdLong(), user.getIdLong(), duration);
});
});
} else {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.replyFailure("That user is already banned").queue();
}
});
});
}
use of com.sx4.bot.annotations.argument.DefaultNumber in project Sx4 by sx4-discord-bot.
the class BanCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "user") String userArgument, @Argument(value = "reason", endless = true, nullDefault = true) Reason reason, @Option(value = "days", description = "Set how many days of messages should be deleted from the user") @DefaultNumber(1) @Limit(min = 0, max = 7) int days) {
SearchUtility.getUser(event.getShardManager(), userArgument).thenAccept(user -> {
if (user == null) {
event.replyFailure("I could not find that user").queue();
return;
}
if (user.getIdLong() == event.getSelfUser().getIdLong()) {
event.replyFailure("You cannot ban me, that is illegal").queue();
return;
}
Member member = event.getGuild().getMember(user);
if (member != null) {
if (!event.getMember().canInteract(member)) {
event.replyFailure("You cannot ban someone higher or equal than your top role").queue();
return;
}
if (!event.getSelfMember().canInteract(member)) {
event.replyFailure("I cannot ban someone higher or equal than my top role").queue();
return;
}
}
event.getGuild().retrieveBan(user).submit().whenComplete((ban, exception) -> {
if (exception instanceof ErrorResponseException && ((ErrorResponseException) exception).getErrorResponse() == ErrorResponse.UNKNOWN_BAN) {
event.getGuild().ban(user, days).reason(ModUtility.getAuditReason(reason, event.getAuthor())).queue($ -> {
event.replySuccess("**" + user.getAsTag() + "** has been banned").queue();
event.getBot().getModActionManager().onModAction(new BanEvent(event.getMember(), user, reason, member != null));
});
} else {
event.replyFailure("That user is already banned").queue();
}
});
});
}
use of com.sx4.bot.annotations.argument.DefaultNumber in project Sx4 by sx4-discord-bot.
the class PickaxeCommand method upgrade.
@Command(value = "upgrade", description = "Upgrade your pickaxe by a certain attribute")
@CommandId(427)
@Examples({ "pickaxe upgrade money", "pickaxe upgrade multiplier 10", "pickaxe 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.PICKAXE)) {
event.replyFailure("You can not use that upgrade on a pickaxe").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.PICKAXE.getId()))).first();
if (data == null) {
event.replyFailure("You do not have a pickaxe").queue();
session.abortTransaction();
return null;
}
Document item = data.get("item", Document.class);
Pickaxe defaultPickaxe = event.getBot().getEconomyManager().getItemById(item.getInteger("id"), Pickaxe.class);
Pickaxe pickaxe = new Pickaxe(item, defaultPickaxe);
int currentUpgrades = pickaxe.getUpgrades();
long price = 0;
for (int i = 0; i < upgrades; i++) {
price += Math.round(0.015D * defaultPickaxe.getPrice() * currentUpgrades++ + 0.025D * defaultPickaxe.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(defaultPickaxe.getPrice() * 0.015D) * upgrades)));
if (upgrade == Upgrade.MONEY) {
int increase = (int) Math.round(defaultPickaxe.getMinYield() * upgrade.getValue()) * upgrades;
update.add(Operators.set("item.minYield", Operators.add("$item.minYield", increase)));
update.add(Operators.set("item.maxYield", Operators.add("$item.maxYield", increase)));
} else 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 = defaultPickaxe.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", pickaxe.getId())), update);
return String.format("You just upgraded %s %d time%s for your `%s` for **$%,d**", upgrade.getName().toLowerCase(), upgrades, (upgrades == 1 ? "" : "s"), pickaxe.getName(), price);
}).whenComplete((message, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception) || message == null) {
return;
}
event.replySuccess(message).queue();
});
}
use of com.sx4.bot.annotations.argument.DefaultNumber in project Sx4 by sx4-discord-bot.
the class GuessTheNumberCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true) Member member, @Option(value = "min", description = "Choose the minimum number of the range") @Limit(min = 1) @DefaultNumber(1) int min, @Option(value = "max", description = "Choose the maximum number of the range") @Limit(min = 2) @DefaultNumber(50) int max) {
User opponent = member.getUser();
if (opponent.isBot()) {
event.replyFailure("You cannot play against bots").queue();
return;
}
if (opponent.getIdLong() == event.getAuthor().getIdLong()) {
event.replyFailure("You cannot play against yourself").queue();
return;
}
List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
event.reply(opponent.getAsMention() + ", do you want to play guess the number with **" + event.getAuthor().getName() + "**?").allowedMentions(EnumSet.of(Message.MentionType.USER)).setActionRow(buttons).submit().thenCompose(message -> {
return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, opponent)).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, opponent)).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
}).whenComplete((confirmEvent, confirmException) -> {
Throwable confirmCause = confirmException instanceof CompletionException ? confirmException.getCause() : confirmException;
if (confirmCause instanceof CancelException) {
GenericEvent cancelEvent = ((CancelException) confirmCause).getEvent();
if (cancelEvent != null) {
((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
}
return;
} else if (confirmCause instanceof TimeoutException) {
event.reply("Timed out :stopwatch:").queue();
return;
}
confirmEvent.deferEdit().queue();
CompletableFuture<MessageReceivedEvent> authorFuture = event.getAuthor().openPrivateChannel().submit().thenCompose(channel -> channel.sendMessage("Send a number between **" + min + "** and **" + max + "** or `cancel` to cancel").submit()).thenCompose(message -> {
return new Waiter<>(event.getBot(), MessageReceivedEvent.class).setUnique(event.getAuthor().getIdLong(), message.getChannel().getIdLong()).setTimeout(30).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setPredicate(e -> {
int number;
try {
number = Integer.parseInt(e.getMessage().getContentRaw());
} catch (NumberFormatException exception) {
return false;
}
return number >= min && number <= max;
}).start();
});
CompletableFuture<MessageReceivedEvent> opponentFuture = opponent.openPrivateChannel().submit().thenCompose(channel -> channel.sendMessage("Send a number between **" + min + "** and **" + max + "** or `cancel` to cancel").submit()).thenCompose(message -> {
return new Waiter<>(event.getBot(), MessageReceivedEvent.class).setUnique(opponent.getIdLong(), message.getChannel().getIdLong()).setTimeout(30).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setPredicate(e -> {
int number;
try {
number = Integer.parseInt(e.getMessage().getContentRaw());
} catch (NumberFormatException exception) {
return false;
}
return number >= min && number <= max;
}).start();
});
authorFuture.whenComplete((messageEvent, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof CancelException) {
opponentFuture.cancel(true);
if (((CancelException) cause).getType() == CancelType.USER) {
event.getAuthor().openPrivateChannel().flatMap(channel -> channel.sendMessage("Cancelled " + event.getConfig().getSuccessEmote())).queue();
}
event.replyFailure("**" + event.getAuthor().getAsTag() + "** cancelled their response").queue();
return;
} else if (cause instanceof TimeoutException) {
opponentFuture.cancel(true);
event.replyFailure("**" + event.getAuthor().getAsTag() + "** took too long to respond").queue();
return;
} else if (cause instanceof ErrorResponseException) {
opponentFuture.cancel(true);
event.replyFailure("I could not send a message to **" + event.getAuthor().getAsTag() + "**").queue();
return;
}
messageEvent.getChannel().sendMessage("Your number has been received, results will be sent in " + event.getTextChannel().getAsMention()).queue();
});
opponentFuture.whenComplete((messageEvent, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof CancelException) {
authorFuture.cancel(true);
if (((CancelException) cause).getType() == CancelType.USER) {
opponent.openPrivateChannel().flatMap(channel -> channel.sendMessage("Cancelled " + event.getConfig().getSuccessEmote())).queue();
}
event.replyFailure("**" + opponent.getAsTag() + "** cancelled their response").queue();
return;
} else if (cause instanceof TimeoutException) {
authorFuture.cancel(true);
event.replyFailure("**" + opponent.getAsTag() + "** took too long to respond").queue();
return;
} else if (cause instanceof ErrorResponseException) {
authorFuture.cancel(true);
event.replyFailure("I could not send a message to **" + opponent.getAsTag() + "**").queue();
return;
}
messageEvent.getChannel().sendMessage("Your number has been received, results will be sent in " + event.getTextChannel().getAsMention()).queue();
});
CompletableFuture.allOf(authorFuture, opponentFuture).whenComplete((result, exception) -> {
if (exception != null) {
return;
}
MessageReceivedEvent authorEvent = authorFuture.join(), opponentEvent = opponentFuture.join();
ObjectId gameId = ObjectId.get();
int authorNumber = Integer.parseInt(authorEvent.getMessage().getContentRaw());
int opponentNumber = Integer.parseInt(opponentEvent.getMessage().getContentRaw());
int randomNumber = event.getRandom().nextInt(max) + 1;
Document authorData = new Document("userId", event.getAuthor().getIdLong()).append("gameId", gameId).append("type", GameType.GUESS_THE_NUMBER.getId()).append("choice", authorNumber).append("answer", randomNumber);
Document opponentData = new Document("userId", opponent.getIdLong()).append("gameId", gameId).append("type", GameType.GUESS_THE_NUMBER.getId()).append("choice", authorNumber).append("answer", randomNumber);
int authorDifference = Math.abs(authorNumber - randomNumber), opponentDifference = Math.abs(opponentNumber - randomNumber);
StringBuilder content = new StringBuilder("The random number was **" + randomNumber + "**\n" + opponent.getName() + "'s number was **" + opponentNumber + "**\n" + event.getAuthor().getName() + "'s number was **" + authorNumber + "**\n\n");
if (authorDifference == opponentDifference) {
content.append("You both guessed the same number, It was a draw!");
authorData.append("state", GameState.DRAW.getId());
opponentData.append("state", GameState.DRAW.getId());
} else if (authorDifference > opponentDifference) {
content.append(opponent.getName()).append(" won! They were the closest to ").append(randomNumber);
authorData.append("state", GameState.LOSS.getId());
opponentData.append("state", GameState.WIN.getId());
} else {
content.append(event.getAuthor().getName()).append(" won! They were the closest to ").append(randomNumber);
authorData.append("state", GameState.WIN.getId());
opponentData.append("state", GameState.LOSS.getId());
}
event.reply(content.toString()).queue();
event.getMongo().insertManyGames(List.of(authorData, opponentData)).whenComplete(MongoDatabase.exceptionally());
});
});
}
Aggregations