use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.
the class YouTubeNotificationCommand method list.
@Command(value = "list", description = "View all the notifications you have setup throughout your server")
@CommandId(165)
@Examples({ "youtube notification list" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void list(Sx4CommandEvent event) {
List<Document> notifications = event.getMongo().getYouTubeNotifications(Filters.eq("guildId", event.getGuild().getIdLong()), Projections.include("uploaderId", "channelId", "message")).into(new ArrayList<>());
if (notifications.isEmpty()) {
event.replyFailure("You have no notifications setup in this server").queue();
return;
}
List<String> channels = notifications.stream().map(d -> d.getString("uploaderId")).distinct().collect(Collectors.toList());
int size = channels.size();
List<CompletableFuture<Map<String, String>>> futures = new ArrayList<>();
for (int i = 0; i < Math.ceil(size / 50D); i++) {
List<String> splitChannels = channels.subList(i * 50, Math.min((i + 1) * 50, size));
String ids = String.join(",", splitChannels);
Request request = new Request.Builder().url("https://www.googleapis.com/youtube/v3/channels?key=" + event.getConfig().getYouTube() + "&id=" + ids + "&part=snippet&maxResults=50").build();
CompletableFuture<Map<String, String>> future = new CompletableFuture<>();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document data = Document.parse(response.body().string());
List<Document> items = data.getList("items", Document.class);
Map<String, String> names = new HashMap<>();
for (Document item : items) {
names.put(item.getString("id"), item.getEmbedded(List.of("snippet", "title"), String.class));
}
future.complete(names);
});
futures.add(future);
}
FutureUtility.allOf(futures).whenComplete((maps, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
Map<String, String> names = new HashMap<>();
for (Map<String, String> map : maps) {
names.putAll(map);
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), notifications).setIncreasedIndex(true).setAutoSelect(false).setAuthor("YouTube Notifications", null, event.getGuild().getIconUrl()).setDisplayFunction(data -> {
String uploaderId = data.getString("uploaderId");
return String.format("%s - [%s](https://youtube.com/channel/%s)", data.getObjectId("_id").toHexString(), names.getOrDefault(uploaderId, "Unknown"), uploaderId);
}).setSelect(SelectType.INDEX);
paged.onSelect(selected -> this.sendStats(event, selected.getSelected()));
paged.execute(event);
});
}
use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.
the class GiveawayCommand method restart.
@Command(value = "restart", description = "Restarts a giveaway")
@CommandId(48)
@Examples({ "giveaway restart 727224132202397726" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void restart(Sx4CommandEvent event, @Argument(value = "message id") MessageArgument messageArgument, @Argument(value = "duration", endless = true, nullDefault = true) Duration duration) {
long timeNow = Clock.systemUTC().instant().getEpochSecond();
List<Bson> update = List.of(Operators.set("endAt", Operators.cond(Operators.exists("$winners"), duration == null ? Operators.add(timeNow, "$duration") : duration.toSeconds() + timeNow, "$endAt")), Operators.set("duration", Operators.cond(Operators.exists("$winners"), duration == null ? "$duration" : duration.toSeconds(), "$duration")), Operators.unset("winners"));
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.exclude("winners"));
event.getMongo().findAndUpdateGiveawayById(messageArgument.getMessageId(), update, options).whenComplete((data, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (data == null) {
event.replyFailure("There is no giveaway with that id").queue();
return;
}
if (data.getLong("endAt") - timeNow > 0) {
event.replyFailure("That giveaway has not ended yet").queue();
return;
}
long seconds = duration == null ? data.getLong("duration") : duration.toSeconds();
BaseGuildMessageChannel channel = event.getGuild().getChannelById(BaseGuildMessageChannel.class, data.getLong("channelId"));
if (channel == null) {
event.replyFailure("That giveaway no longer exists").queue();
return;
}
channel.editMessageEmbedsById(data.getLong("messageId"), this.getEmbed(data.getInteger("winnersAmount"), seconds, data.getString("item"))).queue();
event.getBot().getGiveawayManager().putGiveaway(data, seconds);
event.replySuccess("That giveaway has been restarted").queue();
});
}
use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.
the class GiveawayCommand method list.
@Command(value = "list", description = "Lists all the giveaways which have happened in the server")
@CommandId(52)
@Examples({ "giveaway list" })
public void list(Sx4CommandEvent event) {
List<Document> giveaways = event.getMongo().getGiveaways(Filters.eq("guildId", event.getGuild().getIdLong())).into(new ArrayList<>());
if (giveaways.isEmpty()) {
event.replyFailure("No giveaways have been setup in this server").queue();
return;
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), giveaways).setAuthor("Giveaways", null, event.getGuild().getIconUrl()).setDisplayFunction(data -> {
long endAt = data.getLong("endAt"), timeNow = Clock.systemUTC().instant().getEpochSecond();
return data.getLong("messageId") + " - " + (endAt - timeNow < 0 ? "Ended" : TimeUtility.LONG_TIME_FORMATTER.parse(endAt - timeNow));
});
paged.onSelect(select -> {
ShardManager shardManager = event.getShardManager();
Document data = select.getSelected();
List<Long> winners = data.getList("winners", Long.class, Collections.emptyList());
String winnersString = winners.isEmpty() ? "None" : winners.stream().map(shardManager::getUserById).filter(Objects::nonNull).map(User::getAsMention).collect(Collectors.joining(", "));
event.replyFormat("**Giveaway %d**\nItem: %s\nWinner%s: %s\nDuration: %s", data.getLong("messageId"), data.getString("item"), winners.size() == 1 ? "" : "s", winnersString, TimeUtility.LONG_TIME_FORMATTER.parse(data.getLong("duration"))).queue();
});
paged.execute(event);
}
use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.
the class GiveawayManager method endGiveawayBulk.
public CompletableFuture<UpdateOneModel<Document>> endGiveawayBulk(Document data, boolean forced) {
long guildId = data.getLong("guildId"), messageId = data.get("messageId", 0L);
Guild guild = this.bot.getShardManager().getGuildById(guildId);
if (guild == null) {
return CompletableFuture.completedFuture(null);
}
BaseGuildMessageChannel channel = guild.getChannelById(BaseGuildMessageChannel.class, data.getLong("channelId"));
if (channel == null) {
return CompletableFuture.completedFuture(null);
}
if (!guild.getSelfMember().hasPermission(channel, Permission.VIEW_CHANNEL, Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS)) {
return CompletableFuture.completedFuture(null);
}
CompletableFuture<UpdateOneModel<Document>> future = new CompletableFuture<>();
channel.retrieveMessageById(messageId).queue(message -> {
MessageReaction reaction = message.getReactions().stream().filter(r -> r.getReactionEmote().getName().equals("🎉")).findFirst().orElse(null);
if (reaction == null) {
future.complete(null);
return;
}
List<Long> oldWinners = data.getList("winners", Long.class, Collections.emptyList());
List<Member> members = new ArrayList<>();
reaction.retrieveUsers().forEachAsync(user -> {
Member member = guild.getMember(user);
if (member != null && member.getIdLong() != guild.getSelfMember().getIdLong() && !oldWinners.contains(member.getIdLong())) {
members.add(member);
}
return true;
}).thenRun(() -> {
Bson update;
if (members.size() == 0) {
update = Updates.set("winners", Collections.EMPTY_LIST);
future.complete(new UpdateOneModel<>(Filters.eq("messageId", messageId), forced ? Updates.combine(Updates.set("endAt", Clock.systemUTC().instant().getEpochSecond()), update) : update));
channel.sendMessage("At least " + (oldWinners.isEmpty() ? "1 person needs" : oldWinners.size() == 1 ? "1 extra person needs" : oldWinners.size() + " extra people need") + " to have entered the giveaway to pick a winner " + this.bot.getConfig().getFailureEmote()).queue();
return;
}
Set<Member> winners = MathUtility.randomSample(members, Math.min(data.getInteger("winnersAmount"), members.size()));
List<Long> winnerIds = new ArrayList<>();
List<String> winnerTags = new ArrayList<>(), winnerMentions = new ArrayList<>();
for (Member winner : winners) {
winnerIds.add(winner.getIdLong());
winnerTags.add(winner.getUser().getAsTag());
winnerMentions.add(winner.getAsMention());
}
if (guild.getSelfMember().hasPermission(channel, Permission.MESSAGE_SEND)) {
channel.sendMessage(String.join(", ", winnerMentions) + ", Congratulations you have won the giveaway for **" + data.getString("item") + "**").allowedMentions(EnumSet.of(MentionType.USER)).queue();
}
EmbedBuilder embed = new EmbedBuilder();
embed.setTitle("Giveaway");
embed.setDescription("**" + String.join(", ", winnerTags) + "** has won **" + data.getString("item") + "**");
embed.setTimestamp(Instant.now());
embed.setFooter("Giveaway Ended", null);
if (guild.getSelfMember().hasPermission(channel, Permission.MESSAGE_SEND, Permission.MESSAGE_EMBED_LINKS)) {
message.editMessageEmbeds(embed.build()).queue();
}
update = Updates.set("winners", winnerIds);
future.complete(new UpdateOneModel<>(Filters.eq("messageId", messageId), forced ? Updates.combine(Updates.set("endAt", Clock.systemUTC().instant().getEpochSecond()), update) : update));
});
});
this.deleteExecutor(messageId);
return future;
}
use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.
the class GiveawayCommand method setup.
@Command(value = "setup", description = "Setup giveaways for users to react to")
@CommandId(47)
@Examples({ "giveaway setup", "giveaway setup #giveaways 1 7d $10 Nitro" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void setup(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) TextChannel channel, @Argument(value = "winners") @DefaultNumber(0) @Limit(min = 1) int winners, @Argument(value = "duration", nullDefault = true) Duration duration, @Argument(value = "item", nullDefault = true, endless = true) String item) {
if (channel != null && winners != 0 && duration != null && item != null) {
long seconds = duration.toSeconds();
if (seconds < 1) {
event.replyFailure("The duration of a giveaway cannot be less than 1 second").queue();
return;
}
channel.sendMessageEmbeds(this.getEmbed(winners, seconds, item)).queue(message -> {
message.addReaction("🎉").queue();
Document data = new Document("messageId", message.getIdLong()).append("channelId", channel.getIdLong()).append("guildId", event.getGuild().getIdLong()).append("winnersAmount", winners).append("endAt", Clock.systemUTC().instant().getEpochSecond() + seconds).append("duration", seconds).append("item", item);
event.getMongo().insertGiveaway(data).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.getBot().getGiveawayManager().putGiveaway(data, seconds);
event.reply("Your giveaway has been created in " + channel.getAsMention() + " :tada:").queue();
});
});
return;
}
AtomicReference<TextChannel> atomicChannel = new AtomicReference<>();
AtomicInteger atomicWinners = new AtomicInteger();
AtomicReference<Duration> atomicDuration = new AtomicReference<>();
AtomicReference<String> atomicItem = new AtomicReference<>();
CompletableFuture.completedFuture(true).thenCompose($ -> {
if (channel != null) {
atomicChannel.set(channel);
return CompletableFuture.completedFuture(true);
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
event.reply("What channel would you like to start the giveaway in? Type `cancel` at anytime to cancel the creation.").queue(message -> {
Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setPredicate(e -> {
TextChannel textChannel = SearchUtility.getTextChannel(event.getGuild(), e.getMessage().getContentRaw());
if (textChannel != null) {
atomicChannel.set(textChannel);
return true;
}
event.replyFailure("I could not find that channel").queue();
return false;
});
waiter.onCancelled((type) -> {
event.replySuccess("Cancelled").queue();
future.complete(false);
});
waiter.onTimeout(() -> {
event.reply("Response timed out :stopwatch:").queue();
future.complete(false);
});
waiter.onSuccess(e -> future.complete(true));
waiter.start();
});
return future;
}).thenCompose(success -> {
if (!success) {
return CompletableFuture.completedFuture(false);
}
if (winners != 0) {
atomicWinners.set(winners);
return CompletableFuture.completedFuture(true);
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
event.reply("How many winners would you like the giveaway to have?").queue(message -> {
Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
String content = e.getMessage().getContentRaw();
if (NumberUtility.isNumberUnsigned(content)) {
int number = Integer.parseInt(content);
if (number < 1) {
event.replyFailure("You have to have at least 1 winner").queue();
return false;
}
atomicWinners.set(number);
return true;
}
event.replyFailure("That is not a number").queue();
return false;
});
waiter.onCancelled((type) -> {
event.replySuccess("Cancelled").queue();
future.complete(false);
});
waiter.onTimeout(() -> {
event.reply("Response timed out :stopwatch:").queue();
future.complete(false);
});
waiter.onSuccess(e -> future.complete(true));
waiter.start();
});
return future;
}).thenCompose(success -> {
if (!success) {
return CompletableFuture.completedFuture(false);
}
if (duration != null) {
atomicDuration.set(duration);
return CompletableFuture.completedFuture(true);
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
event.reply("How long would you like the giveaway to last?").queue(message -> {
Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
Duration durationReply = TimeUtility.getDurationFromString(e.getMessage().getContentRaw());
if (durationReply.toSeconds() < 1) {
event.replyFailure("The duration of a giveaway cannot be less than 1 second").queue();
return false;
}
atomicDuration.set(durationReply);
return true;
});
waiter.onCancelled((type) -> {
event.replySuccess("Cancelled").queue();
future.complete(false);
});
waiter.onTimeout(() -> {
event.reply("Response timed out :stopwatch:").queue();
future.complete(false);
});
waiter.onSuccess(e -> future.complete(true));
waiter.start();
});
return future;
}).thenCompose(success -> {
if (!success) {
return CompletableFuture.completedFuture(false);
}
if (item != null) {
atomicItem.set(item);
return CompletableFuture.completedFuture(true);
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
event.reply("What would you like to giveaway?").queue(message -> {
Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
String content = e.getMessage().getContentRaw();
if (content.equalsIgnoreCase("cancel")) {
return false;
}
atomicItem.set(content);
return true;
});
waiter.onCancelled((type) -> {
event.replySuccess("Cancelled").queue();
future.complete(false);
});
waiter.onTimeout(() -> {
event.reply("Response timed out :stopwatch:").queue();
future.complete(false);
});
waiter.onSuccess(e -> future.complete(true));
waiter.start();
});
return future;
}).thenAccept(success -> {
if (!success) {
return;
}
TextChannel channelFuture = atomicChannel.get();
int winnersFuture = atomicWinners.get();
long durationFuture = atomicDuration.get().toSeconds();
String itemFuture = atomicItem.get();
channelFuture.sendMessageEmbeds(this.getEmbed(winnersFuture, durationFuture, itemFuture)).queue(message -> {
message.addReaction("🎉").queue();
Document data = new Document("messageId", message.getIdLong()).append("channelId", channelFuture.getIdLong()).append("guildId", event.getGuild().getIdLong()).append("winnersAmount", winnersFuture).append("endAt", Clock.systemUTC().instant().getEpochSecond() + durationFuture).append("duration", durationFuture).append("item", itemFuture);
event.getMongo().insertGiveaway(data).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.getBot().getGiveawayManager().putGiveaway(data, durationFuture);
event.reply("Your giveaway has been created in " + channelFuture.getAsMention() + " :tada:").queue();
});
});
});
}
Aggregations