use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class HotCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "image url", endless = true, acceptEmpty = true) @ImageUrl String imageUrl) {
Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("hot")).addQuery("image", imageUrl).build(event.getConfig().getImageWebserver());
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> ImageUtility.getImageMessage(event, response).queue());
}
use of com.sx4.bot.core.Sx4CommandEvent 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.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class YouTubeCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query, @Option(value = "channel", description = "Only return a channel") boolean channel, @Option(value = "playlist", description = "Only return a playlist") boolean playlist, @Option(value = "video", description = "Only return a video") boolean video) {
String type = channel ? "channel" : video ? "video" : playlist ? "playlist" : null;
Request request = new Request.Builder().url(String.format("https://www.googleapis.com/youtube/v3/search?key=%s&part=snippet&maxResults=50&safeSearch=none&q=%s%s", event.getConfig().getYouTube(), URLEncoder.encode(query, StandardCharsets.UTF_8), type == null ? "" : "&type=" + type)).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document json = Document.parse(response.body().string());
List<Document> items = json.getList("items", Document.class);
if (items.isEmpty()) {
event.replyFailure("I could not find any results").queue();
return;
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), items).setAuthor("YouTube Results", null, "https://media-thumbs.golden.com/4hBhjfnhOC6J3uJZglZG0quRsPU=/200x200/smart/golden-media.s3.amazonaws.com%2Ftopic_images%2F6c3fdb0966b049eba2b9c2331da224f0.png").setAutoSelect(true).setDisplayFunction(data -> {
Document id = data.get("id", Document.class);
String kind = id.getString("kind");
return "[" + data.getEmbedded(List.of("snippet", "title"), String.class) + "](" + this.getUrlFromId(id) + ")" + " (" + StringUtility.title(kind.substring(kind.indexOf('#') + 1)) + ")";
});
paged.onSelect(select -> {
Document result = select.getSelected();
Document id = result.get("id", Document.class);
Document snippet = result.get("snippet", Document.class);
Document thumbnails = snippet.get("thumbnails", Document.class);
ZonedDateTime uploadedAt = ZonedDateTime.parse(snippet.getString("publishedAt"));
EmbedBuilder embed = new EmbedBuilder();
embed.setColor(16711680);
embed.setDescription(snippet.getString("description"));
embed.setImage(thumbnails.getEmbedded(List.of("high", "url"), String.class));
embed.setTitle(snippet.getString("title"), this.getUrlFromId(id));
String kind = id.getString("kind");
if (kind.equals("youtube#channel")) {
embed.addField("Created At", uploadedAt.format(this.formatter), true);
} else if (kind.equals("youtube#video")) {
String state = snippet.getString("liveBroadcastContent");
embed.addField("Uploaded By", "[" + snippet.getString("channelTitle") + "](https://www.youtube.com/channel/" + snippet.getString("channelId") + ")", true);
embed.addField("Uploaded At", uploadedAt.format(this.formatter), true);
embed.addField("State", state.equals("live") ? "Live Now" : state.equals("upcoming") ? "Scheduled" : "Uploaded", true);
Request metaDataRequest = new Request.Builder().url("https://api.jockiemusic.com/v1/youtube/videos/" + id.getString("videoId") + "/metadata").build();
event.reply(embed.build()).queue(message -> {
event.getHttpClient().newCall(metaDataRequest).enqueue((HttpCallback) metaDataResponse -> {
if (metaDataResponse.code() == 404) {
return;
}
Document data = Document.parse(metaDataResponse.body().string()).get("data", Document.class);
Document metaData = data.get("metadata", Document.class);
Document rating = metaData.get("rating", Document.class);
long likes = rating.get("likes", Number.class).longValue(), dislikes = rating.get("dislikes", Number.class).longValue();
double ratingPercent = ((double) likes / (likes + dislikes)) * 100D;
embed.addField("Duration", TimeUtility.getMusicTimeString(metaData.get("length", Number.class).longValue(), TimeUnit.MILLISECONDS), true);
embed.addField("Views", String.format("%,d", metaData.get("views", Number.class).longValue()), true);
embed.addField("Likes/Dislikes", String.format("%,d \\\uD83D\uDC4D\n%,d \\\uD83D\uDC4E", likes, dislikes), true);
embed.addField("Rating", NumberUtility.DEFAULT_DECIMAL_FORMAT.format(ratingPercent) + "%", true);
embed.setFooter("Views and Ratings last updated");
embed.setTimestamp(Instant.ofEpochSecond(data.get("lastUpdated", Number.class).longValue()));
message.editMessageEmbeds(embed.build()).queue();
});
});
return;
} else {
embed.addField("Uploaded By", "[" + snippet.getString("channelTitle") + "](https://www.youtube.com/channel/" + snippet.getString("channelId") + ")", true);
embed.addField("Uploaded At", uploadedAt.format(this.formatter), true);
}
event.reply(embed.build()).queue();
});
paged.execute(event);
});
}
use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class AutoRoleCommand method fix.
@Command(value = "fix", description = "Will give missing members the auto role if needed")
@CommandId(458)
@Examples({ "auto role fix @Role", "auto role fix Role", "auto role fix 406240455622262784" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@BotPermissions(permissions = { Permission.MANAGE_ROLES })
public void fix(Sx4CommandEvent event, @Argument(value = "role", endless = true) Role role) {
Document data = event.getMongo().getAutoRole(Filters.eq("roleId", role.getIdLong()), Projections.include("filters"));
if (data == null) {
event.replyFailure("That role is not an auto role").queue();
return;
}
if (!event.getSelfMember().canInteract(role)) {
event.replyFailure("That auto role is above my top role").queue();
return;
}
List<Document> filters = data.getList("filters", Document.class, Collections.emptyList());
List<Member> members = event.getGuild().getMemberCache().applyStream(stream -> stream.filter(member -> AutoRoleUtility.filtersMatch(member, filters) && !member.getRoles().contains(role) && !member.isPending()).collect(Collectors.toList()));
if (members.size() == 0) {
event.replyFailure("No users currently need that auto role").queue();
return;
}
if (!this.pending.add(event.getGuild().getIdLong())) {
event.replyFailure("You already have an auto role fix in progress").queue();
return;
}
event.replyFormat("Adding %s to **%,d** user%s, another message will be sent once this is done %s", role.getAsMention(), members.size(), members.size() == 1 ? "" : "s", event.getConfig().getSuccessEmote()).queue();
List<CompletableFuture<Integer>> futures = new ArrayList<>();
for (Member member : members) {
futures.add(event.getGuild().addRoleToMember(member, role).submit().handle((result, exception) -> exception == null ? 1 : 0));
}
FutureUtility.allOf(futures).whenComplete((completed, exception) -> {
this.pending.remove(event.getGuild().getIdLong());
int count = completed.stream().reduce(0, Integer::sum);
event.replyFormat("Successfully added the role %s to **%,d/%,d** user%s %s", role.getAsMention(), count, members.size(), count == 1 ? "" : "s", event.getConfig().getSuccessEmote()).queue();
});
}
use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class GiveawayCommand method reroll.
@Command(value = "reroll", aliases = { "re roll" }, description = "Rerolls the winners for an ended giveaway")
@CommandId(49)
@Examples({ "giveaway reroll 727224132202397726" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void reroll(Sx4CommandEvent event, @Argument(value = "message id") MessageArgument messageArgument) {
Document data = event.getMongo().getGiveawayById(messageArgument.getMessageId());
if (data == null) {
event.replyFailure("There is no giveaway with that id").queue();
return;
}
if (!data.containsKey("winners")) {
event.replyFailure("That giveaway has not ended yet").queue();
return;
}
event.getBot().getGiveawayManager().endGiveaway(data, true);
}
Aggregations