use of com.sx4.bot.annotations.command.BotPermissions 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.annotations.command.BotPermissions in project Sx4 by sx4-discord-bot.
the class LoggerCommand method list.
@Command(value = "list", description = "List and get info about loggers in the current server")
@CommandId(458)
@Examples({ "logger list" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void list(Sx4CommandEvent event, @Argument(value = "channel", endless = true, nullDefault = true) BaseGuildMessageChannel channel) {
Bson filter = channel == null ? Filters.eq("guildId", event.getGuild().getIdLong()) : Filters.eq("channelId", channel.getIdLong());
List<Document> loggers = event.getMongo().getLoggers(filter, MongoDatabase.EMPTY_DOCUMENT).into(new ArrayList<>());
if (loggers.isEmpty()) {
event.replyFailure(channel == null ? "There are not any loggers setup" : "There is not a logger setup in " + channel.getAsMention()).queue();
return;
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), loggers).setAuthor("Loggers", null, event.getGuild().getIconUrl()).setAutoSelect(true).setDisplayFunction(data -> "<#" + data.getLong("channelId") + ">");
paged.onSelect(select -> {
Document data = select.getSelected();
EnumSet<LoggerEvent> events = LoggerEvent.getEvents(data.get("events", LoggerEvent.ALL));
PagedResult<LoggerEvent> loggerPaged = new PagedResult<>(event.getBot(), new ArrayList<>(events)).setSelect().setPerPage(20).setCustomFunction(page -> {
EmbedBuilder embed = new EmbedBuilder().setAuthor("Logger Settings", null, event.getGuild().getIconUrl()).setTitle("Page " + page.getPage() + "/" + page.getMaxPage()).setFooter(PagedResult.DEFAULT_FOOTER_TEXT).addField("Status", data.getBoolean("enabled", true) ? "Enabled" : "Disabled", true).addField("Channel", "<#" + data.getLong("channelId") + ">", true);
StringJoiner content = new StringJoiner("\n");
page.forEach((loggerEvent, index) -> content.add(loggerEvent.name()));
embed.addField("Enabled Events", content.toString(), false);
return new MessageBuilder().setEmbeds(embed.build());
});
loggerPaged.execute(event);
});
paged.execute(event);
}
use of com.sx4.bot.annotations.command.BotPermissions in project Sx4 by sx4-discord-bot.
the class WelcomerCommand method formatters.
@Command(value = "formatters", aliases = { "format", "formatting" }, description = "Get all the formatters for welcomer you can use")
@CommandId(441)
@Examples({ "welcomer formatters" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void formatters(Sx4CommandEvent event) {
EmbedBuilder embed = new EmbedBuilder().setAuthor("Welcomer Formatters", null, event.getSelfUser().getEffectiveAvatarUrl());
FormatterManager manager = FormatterManager.getDefaultManager();
StringJoiner content = new StringJoiner("\n");
for (FormatterVariable<?> variable : manager.getVariables(User.class)) {
content.add("`{user." + variable.getName() + "}` - " + variable.getDescription());
}
for (FormatterVariable<?> variable : manager.getVariables(Member.class)) {
content.add("`{member." + variable.getName() + "}` - " + variable.getDescription());
}
for (FormatterVariable<?> variable : manager.getVariables(Guild.class)) {
content.add("`{server." + variable.getName() + "}` - " + variable.getDescription());
}
for (FormatterVariable<?> variable : manager.getVariables(OffsetDateTime.class)) {
content.add("`{now." + variable.getName() + "}` - " + variable.getDescription());
}
content.add("`{user.age}` - Gets the age of a user as a string");
embed.setDescription(content.toString());
event.reply(embed.build()).queue();
}
use of com.sx4.bot.annotations.command.BotPermissions 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.BotPermissions in project Sx4 by sx4-discord-bot.
the class SteamCommand method inventory.
@Command(value = "inventory", description = "Look at your steam inventory for a game")
@CommandId(505)
@Examples({ "steam inventory Intruder", "steam inventory Counter-Strike" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void inventory(Sx4CommandEvent event, @Argument(value = "game", endless = true) String query) {
SteamGameCache cache = event.getBot().getSteamGameCache();
if (cache.getGames().isEmpty()) {
event.replyFailure("The steam cache is currently empty, try again").queue();
return;
}
Matcher urlMatcher;
List<Document> games;
if (NumberUtility.isNumberUnsigned(query)) {
games = List.of(new Document("appid", Integer.parseInt(query)));
} else if ((urlMatcher = this.gamePattern.matcher(query)).matches()) {
games = List.of(new Document("appid", Integer.parseInt(urlMatcher.group(1))));
} else {
games = cache.getGames(query);
if (games.isEmpty()) {
event.replyFailure("I could not find any games with that query").queue();
return;
}
}
PagedResult<Document> gamePaged = new PagedResult<>(event.getBot(), games).setAuthor("Steam Search", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setIncreasedIndex(true).setAutoSelect(true).setTimeout(60).setDisplayFunction(game -> game.getString("name"));
gamePaged.onSelect(gameSelect -> {
int game = gameSelect.getSelected().getInteger("appid");
List<Document> connections = event.getMongo().getUserById(event.getAuthor().getIdLong(), Projections.include("connections.steam")).getEmbedded(List.of("connections", "steam"), Collections.emptyList());
if (connections.isEmpty()) {
event.replyFailure("You do not have a steam account linked, use `steam connect` to link an account or provide an argument to search").queue();
return;
}
List<Document> profiles = connections.stream().map(data -> data.append("url", "https://steamcommunity.com/profiles/" + data.getLong("id") + "/")).collect(Collectors.toList());
PagedResult<Document> profilePaged = new PagedResult<>(event.getBot(), profiles).setAutoSelect(true).setAuthor("Steam Profiles", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setDisplayFunction(data -> "[" + data.getString("name") + "](" + data.getString("url") + ")");
profilePaged.onSelect(profileSelect -> {
long id = profileSelect.getSelected().getLong("id");
Request request = new Request.Builder().url("https://steamcommunity.com/inventory/" + id + "/" + game + "/2?l=english&count=5000").build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
String body = response.body().string();
if (body.equals("null")) {
event.replyFailure("Your inventory is set to private").queue();
return;
}
Document json = Document.parse(body);
if (json.containsKey("error")) {
event.replyFailure("That game does not have inventory items").queue();
return;
}
int totalCount = json.getInteger("total_inventory_count");
if (totalCount == 0) {
event.replyFailure("You do not have any inventory items for this game").queue();
return;
}
List<Document> items = json.getList("descriptions", Document.class);
List<Document> assets = json.getList("assets", Document.class);
PagedResult<Document> itemPaged = new PagedResult<>(event.getBot(), items).setSelect().setPerPage(1).cachePages(true).setAsyncFunction((page, message) -> {
EmbedBuilder embed = new EmbedBuilder();
embed.setFooter("Item " + page.getPage() + "/" + page.getMaxPage());
page.forEach((item, index) -> {
Document asset = assets.stream().filter(d -> d.getString("classid").equals(item.getString("classid"))).findFirst().orElse(null);
List<Document> descriptions = item.getList("descriptions", Document.class);
StringJoiner joiner = new StringJoiner("\n");
for (Document description : descriptions) {
String value = description.getString("value");
if (value.isBlank()) {
continue;
}
Element element = Jsoup.parse(value.replace("*", "\\*"));
for (Element italicElement : element.getElementsByTag("i")) {
italicElement.replaceWith(new TextNode("*" + italicElement.text() + "*"));
}
for (Element boldElement : element.getElementsByTag("b")) {
boldElement.replaceWith(new TextNode("**" + boldElement.text() + "**"));
}
joiner.add(element.text());
}
String inspect = item.getList("actions", Document.class, Collections.emptyList()).stream().filter(d -> d.getString("name").equals("Inspect in Game...")).map(d -> d.getString("link")).findFirst().orElse(null);
embed.setDescription(joiner.toString());
embed.setTitle(item.getString("market_name"), "https://steamcommunity.com/profiles/" + id + "/inventory/#" + game + (asset == null ? "" : "_2_" + asset.getString("assetid")));
embed.setImage("https://community.cloudflare.steamstatic.com/economy/image/" + item.getString("icon_url"));
if (inspect != null) {
embed.addField("Inspect In Game", "<" + inspect + ">", false);
}
Request itemRequest = new Request.Builder().url("https://steamcommunity.com/market/priceoverview/?appid=" + game + "¤cy=2&market_hash_name=" + URLEncoder.encode(item.getString("market_hash_name"), StandardCharsets.UTF_8)).build();
event.getHttpClient().newCall(itemRequest).enqueue((HttpCallback) itemResponse -> {
String itemBody = itemResponse.body().string();
if (itemBody.equals("null")) {
message.accept(new MessageBuilder().setEmbeds(embed.build()));
return;
}
Document priceData = Document.parse(itemBody);
if (priceData.getBoolean("success") && priceData.containsKey("lowest_price")) {
embed.addField("Lowest Price", priceData.getString("lowest_price"), false);
}
message.accept(new MessageBuilder().setEmbeds(embed.build()));
});
});
});
itemPaged.execute(event);
});
});
profilePaged.execute(event);
});
gamePaged.execute(event);
}
Aggregations