use of com.jockie.bot.core.argument.Argument 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.jockie.bot.core.argument.Argument 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.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class WeatherCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
Request request = new Request.Builder().url(event.getConfig().getSearchWebserverUrl("weather") + "?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8)).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
if (response.code() == 404) {
event.replyFailure("I could not find that location").queue();
return;
}
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;
}
Document now = document.get("now", Document.class);
Document today = document.get("today", Document.class);
int windDegrees = now.getInteger("wdir");
Integer maxTemp = today.getInteger("max_temp");
EmbedBuilder embed = new EmbedBuilder();
embed.setAuthor(document.getString("location"), document.getString("url"), null);
embed.setTitle(now.getString("phrase_32char"));
embed.addField("Temperature", String.format("Maximum: %s°C\nCurrent: %d°C\nMinimum: %d°C", maxTemp == null ? "--" : maxTemp, now.getInteger("temp"), today.getInteger("min_temp")), true);
embed.addBlankField(true);
embed.addField("Wind", String.format("Direction: %d° (%s)\nSpeed: %d mph", windDegrees, Direction.getDirection(windDegrees).getName(), now.getInteger("wspd")), true);
embed.addField("Humidity", now.getInteger("rh") + "%", true);
embed.addBlankField(true);
embed.addField("Precipitation", now.getInteger("pop") + "%", true);
embed.setThumbnail(now.getString("icon"));
embed.setFooter(now.getString("dow") + " " + OffsetDateTime.parse(now.getString("fcst_valid_local"), this.parseFormatter).format(this.formatter));
event.reply(embed.build()).queue();
});
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class ShortenCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "url") String url) {
Request request = new Request.Builder().url("https://api-ssl.bitly.com/v4/shorten").post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Document("long_url", url).toJson())).addHeader("Authorization", "Bearer " + event.getConfig().getBitly()).addHeader("Content-Type", "application/json").build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document json = Document.parse(response.body().string());
event.replyFormat("<" + json.getString("link") + ">").queue();
});
}
use of com.jockie.bot.core.argument.Argument 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