use of net.kodehawa.mantarobot.core.CommandRegistry in project MantaroBot by Mantaro.
the class AnimeCmds method anime.
@Subscribe
public void anime(CommandRegistry cr) {
cr.register("anime", new SimpleCommand(Category.FUN) {
@Override
public void call(GuildMessageReceivedEvent event, String content, String[] args) {
try {
if (content.isEmpty()) {
onHelp(event);
return;
}
String connection = String.format("https://anilist.co/api/anime/search/%1s?access_token=%2s", URLEncoder.encode(content, "UTF-8"), authToken);
String json = Utils.wgetResty(connection, event);
AnimeData[] type = AnimeData.fromJson(json);
if (type.length == 1) {
animeData(event, type[0]);
return;
}
DiscordUtils.selectList(event, type, anime -> String.format("**[%s (%s)](%s)**", anime.getTitleEnglish(), anime.getTitleJapanese(), "http://anilist.co/anime/" + anime.getId()), s -> baseEmbed(event, "Type the number of the anime you want to select.").setDescription(s).setThumbnail("https://anilist.co/img/logo_al.png").setFooter("Information provided by Anilist. Type &cancel to cancel.", event.getAuthor().getAvatarUrl()).build(), anime -> animeData(event, anime));
} catch (JsonSyntaxException jsonException) {
event.getChannel().sendMessage(EmoteReference.ERROR + "No results found...").queue();
} catch (NullPointerException nullException) {
event.getChannel().sendMessage(EmoteReference.ERROR + "We got a wrong API result for this specific search. Maybe try another one?").queue();
} catch (Exception exception) {
event.getChannel().sendMessage(String.format("%s**I swear I didn't drop your favorite anime!**\n We received a ``%s`` while trying to process the command.", EmoteReference.ERROR, exception.getClass().getSimpleName())).queue();
}
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Anime command").setDescription("**Get anime info from AniList (For anime characters use ~>character).**").addField("Usage", "`~>anime <animename>` - **Retrieve information of an anime based on the name.**", false).addField("Parameters", "`animename` - **The name of the anime you are looking for. Keep queries similar to their english names!**", false).setColor(Color.PINK).build();
}
});
cr.registerAlias("anime", "animu");
}
use of net.kodehawa.mantarobot.core.CommandRegistry in project MantaroBot by Mantaro.
the class AnimeCmds method character.
@Subscribe
public void character(CommandRegistry cr) {
cr.register("character", new SimpleCommand(Category.FUN) {
@Override
public void call(GuildMessageReceivedEvent event, String content, String[] args) {
try {
if (content.isEmpty()) {
onHelp(event);
return;
}
String url = String.format("https://anilist.co/api/character/search/%1s?access_token=%2s", URLEncoder.encode(content, "UTF-8"), authToken);
String json = Utils.wgetResty(url, event);
CharacterData[] character = CharacterData.fromJson(json);
if (character.length == 1) {
characterData(event, character[0]);
return;
}
DiscordUtils.selectList(event, character, character1 -> String.format("**[%s %s](%s)**", character1.getLastName() == null ? "" : character1.getLastName(), character1.getFirstName(), "http://anilist.co/character/" + character1.getId()), s -> baseEmbed(event, "Type the number of the character you want to select.").setDescription(s).setThumbnail("https://anilist.co/img/logo_al.png").setFooter("Information provided by Anilist. Type &cancel to cancel.", event.getAuthor().getAvatarUrl()).build(), character1 -> characterData(event, character1));
} catch (JsonSyntaxException jsonException) {
event.getChannel().sendMessage(EmoteReference.ERROR + "No results found...").queue();
} catch (NullPointerException nullException) {
event.getChannel().sendMessage(EmoteReference.ERROR + "We got a wrong API result for this specific search. Maybe try another one?").queue();
} catch (Exception exception) {
event.getChannel().sendMessage(String.format("%s**I swear I didn't d-drop your waifu, please forgive me!**\nI got ``%s`` while trying to process this command.", EmoteReference.ERROR, exception.getClass().getSimpleName())).queue();
}
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Character command").setDescription("**Get character info from AniList (For anime use `~>anime`).**").addField("Usage", "`~>character <name>` - **Retrieve information of a charactrer based on the name.**", false).addField("Parameters", "`name` - **The name of the character you are looking for. Keep queries similar to their romanji names!**", false).setColor(Color.PINK).build();
}
});
cr.registerAlias("character", "char");
}
use of net.kodehawa.mantarobot.core.CommandRegistry in project MantaroBot by Mantaro.
the class CustomCmds method custom.
@Subscribe
public void custom(CommandRegistry cr) {
String any = "[\\d\\D]*?";
cr.register("custom", new SimpleCommand(Category.UTILS) {
@Override
public void call(GuildMessageReceivedEvent event, String content, String[] args) {
if (args.length < 1) {
onHelp(event);
return;
}
String action = args[0];
if (action.equals("list") || action.equals("ls")) {
if (!MantaroCore.hasLoadedCompletely()) {
event.getChannel().sendMessage("The bot hasn't been fully booted up yet... custom commands will be available shortly!").queue();
return;
}
String filter = event.getGuild().getId() + ":";
List<String> commands = customCommands.keySet().stream().filter(s -> s.startsWith(filter)).map(s -> s.substring(filter.length())).collect(Collectors.toList());
EmbedBuilder builder = new EmbedBuilder().setAuthor("Commands for this guild", null, event.getGuild().getIconUrl()).setColor(event.getMember().getColor());
builder.setDescription(commands.isEmpty() ? "There is nothing here, just dust." : checkString(forType(commands)));
event.getChannel().sendMessage(builder.build()).queue();
return;
}
if (action.equals("view")) {
if (args.length < 2) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the command and the response number!").queue();
return;
}
String cmd = args[1];
CustomCommand command = db().getCustomCommand(event.getGuild(), cmd);
if (command == null) {
event.getChannel().sendMessage(EmoteReference.ERROR + "There isn't a custom command with that name here!").queue();
return;
}
int number;
try {
number = Integer.parseInt(args[2]) - 1;
} catch (NumberFormatException e) {
event.getChannel().sendMessage(EmoteReference.ERROR + "That's not a number...").queue();
return;
}
if (command.getValues().size() < number) {
event.getChannel().sendMessage(EmoteReference.ERROR + "This commands has less responses than the number you specified...").queue();
return;
}
event.getChannel().sendMessage(String.format("**Response `%d` for custom command `%s`:** \n```\n%s```", (number + 1), command.getName(), command.getValues().get(number))).queue();
return;
}
if (action.equals("raw")) {
if (args.length < 2) {
onHelp(event);
return;
}
String cmd = args[1];
if (!NAME_PATTERN.matcher(cmd).matches()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
return;
}
CustomCommand custom = db().getCustomCommand(event.getGuild(), cmd);
if (custom == null) {
event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
return;
}
Pair<String, Integer> pair = DiscordUtils.embedList(custom.getValues(), Object::toString);
String pasted = null;
if (pair.getRight() < custom.getValues().size()) {
AtomicInteger i = new AtomicInteger();
pasted = Utils.paste(custom.getValues().stream().map(s -> i.incrementAndGet() + s).collect(Collectors.joining("\n")));
}
EmbedBuilder embed = baseEmbed(event, "Command \"" + cmd + "\":").setDescription(pair.getLeft()).setFooter("(Showing " + pair.getRight() + " responses of " + custom.getValues().size() + ")", null);
if (pasted != null && pasted.contains("hastebin.com")) {
embed.addField("Pasted content", pasted, false);
}
event.getChannel().sendMessage(embed.build()).queue();
return;
}
if (db().getGuild(event.getGuild()).getData().isCustomAdminLock() && !CommandPermission.ADMIN.test(event.getMember())) {
event.getChannel().sendMessage("This guild only accepts custom command creation, edits, imports and eval from administrators.").queue();
return;
}
if (action.equals("clear")) {
if (!CommandPermission.ADMIN.test(event.getMember())) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot do that, silly.").queue();
return;
}
List<CustomCommand> customCommands = db().getCustomCommands(event.getGuild());
if (customCommands.isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "There's no Custom Commands registered in this Guild, just dust.").queue();
}
int size = customCommands.size();
customCommands.forEach(CustomCommand::deleteAsync);
customCommands.forEach(c -> CustomCmds.customCommands.remove(c.getId()));
event.getChannel().sendMessage(EmoteReference.PENCIL + "Cleared **" + size + " Custom Commands**!").queue();
return;
}
if (args.length < 2) {
onHelp(event);
return;
}
String cmd = args[1];
if (action.equals("make")) {
if (!NAME_PATTERN.matcher(cmd).matches()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
return;
}
List<String> responses = new ArrayList<>();
boolean created = InteractiveOperations.create(event.getChannel(), 60, e -> {
if (!e.getAuthor().equals(event.getAuthor()))
return Operation.IGNORED;
String c = e.getMessage().getContentRaw();
if (!c.startsWith("&"))
return Operation.IGNORED;
c = c.substring(1);
if (c.startsWith("~>cancel") || c.startsWith("~>stop")) {
event.getChannel().sendMessage(EmoteReference.CORRECT + "Command Creation canceled.").queue();
return Operation.COMPLETED;
}
if (c.startsWith("~>save")) {
String arg = c.substring(6).trim();
String saveTo = !arg.isEmpty() ? arg : cmd;
if (!NAME_PATTERN.matcher(cmd).matches()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
return Operation.RESET_TIMEOUT;
}
if (cmd.length() >= 100) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Name is too long.").queue();
return Operation.RESET_TIMEOUT;
}
if (DefaultCommandProcessor.REGISTRY.commands().containsKey(saveTo) && !DefaultCommandProcessor.REGISTRY.commands().get(saveTo).equals(customCommand)) {
event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
return Operation.RESET_TIMEOUT;
}
if (responses.isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "No responses were added. Stopping creation without saving...").queue();
} else {
CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmd, responses);
// save at DB
custom.saveAsync();
// reflect at local
customCommands.put(custom.getId(), custom.getValues());
// add mini-hack
DefaultCommandProcessor.REGISTRY.commands().put(cmd, customCommand);
event.getChannel().sendMessage(EmoteReference.CORRECT + "Saved to command ``" + cmd + "``!").queue();
// easter egg :D
TextChannelGround.of(event).dropItemWithChance(8, 2);
}
return Operation.COMPLETED;
}
responses.add(c.replace("@everyone", "[nice meme]").replace("@here", "[you tried]"));
e.getMessage().addReaction(EmoteReference.CORRECT.getUnicode()).queue();
return Operation.RESET_TIMEOUT;
}) != null;
if (created) {
event.getChannel().sendMessage(EmoteReference.PENCIL + "Started **\"Creation of Custom Command ``" + cmd + "``\"**!\nSend ``&~>stop`` to stop creation **without saving**.\nSend ``&~>save`` to stop creation an **save the new Command**. Send any text beginning with ``&`` to be added to the Command Responses.\nThis Interactive Operation ends without saving after 60 seconds of inactivity.").queue();
} else {
event.getChannel().sendMessage(EmoteReference.ERROR + "There's already an Interactive Operation happening on this channel.").queue();
}
return;
}
if (action.equals("eval")) {
try {
runCustom(content.replace("eval ", ""), event);
} catch (Exception e) {
event.getChannel().sendMessage(EmoteReference.ERROR + "There was an error while evaluating your command!" + (e.getMessage() == null ? "" : " (E: " + e.getMessage() + ")")).queue();
}
return;
}
if (action.equals("remove") || action.equals("rm")) {
if (!NAME_PATTERN.matcher(cmd).matches()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
return;
}
CustomCommand custom = db().getCustomCommand(event.getGuild(), cmd);
if (custom == null) {
event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
return;
}
// delete at DB
custom.deleteAsync();
// reflect at local
customCommands.remove(custom.getId());
// clear commands if none
if (customCommands.keySet().stream().noneMatch(s -> s.endsWith(":" + cmd)))
DefaultCommandProcessor.REGISTRY.commands().remove(cmd);
event.getChannel().sendMessage(EmoteReference.PENCIL + "Removed Custom Command ``" + cmd + "``!").queue();
return;
}
if (action.equals("import")) {
if (!NAME_WILDCARD_PATTERN.matcher(cmd).matches()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
return;
}
Map<String, Guild> mapped = MantaroBot.getInstance().getMutualGuilds(event.getAuthor()).stream().collect(Collectors.toMap(ISnowflake::getId, g -> g));
List<Pair<Guild, CustomCommand>> filtered = MantaroData.db().getCustomCommandsByName(("*" + cmd + "*").replace("*", any)).stream().map(customCommand -> {
Guild guild = mapped.get(customCommand.getGuildId());
return guild == null ? null : Pair.of(guild, customCommand);
}).filter(Objects::nonNull).collect(Collectors.toList());
if (filtered.size() == 0) {
event.getChannel().sendMessage(EmoteReference.ERROR + "There are no custom commands matching your search query.").queue();
return;
}
DiscordUtils.selectList(event, filtered, pair -> "``" + pair.getValue().getName() + "`` - Guild: ``" + pair.getKey() + "``", s -> baseEmbed(event, "Select the Command:").setDescription(s).setFooter("(You can only select custom commands from guilds that you are a member of)", null).build(), pair -> {
String cmdName = pair.getValue().getName();
List<String> responses = pair.getValue().getValues();
CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmdName, responses);
// save at DB
custom.saveAsync();
// reflect at local
customCommands.put(custom.getId(), custom.getValues());
event.getChannel().sendMessage(String.format("Imported custom command ``%s`` from guild `%s` with responses ``%s``", cmdName, pair.getKey().getName(), String.join("``, ``", responses))).queue();
// easter egg :D
TextChannelGround.of(event).dropItemWithChance(8, 2);
});
return;
}
if (args.length < 3) {
onHelp(event);
return;
}
String value = args[2];
if (action.equals("edit")) {
CustomCommand custom = db().getCustomCommand(event.getGuild(), cmd);
if (custom == null) {
event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
return;
}
String[] vals = StringUtils.splitArgs(value, 2);
int where;
try {
where = Math.abs(Integer.parseInt(vals[0]));
} catch (NumberFormatException e) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a correct number to change!").queue();
return;
}
List<String> values = custom.getValues();
if (where - 1 > values.size()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot edit a non-existent index!").queue();
return;
}
if (vals[1].isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot edit to an empty response!").queue();
return;
}
custom.getValues().set(where - 1, vals[1]);
custom.saveAsync();
customCommands.put(custom.getId(), custom.getValues());
event.getChannel().sendMessage(EmoteReference.CORRECT + "Edited response **#" + where + "** of the command `" + custom.getName() + "` correctly!").queue();
return;
}
if (action.equals("rename")) {
if (!NAME_PATTERN.matcher(cmd).matches() || !NAME_PATTERN.matcher(value).matches()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
return;
}
if (DefaultCommandProcessor.REGISTRY.commands().containsKey(value) && !DefaultCommandProcessor.REGISTRY.commands().get(value).equals(customCommand)) {
event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
return;
}
CustomCommand oldCustom = db().getCustomCommand(event.getGuild(), cmd);
if (oldCustom == null) {
event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
return;
}
CustomCommand newCustom = CustomCommand.of(event.getGuild().getId(), value, oldCustom.getValues());
// change at DB
oldCustom.deleteAsync();
newCustom.saveAsync();
// reflect at local
customCommands.remove(oldCustom.getId());
customCommands.put(newCustom.getId(), newCustom.getValues());
// add mini-hack
DefaultCommandProcessor.REGISTRY.commands().put(value, customCommand);
// clear commands if none
if (customCommands.keySet().stream().noneMatch(s -> s.endsWith(":" + cmd)))
DefaultCommandProcessor.REGISTRY.commands().remove(cmd);
event.getChannel().sendMessage(EmoteReference.CORRECT + "Renamed command ``" + cmd + "`` to ``" + value + "``!").queue();
// easter egg :D
TextChannelGround.of(event).dropItemWithChance(8, 2);
return;
}
if (action.equals("add") || action.equals("new")) {
if (!NAME_PATTERN.matcher(cmd).matches()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
return;
}
if (cmd.length() >= 100) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Name is too long.").queue();
return;
}
if (DefaultCommandProcessor.REGISTRY.commands().containsKey(cmd) && !DefaultCommandProcessor.REGISTRY.commands().get(cmd).equals(customCommand)) {
event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
return;
}
CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmd, Collections.singletonList(value.replace("@everyone", "[nice meme]").replace("@here", "[you tried]")));
if (action.equals("add")) {
CustomCommand c = db().getCustomCommand(event, cmd);
if (c != null)
custom.getValues().addAll(c.getValues());
}
// save at DB
custom.saveAsync();
// reflect at local
customCommands.put(custom.getId(), custom.getValues());
// add mini-hack
DefaultCommandProcessor.REGISTRY.commands().put(cmd, customCommand);
event.getChannel().sendMessage(EmoteReference.CORRECT + "Saved to command ``" + cmd + "``!").queue();
// easter egg :D
TextChannelGround.of(event).dropItemWithChance(8, 2);
return;
}
onHelp(event);
}
@Override
public String[] splitArgs(String content) {
return SPLIT_PATTERN.split(content, 3);
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "CustomCommand Manager").setDescription("**Manages the Custom Commands of the Guild.**").addField("Guide", "https://github.com/Mantaro/MantaroBot/wiki/Custom-Commands", false).addField("Usage:", "`~>custom` - Shows this help\n" + "`~>custom <list|ls>` - **List all commands. If detailed is supplied, it prints the responses of each command.**\n" + "`~>custom clear` - **Remove all Custom Commands from this Guild. (ADMIN-ONLY)**\n" + "`~>custom add <name> <response>` - **Creates or adds the response provided to a custom command.**\n" + "`~>custom make <name>` - **Starts a Interactive Operation to create a command with the specified name.**\n" + "`~>custom <remove|rm> <name>` - **Removes a command with an specific name.**\n" + "`~>custom import <search>` - **Imports a command from another guild you're in.**\n" + "`~>custom eval <response>` - **Tests how a custom command response will look**\n" + "`~>custom edit <name> <response number> <new content>` - **Edits one response of the specified command**\n" + "`~>custom view <name> <response number>` - **Views the content of one response**\n" + "`~>custom rename <previous name> <new name>` - **Renames a custom command**", false).addField("Considerations", "If you wish to dissallow normal people from making custom commands, run `~>opts admincustom true`", false).build();
}
});
}
use of net.kodehawa.mantarobot.core.CommandRegistry in project MantaroBot by Mantaro.
the class InfoCmds method guildinfo.
@Subscribe
public void guildinfo(CommandRegistry cr) {
cr.register("serverinfo", new SimpleCommand(Category.INFO) {
@Override
protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
Guild guild = event.getGuild();
TextChannel channel = event.getChannel();
String roles = guild.getRoles().stream().filter(role -> !guild.getPublicRole().equals(role)).map(Role::getName).collect(Collectors.joining(", "));
if (roles.length() > 1024)
roles = roles.substring(0, 1024 - 4) + "...";
channel.sendMessage(new EmbedBuilder().setAuthor("Server Information", null, guild.getIconUrl()).setColor(guild.getOwner().getColor() == null ? Color.ORANGE : guild.getOwner().getColor()).setDescription("Server information for " + guild.getName()).setThumbnail(guild.getIconUrl()).addField("Users (Online/Unique)", (int) guild.getMembers().stream().filter(u -> !u.getOnlineStatus().equals(OnlineStatus.OFFLINE)).count() + "/" + guild.getMembers().size(), true).addField("Creation Date", guild.getCreationTime().format(DateTimeFormatter.ISO_DATE_TIME).replaceAll("[^0-9.:-]", " "), true).addField("Voice/Text Channels", guild.getVoiceChannels().size() + "/" + guild.getTextChannels().size(), true).addField("Owner", guild.getOwner().getUser().getName() + "#" + guild.getOwner().getUser().getDiscriminator(), true).addField("Region", guild.getRegion() == null ? "Unknown." : guild.getRegion().getName(), true).addField("Roles (" + guild.getRoles().size() + ")", roles, false).setFooter("Server ID: " + String.valueOf(guild.getId()), null).build()).queue();
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Server Info Command").setDescription("**See your server's current stats.**").setColor(event.getGuild().getOwner().getColor() == null ? Color.ORANGE : event.getGuild().getOwner().getColor()).build();
}
});
cr.registerAlias("serverinfo", "guildinfo");
}
use of net.kodehawa.mantarobot.core.CommandRegistry in project MantaroBot by Mantaro.
the class InfoCmds method stats.
@Subscribe
public void stats(CommandRegistry cr) {
TreeCommand statsCommand = (TreeCommand) cr.register("stats", new TreeCommand(Category.INFO) {
@Override
public Command defaultTrigger(GuildMessageReceivedEvent event, String currentCommand, String attemptedCommand) {
return new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
if (content.isEmpty()) {
event.getChannel().sendMessage(EmoteReference.MEGA + "**[Stats]** Y-Yeah... gathering them, hold on for a bit...").queue(message -> {
GuildStatsManager.MILESTONE = (((int) (MantaroBot.getInstance().getGuildCache().size() + 99) / 100) * 100) + 100;
List<Guild> guilds = MantaroBot.getInstance().getGuilds();
List<VoiceChannel> voiceChannels = MantaroBot.getInstance().getVoiceChannels();
List<VoiceChannel> musicChannels = voiceChannels.parallelStream().filter(vc -> vc.getMembers().contains(vc.getGuild().getSelfMember())).collect(Collectors.toList());
IntSummaryStatistics usersPerGuild = calculateInt(guilds, value -> value.getMembers().size());
IntSummaryStatistics onlineUsersPerGuild = calculateInt(guilds, value -> (int) value.getMembers().stream().filter(member -> !member.getOnlineStatus().equals(OnlineStatus.OFFLINE)).count());
DoubleSummaryStatistics onlineUsersPerUserPerGuild = calculateDouble(guilds, value -> (double) value.getMembers().stream().filter(member -> !member.getOnlineStatus().equals(OnlineStatus.OFFLINE)).count() / (double) value.getMembers().size() * 100);
DoubleSummaryStatistics listeningUsersPerUsersPerGuilds = calculateDouble(musicChannels, value -> (double) value.getMembers().size() / (double) value.getGuild().getMembers().size() * 100);
DoubleSummaryStatistics listeningUsersPerOnlineUsersPerGuilds = calculateDouble(musicChannels, value -> (double) value.getMembers().size() / (double) value.getGuild().getMembers().stream().filter(member -> !member.getOnlineStatus().equals(OnlineStatus.OFFLINE)).count() * 100);
IntSummaryStatistics textChannelsPerGuild = calculateInt(guilds, value -> value.getTextChannels().size());
IntSummaryStatistics voiceChannelsPerGuild = calculateInt(guilds, value -> value.getVoiceChannels().size());
int musicConnections = (int) voiceChannels.stream().filter(voiceChannel -> voiceChannel.getMembers().contains(voiceChannel.getGuild().getSelfMember())).count();
long exclusiveness = MantaroBot.getInstance().getGuildCache().stream().filter(g -> g.getMembers().stream().filter(member -> member.getUser().isBot()).count() == 1).count();
double musicConnectionsPerServer = (double) musicConnections / (double) guilds.size() * 100;
double exclusivenessPercent = (double) exclusiveness / (double) guilds.size() * 100;
long bigGuilds = MantaroBot.getInstance().getGuildCache().stream().filter(g -> g.getMembers().size() > 500).count();
message.editMessage(new EmbedBuilder().setColor(Color.PINK).setAuthor("Mantaro Statistics", "https://github.com/Kodehawa/MantaroBot/", event.getJDA().getSelfUser().getAvatarUrl()).setThumbnail(event.getJDA().getSelfUser().getAvatarUrl()).setDescription("Well... I did my math!").addField("Users per Guild", String.format(Locale.ENGLISH, "Min: %d\nAvg: %.1f\nMax: %d", usersPerGuild.getMin(), usersPerGuild.getAverage(), usersPerGuild.getMax()), true).addField("Online Users per Server", String.format(Locale.ENGLISH, "Min: %d\nAvg: %.1f\nMax: %d", onlineUsersPerGuild.getMin(), onlineUsersPerGuild.getAverage(), onlineUsersPerGuild.getMax()), true).addField("Online Users per Users per Server", String.format(Locale.ENGLISH, "Min: %.1f%%\nAvg: %.1f%%\nMax: %.1f%%", onlineUsersPerUserPerGuild.getMin(), onlineUsersPerUserPerGuild.getAverage(), onlineUsersPerUserPerGuild.getMax()), true).addField("Text Channels per Server", String.format(Locale.ENGLISH, "Min: %d\nAvg: %.1f\nMax: %d", textChannelsPerGuild.getMin(), textChannelsPerGuild.getAverage(), textChannelsPerGuild.getMax()), true).addField("Voice Channels per Server", String.format(Locale.ENGLISH, "Min: %d\nAvg: %.1f\nMax: %d", voiceChannelsPerGuild.getMin(), voiceChannelsPerGuild.getAverage(), voiceChannelsPerGuild.getMax()), true).addField("Music Listeners per Users per Server", String.format(Locale.ENGLISH, "Min: %.1f%%\nAvg: %.1f%%\nMax: %.1f%%", listeningUsersPerUsersPerGuilds.getMin(), listeningUsersPerUsersPerGuilds.getAverage(), listeningUsersPerUsersPerGuilds.getMax()), true).addField("Music Listeners per Online Users per Server", String.format(Locale.ENGLISH, "Min: %.1f%%\nAvg: %.1f%%\nMax: %.1f%%", listeningUsersPerOnlineUsersPerGuilds.getMin(), listeningUsersPerOnlineUsersPerGuilds.getAverage(), listeningUsersPerOnlineUsersPerGuilds.getMax()), true).addField("Music Connections per Server", String.format(Locale.ENGLISH, "%.1f%% (%d Connections)", musicConnectionsPerServer, musicConnections), true).addField("Total queue size", Long.toString(MantaroBot.getInstance().getAudioManager().getTotalQueueSize()), true).addField("Total commands (including custom)", String.valueOf(DefaultCommandProcessor.REGISTRY.commands().size()), true).addField("Exclusiveness in Total Servers", Math.round(exclusivenessPercent) + "% (" + exclusiveness + ")", false).addField("Big Servers", String.valueOf(bigGuilds), true).setFooter("! Guilds to next milestone (" + GuildStatsManager.MILESTONE + "): " + (GuildStatsManager.MILESTONE - MantaroBot.getInstance().getGuildCache().size()), event.getJDA().getSelfUser().getAvatarUrl()).build()).override(true).queue();
TextChannelGround.of(event).dropItemWithChance(4, 5);
});
} else {
onError(event);
}
}
};
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Statistics command").setDescription("**See the bot, usage or vps statistics**").addField("Usage", "`~>stats <usage/server/cmds/guilds>` - **Returns statistical information**", true).build();
}
});
statsCommand.addSubCommand("usage", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Mantaro's usage information", null, "https://puu.sh/sMsVC/576856f52b.png").setDescription("Hardware and usage information.").setThumbnail("https://puu.sh/suxQf/e7625cd3cd.png").addField("Threads:", getThreadCount() + " Threads", true).addField("Memory Usage:", getTotalMemory() - getFreeMemory() + "MB/" + getMaxMemory() + "MB", true).addField("CPU Cores:", getAvailableProcessors() + " Cores", true).addField("CPU Usage:", String.format("%.2f", getVpsCPUUsage()) + "%", true).addField("Assigned Memory:", getTotalMemory() + "MB", true).addField("Remaining from assigned:", getFreeMemory() + "MB", true).build()).queue();
TextChannelGround.of(event).dropItemWithChance(4, 5);
}
});
statsCommand.addSubCommand("server", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
TextChannelGround.of(event).dropItemWithChance(4, 5);
EmbedBuilder embedBuilder = new EmbedBuilder().setAuthor("Mantaro's server usage information", null, "https://puu.sh/sMsVC/576856f52b.png").setThumbnail("https://puu.sh/suxQf/e7625cd3cd.png").addField("CPU Usage", String.format("%.2f", getVpsCPUUsage()) + "%", true).addField("RAM (TOTAL/FREE/USED)", String.format("%.2f", getVpsMaxMemory()) + "GB/" + String.format("%.2f", getVpsFreeMemory()) + "GB/" + String.format("%.2f", getVpsUsedMemory()) + "GB", false);
event.getChannel().sendMessage(embedBuilder.build()).queue();
}
});
statsCommand.addSubCommand("cmds", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
String[] args = content.split(" ");
if (args.length > 0) {
String what = args[0];
if (what.equals("total")) {
event.getChannel().sendMessage(commandStatsManager.fillEmbed(CommandStatsManager.TOTAL_CMDS, baseEmbed(event, "Command Stats | Total")).build()).queue();
return;
}
if (what.equals("daily")) {
event.getChannel().sendMessage(commandStatsManager.fillEmbed(CommandStatsManager.DAY_CMDS, baseEmbed(event, "Command Stats | Daily")).build()).queue();
return;
}
if (what.equals("hourly")) {
event.getChannel().sendMessage(commandStatsManager.fillEmbed(CommandStatsManager.HOUR_CMDS, baseEmbed(event, "Command Stats | Hourly")).build()).queue();
return;
}
if (what.equals("now")) {
event.getChannel().sendMessage(commandStatsManager.fillEmbed(CommandStatsManager.MINUTE_CMDS, baseEmbed(event, "Command Stats | Now")).build()).queue();
return;
}
}
// Default
event.getChannel().sendMessage(baseEmbed(event, "Command Stats").addField("Now", commandStatsManager.resume(CommandStatsManager.MINUTE_CMDS), false).addField("Hourly", commandStatsManager.resume(CommandStatsManager.HOUR_CMDS), false).addField("Daily", commandStatsManager.resume(CommandStatsManager.DAY_CMDS), false).addField("Total", commandStatsManager.resume(CommandStatsManager.TOTAL_CMDS), false).build()).queue();
}
});
statsCommand.addSubCommand("guilds", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
String[] args = content.split(" ");
if (args.length > 0) {
String what = args[0];
if (what.equals("total")) {
event.getChannel().sendMessage(guildStatsManager.fillEmbed(GuildStatsManager.TOTAL_EVENTS, baseEmbed(event, "Guild Stats | Total")).build()).queue();
return;
}
if (what.equals("daily")) {
event.getChannel().sendMessage(guildStatsManager.fillEmbed(GuildStatsManager.DAY_EVENTS, baseEmbed(event, "Guild Stats | Daily")).build()).queue();
return;
}
if (what.equals("hourly")) {
event.getChannel().sendMessage(guildStatsManager.fillEmbed(GuildStatsManager.HOUR_EVENTS, baseEmbed(event, "Guild Stats | Hourly")).build()).queue();
return;
}
if (what.equals("now")) {
event.getChannel().sendMessage(guildStatsManager.fillEmbed(GuildStatsManager.MINUTE_EVENTS, baseEmbed(event, "Guild Stats | Now")).build()).queue();
return;
}
}
// Default
event.getChannel().sendMessage(baseEmbed(event, "Guild Stats").addField("Now", guildStatsManager.resume(GuildStatsManager.MINUTE_EVENTS), false).addField("Hourly", guildStatsManager.resume(GuildStatsManager.HOUR_EVENTS), false).addField("Daily", guildStatsManager.resume(GuildStatsManager.DAY_EVENTS), false).addField("Total", guildStatsManager.resume(GuildStatsManager.TOTAL_EVENTS), false).setFooter("Guilds: " + MantaroBot.getInstance().getGuildCache().size(), null).build()).queue();
}
});
statsCommand.addSubCommand("category", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
String[] args = content.split(" ");
if (args.length > 0) {
String what = args[0];
if (what.equals("total")) {
event.getChannel().sendMessage(categoryStatsManager.fillEmbed(CategoryStatsManager.TOTAL_CATS, baseEmbed(event, "Category Stats | Total")).build()).queue();
return;
}
if (what.equals("daily")) {
event.getChannel().sendMessage(categoryStatsManager.fillEmbed(CategoryStatsManager.DAY_CATS, baseEmbed(event, "Category Stats | Daily")).build()).queue();
return;
}
if (what.equals("hourly")) {
event.getChannel().sendMessage(categoryStatsManager.fillEmbed(CategoryStatsManager.HOUR_CATS, baseEmbed(event, "Category Stats | Hourly")).build()).queue();
return;
}
if (what.equals("now")) {
event.getChannel().sendMessage(categoryStatsManager.fillEmbed(CategoryStatsManager.MINUTE_CATS, baseEmbed(event, "Category Stats | Now")).build()).queue();
return;
}
}
// Default
event.getChannel().sendMessage(baseEmbed(event, "Category Stats").addField("Now", categoryStatsManager.resume(CategoryStatsManager.MINUTE_CATS), false).addField("Hourly", categoryStatsManager.resume(CategoryStatsManager.HOUR_CATS), false).addField("Daily", categoryStatsManager.resume(CategoryStatsManager.DAY_CATS), false).addField("Total", categoryStatsManager.resume(CategoryStatsManager.TOTAL_CATS), false).build()).queue();
}
});
statsCommand.addSubCommand("custom", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
event.getChannel().sendMessage(customCommandStatsManager.fillEmbed(CustomCommandStatsManager.TOTAL_CUSTOM_CMDS, baseEmbed(event, "CCS Stats | Total")).build()).queue();
}
});
statsCommand.addSubCommand("game", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
event.getChannel().sendMessage(baseEmbed(event, "Game Stats").setDescription(gameStatsManager.resume(GameStatsManager.TOTAL_GAMES)).build()).queue();
}
});
}
Aggregations