use of com.sx4.bot.annotations.command.CommandId in project Sx4 by sx4-discord-bot.
the class WarnCommand method view.
@Command(value = "view", description = "View the amount of warnings a specific user is on")
@CommandId(259)
@Examples({ "warn view @Shea#6653", "warn view Shea", "warn view 402557516728369153" })
@Redirects({ "warnings", "warns" })
public void view(Sx4CommandEvent event, @Argument(value = "user", endless = true) Member member) {
List<Bson> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("userId", member.getIdLong()), Filters.eq("guildId", event.getGuild().getIdLong()))), Aggregates.project(Projections.computed("warnings", Operators.cond(Operators.or(Operators.isNull("$reset"), Operators.isNull("$warnings")), Operators.ifNull("$warnings", 0), Operators.max(0, Operators.subtract("$warnings", Operators.multiply(Operators.toInt(Operators.floor(Operators.divide(Operators.subtract(Operators.nowEpochSecond(), "$lastWarning"), "$reset.after"))), "$reset.amount")))))));
event.getMongo().aggregateWarnings(pipeline).whenComplete((documents, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
Document data = documents.isEmpty() ? MongoDatabase.EMPTY_DOCUMENT : documents.get(0);
int warnings = data.getInteger("warnings", 0);
event.reply("**" + member.getUser().getAsTag() + "** is currently on **" + warnings + "** warning" + (warnings == 1 ? "" : "s")).queue();
});
}
use of com.sx4.bot.annotations.command.CommandId in project Sx4 by sx4-discord-bot.
the class WarnCommand method set.
@Command(value = "set", description = "Set the amount of warns a user has")
@CommandId(242)
@Redirects({ "set warns", "set warnings" })
@Examples({ "warn set @Shea#6653 2", "warn set Shea#6653 0", "warn set 402557516728369153 1" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void set(Sx4CommandEvent event, @Argument(value = "user") Member member, @Argument(value = "warnings") int warnings) {
if (member.canInteract(event.getMember())) {
event.replyFailure("You cannot change the amount of warnings of someone higher or equal than your top role").queue();
return;
}
Document warnData = event.getMongo().getGuildById(event.getGuild().getIdLong(), Projections.include("warn")).get("warn", MongoDatabase.EMPTY_DOCUMENT);
boolean punishments = warnData.get("punishments", true);
int maxWarning = punishments ? warnData.getList("config", Document.class, Warn.DEFAULT_CONFIG).stream().map(d -> d.getInteger("number")).max(Integer::compareTo).get() : Integer.MAX_VALUE;
if (warnings > maxWarning) {
event.replyFailure("The max amount of warnings you can give is **" + maxWarning + "**").queue();
return;
}
Bson update = warnings == 0 ? Updates.unset("warnings") : Updates.combine(Updates.set("warnings", warnings), Updates.set("lastWarning", Clock.systemUTC().instant().getEpochSecond()));
Bson filter = Filters.and(Filters.eq("userId", member.getIdLong()), Filters.eq("guildId", event.getGuild().getIdLong()));
event.getMongo().updateWarnings(filter, update, new UpdateOptions().upsert(true)).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (result.getModifiedCount() == 0 && result.getUpsertedId() == null) {
event.replyFailure("That user already had that amount of warnings").queue();
return;
}
event.replySuccess("That user now has **" + warnings + "** warning" + (warnings == 1 ? "" : "s")).queue();
});
}
use of com.sx4.bot.annotations.command.CommandId in project Sx4 by sx4-discord-bot.
the class SteamCommand method compare.
@Command(value = "compare", description = "Compare what games 2 steam accounts have in common")
@CommandId(279)
@Examples({ "steam compare dog cat", "steam compare https://steamcommunity.com/id/dog https://steamcommunity.com/id/cat" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void compare(Sx4CommandEvent event, @Argument(value = "first profile") String firstQuery, @Argument(value = "second profile", endless = true) String secondQuery) {
String firstUrl = this.getProfileUrl(firstQuery), secondUrl = this.getProfileUrl(secondQuery);
Request firstRequest = new Request.Builder().url(firstUrl + "games/?tab=all&xml=1").build();
Request secondRequest = new Request.Builder().url(secondUrl + "games/?tab=all&xml=1").build();
event.getHttpClient().newCall(firstRequest).enqueue((HttpCallback) firstResponse -> {
JSONObject firstData = XML.toJSONObject(firstResponse.body().string()).getJSONObject("gamesList");
if (firstData.has("error")) {
event.replyFailure("The steam profile <https://steamcommunity.com/profiles/" + firstData.getLong("steamID64") + "> is private").queue();
return;
}
event.getHttpClient().newCall(secondRequest).enqueue((HttpCallback) secondResponse -> {
JSONObject secondData = XML.toJSONObject(secondResponse.body().string()).getJSONObject("gamesList");
if (secondData.has("error")) {
event.replyFailure("The steam profile <https://steamcommunity.com/profiles/" + secondData.getLong("steamID64") + "> is private").queue();
return;
}
JSONArray firstGames = firstData.getJSONObject("games").getJSONArray("game"), secondGames = secondData.getJSONObject("games").getJSONArray("game");
Map<Integer, String> commonGames = new HashMap<>();
for (int x = 0; x < firstGames.length(); x++) {
for (int y = 0; y < secondGames.length(); y++) {
JSONObject firstGame = firstGames.getJSONObject(x), secondGame = secondGames.getJSONObject(y);
if (firstGame.getInt("appID") == secondGame.getInt("appID")) {
commonGames.put(firstGame.getInt("appID"), firstGame.getString("name"));
}
}
}
PagedResult<Map.Entry<Integer, String>> paged = new PagedResult<>(event.getBot(), new ArrayList<>(commonGames.entrySet())).setAuthor("Games In Common (" + commonGames.size() + ")", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setPerPage(15).setIncreasedIndex(true).setDisplayFunction(d -> "[" + d.getValue() + "](https://store.steampowered.com/app/" + d.getKey() + ")");
paged.execute(event);
});
});
}
use of com.sx4.bot.annotations.command.CommandId in project Sx4 by sx4-discord-bot.
the class SteamCommand method connect.
@Command(value = "connect", description = "Connect your steam account with Sx4")
@CommandId(488)
@Examples({ "steam connect" })
public void connect(Sx4CommandEvent event) {
String id = event.getAuthor().getId();
long timestamp = Instant.now().getEpochSecond();
String signature;
try {
signature = HmacUtility.getSignatureHex(event.getConfig().getSteam(), id + timestamp, HmacUtility.HMAC_MD5);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
event.replyFailure("Something went wrong there, try again").queue();
return;
}
String redirectUrl = URLEncoder.encode(event.getConfig().getBaseUrl() + "/redirect/steam?user_id=" + id + "×tamp=" + timestamp + "&signature=" + signature, StandardCharsets.UTF_8);
MessageEmbed embed = new EmbedBuilder().setAuthor("Steam Authorization").setDescription("The link below will allow you to link your steam account on Sx4\n**:warning: Do not give this link to anyone :warning:**\n\n[Authorize](https://sx4.dev/connect/steam?redirect_url=" + redirectUrl + ")").setColor(event.getConfig().getOrange()).setFooter("The authorization link will expire in 5 minutes").build();
event.getAuthor().openPrivateChannel().flatMap(channel -> channel.sendMessageEmbeds(embed)).flatMap($ -> event.replySuccess("I sent you a message containing your authorization link")).onErrorFlatMap($ -> event.replyFailure("I failed to send you your authorization link, make sure to have your dms open")).queue();
}
use of com.sx4.bot.annotations.command.CommandId in project Sx4 by sx4-discord-bot.
the class PickaxeCommand method repair.
@Command(value = "repair", description = "Repair your current pickaxe with the material it is made from")
@CommandId(363)
@Examples({ "pickaxe repair 10", "pickaxe repair all" })
public void repair(Sx4CommandEvent event, @Argument(value = "durability") @AlternativeOptions("all") Alternative<Integer> option) {
Bson filter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.type", ItemType.PICKAXE.getId()));
Document data = event.getMongo().getItem(filter, Projections.include("item"));
if (data == null) {
event.replyFailure("You do not have a pickaxe").queue();
return;
}
Pickaxe pickaxe = Pickaxe.fromData(event.getBot().getEconomyManager(), data.get("item", Document.class));
CraftItem item = pickaxe.getRepairItem();
if (item == null) {
event.replyFailure("That pickaxe is not repairable").queue();
return;
}
int maxDurability = pickaxe.getMaxDurability() - pickaxe.getDurability();
if (maxDurability <= 0) {
event.replyFailure("Your pickaxe is already at full durability").queue();
return;
}
int durability;
if (option.isAlternative()) {
durability = maxDurability;
} else {
int amount = option.getValue();
if (amount > maxDurability) {
event.reply("You can only repair your pickaxe by **" + maxDurability + "** durability :no_entry:").queue();
return;
}
durability = amount;
}
int itemCount = (int) Math.ceil((((double) pickaxe.getPrice() / item.getPrice()) / pickaxe.getMaxDurability()) * durability);
List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
event.reply("It will cost you `" + itemCount + " " + item.getName() + "` to repair your pickaxe by **" + durability + "** durability, are you sure you want to repair it?").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;
}
List<Bson> update = List.of(Operators.set("amount", Operators.let(new Document("amount", Operators.ifNull("$amount", 0L)), Operators.cond(Operators.lte(itemCount, "$$amount"), Operators.subtract("$$amount", itemCount), "$$amount"))));
event.getMongo().updateItem(Filters.and(Filters.eq("item.id", item.getId()), Filters.eq("userId", event.getAuthor().getIdLong())), update, new UpdateOptions()).thenCompose(result -> {
if (result.getMatchedCount() == 0 || result.getModifiedCount() == 0) {
e.reply("You do not have `" + itemCount + " " + item.getName() + "` " + event.getConfig().getFailureEmote()).queue();
return CompletableFuture.completedFuture(null);
}
List<Bson> itemUpdate = List.of(Operators.set("item.durability", Operators.cond(Operators.eq("$item.durability", pickaxe.getDurability()), Operators.add("$item.durability", durability), "$item.durability")));
return event.getMongo().updateItem(Filters.and(Filters.eq("item.id", pickaxe.getId()), Filters.eq("userId", event.getAuthor().getIdLong())), itemUpdate, new UpdateOptions());
}).whenComplete((result, databaseException) -> {
if (ExceptionUtility.sendExceptionally(event, databaseException) || result == null) {
return;
}
if (result.getMatchedCount() == 0) {
e.reply("You no longer have that pickaxe " + event.getConfig().getFailureEmote()).queue();
return;
}
if (result.getMatchedCount() == 0) {
e.reply("The durability of your pickaxe has changed " + event.getConfig().getFailureEmote()).queue();
return;
}
e.reply("You just repaired your pickaxe by **" + durability + "** durability " + event.getConfig().getSuccessEmote()).queue();
});
});
}
Aggregations