use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.
the class AxeCommand method info.
@Command(value = "info", aliases = { "information" }, description = "View information on a users axe")
@CommandId(391)
@Examples({ "axe info", "axe info @Shea#6653", "axe info Shea" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void info(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
Member effectiveMember = member == null ? event.getMember() : member;
User user = member == null ? event.getAuthor() : effectiveMember.getUser();
Bson filter = Filters.and(Filters.eq("userId", effectiveMember.getIdLong()), Filters.eq("item.type", ItemType.AXE.getId()));
Document data = event.getMongo().getItem(filter, Projections.include("item"));
if (data == null) {
event.replyFailure("That user does not have an axe").queue();
return;
}
Axe axe = Axe.fromData(event.getBot().getEconomyManager(), data.get("item", Document.class));
EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getName() + "'s " + axe.getName(), null, user.getEffectiveAvatarUrl()).setColor(effectiveMember.getColorRaw()).setThumbnail("https://www.shareicon.net/data/2016/09/02/823994_ax_512x512.png").addField("Durability", axe.getDurability() + "/" + axe.getMaxDurability(), false).addField("Current Price", String.format("$%,d", axe.getCurrentPrice()), false).addField("Price", String.format("$%,d", axe.getPrice()), false).addField("Max Materials", String.valueOf(axe.getMaxMaterials()), false).addField("Multiplier", NumberUtility.DEFAULT_DECIMAL_FORMAT.format(axe.getMultiplier()), false);
event.reply(embed.build()).queue();
}
use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.
the class AxeCommand method repair.
@Command(value = "repair", description = "Repair your current axe with the material it is made from")
@CommandId(392)
@Examples({ "axe repair 10", "axe 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.AXE.getId()));
Document data = event.getMongo().getItem(filter, Projections.include("item"));
if (data == null) {
event.replyFailure("You do not have a axe").queue();
return;
}
Axe axe = Axe.fromData(event.getBot().getEconomyManager(), data.get("item", Document.class));
CraftItem item = axe.getRepairItem();
if (item == null) {
event.replyFailure("That axe is not repairable").queue();
return;
}
int maxDurability = axe.getMaxDurability() - axe.getDurability();
if (maxDurability <= 0) {
event.replyFailure("Your axe 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 axe by **" + maxDurability + "** durability :no_entry:").queue();
return;
}
durability = amount;
}
String acceptId = new CustomButtonId.Builder().setType(ButtonType.AXE_REPAIR_CONFIRM).setTimeout(60).setOwners(event.getAuthor().getIdLong()).setArguments(item.getId(), axe.getId(), axe.getDurability(), durability).getId();
String rejectId = new CustomButtonId.Builder().setType(ButtonType.GENERIC_REJECT).setTimeout(60).setOwners(event.getAuthor().getIdLong()).getId();
List<Button> buttons = List.of(Button.success(acceptId, "Yes"), Button.danger(rejectId, "No"));
int itemCount = (int) Math.ceil((((double) axe.getPrice() / item.getPrice()) / axe.getMaxDurability()) * durability);
event.reply("It will cost you `" + itemCount + " " + item.getName() + "` to repair your axe by **" + durability + "** durability, are you sure you want to repair it?").setActionRow(buttons).queue();
}
use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.
the class CrateCommand method shop.
@Command(value = "shop", description = "View all the crates you can buy")
@CommandId(411)
@Examples({ "crate shop" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void shop(Sx4CommandEvent event) {
List<Crate> crates = event.getBot().getEconomyManager().getItems(Crate.class).stream().filter(Predicate.not(Crate::isHidden)).collect(Collectors.toList());
PagedResult<Crate> paged = new PagedResult<>(event.getBot(), crates).setPerPage(12).setCustomFunction(page -> {
EmbedBuilder embed = new EmbedBuilder().setDescription("Crates give you a random item, the better the crate the better the chance of a better item").setAuthor("Crate Shop", null, event.getSelfUser().getEffectiveAvatarUrl()).setTitle("Page " + page.getPage() + "/" + page.getMaxPage()).setFooter(PagedResult.DEFAULT_FOOTER_TEXT);
page.forEach((crate, index) -> embed.addField(crate.getName(), String.format("Price: $%,d\nContents: %s", crate.getPrice(), crate.getContentString()), true));
return new MessageBuilder().setEmbeds(embed.build());
});
paged.execute(event);
}
use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.
the class DailyCommand method onCommand.
public void onCommand(Sx4CommandEvent event) {
List<Bson> update = List.of(Operators.set("economy.balance", Operators.let(new Document("reset", Operators.ifNull("$economy.resets.daily", 0L)).append("balance", Operators.ifNull("$economy.balance", 0L)), Operators.let(new Document("streak", Operators.cond(Operators.and(Operators.gte(Operators.nowEpochSecond(), "$$reset"), Operators.lt(Operators.nowEpochSecond(), Operators.add("$$reset", DailyCommand.COOLDOWN))), Operators.add(Operators.ifNull("$economy.streak", 0), 1), 0)), Operators.cond(Operators.lt(Operators.nowEpochSecond(), "$$reset"), "$$balance", Operators.add("$$balance", Operators.add(100L, Operators.multiply(Operators.min(10L, "$$streak"), Operators.add(20L, Operators.multiply(Operators.min(10L, "$$streak"), 5L))))))))), Operators.set("economy.streak", Operators.let(new Document("reset", Operators.ifNull("$economy.resets.daily", 0L)).append("streak", Operators.ifNull("$economy.streak", 0)), Operators.cond(Operators.and(Operators.gte(Operators.nowEpochSecond(), "$$reset"), Operators.lt(Operators.nowEpochSecond(), Operators.add("$$reset", DailyCommand.COOLDOWN))), Operators.add("$$streak", 1), Operators.cond(Operators.lt(Operators.nowEpochSecond(), "$$reset"), "$$streak", 0)))), Operators.set("economy.resets.daily", Operators.let(new Document("reset", Operators.ifNull("$economy.resets.daily", 0L)), Operators.cond(Operators.lt(Operators.nowEpochSecond(), "$$reset"), "$$reset", Operators.add(Operators.nowEpochSecond(), DailyCommand.COOLDOWN)))));
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("economy.resets.daily", "economy.streak")).upsert(true);
EmbedBuilder embed = new EmbedBuilder().setAuthor(event.getAuthor().getName(), null, event.getAuthor().getEffectiveAvatarUrl()).setColor(event.getMember().getColor());
event.getMongo().findAndUpdateUserById(event.getAuthor().getIdLong(), update, options).thenCompose(data -> {
Document economy = (data == null ? MongoDatabase.EMPTY_DOCUMENT : data).get("economy", MongoDatabase.EMPTY_DOCUMENT);
long reset = economy.getEmbedded(List.of("resets", "daily"), 0L), timestamp = Clock.systemUTC().instant().getEpochSecond();
if (timestamp < reset) {
event.reply("Slow down! You can collect your daily in " + TimeUtility.LONG_TIME_FORMATTER.parse(reset - timestamp) + " :stopwatch:").queue();
return CompletableFuture.completedFuture(null);
}
int previousStreak = economy.get("streak", 0);
int streak = timestamp < reset + DailyCommand.COOLDOWN ? previousStreak + 1 : 0;
long money = 100 + Math.min(10, streak) * (20 + Math.min(10, streak) * 5L);
embed.setDescription("You have collected your daily money (**$" + money + "**)" + (streak == 0 && previousStreak != streak ? "\n\nIt has been over 2 days since you last collected your daily, your streak has been reset" : streak == 0 ? "" : "\nYou had a bonus of $" + (money - 100) + String.format(" for having a %,d day streak", streak)));
List<Crate> crates = new ArrayList<>();
if (streak != 0) {
for (Crate crate : event.getBot().getEconomyManager().getItems(Crate.class)) {
if (crate.isHidden()) {
continue;
}
double randomDouble = event.getBot().getEconomyManager().getRandom().nextDouble();
if (randomDouble <= Math.min(1D / Math.ceil((crate.getPrice() / 10D / streak) * 4), 1)) {
crates.add(crate);
}
}
}
crates.sort(Comparator.comparingLong(Crate::getPrice).reversed());
if (!crates.isEmpty()) {
Crate crate = crates.get(0);
embed.appendDescription(String.format("\n\nYou also received a `%s` (**$%,d**), it has been added to your items.", crate.getName(), crate.getPrice()));
List<Bson> crateUpdate = List.of(Operators.set("item", crate.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), 1L)));
return event.getMongo().updateItem(Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", crate.getId())), crateUpdate, new UpdateOptions().upsert(true));
}
return CompletableFuture.completedFuture(UpdateResult.acknowledged(0L, 0L, null));
}).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception) || result == null) {
return;
}
event.reply(embed.build()).queue();
});
}
use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.
the class YouTubeNotificationCommand method add.
@Command(value = "add", description = "Add a youtube notification to be posted to a specific channel when the user uploads")
@CommandId(158)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "youtube notification add videos mrbeast", "youtube notification add mrbeast", "youtube notification add #videos pewdiepie" })
public void add(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) BaseGuildMessageChannel channel, @Argument(value = "youtube channel", endless = true) String channelQuery) {
if (!event.getBot().getConnectionHandler().isReady()) {
event.replyFailure("The bot has to be fully started to use this command, try again later").queue();
return;
}
MessageChannel messageChannel = event.getChannel();
if (channel == null && !(messageChannel instanceof BaseGuildMessageChannel)) {
event.replyFailure("You cannot use this channel type").queue();
return;
}
BaseGuildMessageChannel effectiveChannel = channel == null ? (BaseGuildMessageChannel) messageChannel : channel;
boolean id = this.id.matcher(channelQuery).matches();
boolean search;
String queryName, query;
Matcher matcher = this.url.matcher(channelQuery);
if (!id && matcher.matches()) {
String path = matcher.group(1);
search = false;
queryName = path == null || path.equals("user") ? "forUsername" : "id";
query = matcher.group(2);
} else {
search = !id;
queryName = id ? "id" : "q";
query = channelQuery;
}
Request channelRequest = new Request.Builder().url("https://www.googleapis.com/youtube/v3/" + (search ? "search" : "channels") + "?key=" + event.getConfig().getYouTube() + "&" + queryName + "=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&part=snippet&type=channel&maxResults=1").build();
event.getHttpClient().newCall(channelRequest).enqueue((HttpCallback) channelResponse -> {
Document json = Document.parse(channelResponse.body().string());
List<Document> items = json.getList("items", Document.class, Collections.emptyList());
if (items.isEmpty()) {
event.replyFailure("I could not find that youtube channel").queue();
return;
}
Document item = items.get(0);
String channelId = search ? item.getEmbedded(List.of("id", "channelId"), String.class) : item.getString("id");
Document notificationData = new Document("uploaderId", channelId).append("channelId", effectiveChannel.getIdLong()).append("guildId", event.getGuild().getIdLong());
if (!event.getBot().getYouTubeManager().hasExecutor(channelId)) {
RequestBody body = new MultipartBody.Builder().addFormDataPart("hub.mode", "subscribe").addFormDataPart("hub.topic", "https://www.youtube.com/xml/feeds/videos.xml?channel_id=" + channelId).addFormDataPart("hub.callback", event.getConfig().getBaseUrl() + "/api/youtube").addFormDataPart("hub.verify", "sync").addFormDataPart("hub.verify_token", event.getConfig().getYouTube()).setType(MultipartBody.FORM).build();
Request request = new Request.Builder().url("https://pubsubhubbub.appspot.com/subscribe").post(body).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
if (response.isSuccessful()) {
this.addNotification(event, effectiveChannel.getIdLong(), notificationData).whenComplete((result, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
event.replyFailure("You already have a notification setup for that youtube channel in " + effectiveChannel.getAsMention()).queue();
return;
}
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.replyFormat("Notifications will now be sent in %s when **%s** uploads with id `%s` %s", effectiveChannel.getAsMention(), item.getEmbedded(List.of("snippet", "title"), String.class), result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).queue();
});
} else {
event.replyFailure("Oops something went wrong there, try again. If this repeats report this to my developer (Message: " + response.body().string() + ")").queue();
}
});
} else {
this.addNotification(event, effectiveChannel.getIdLong(), notificationData).whenComplete((result, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
event.replyFailure("You already have a notification setup for that youtube channel in " + effectiveChannel.getAsMention()).queue();
return;
}
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.replyFormat("Notifications will now be sent in %s when **%s** uploads with id `%s` %s", effectiveChannel.getAsMention(), item.getEmbedded(List.of("snippet", "title"), String.class), result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).queue();
});
}
});
}
Aggregations