use of net.kodehawa.mantarobot.core.modules.commands.SubCommand in project MantaroBot by Mantaro.
the class GameCmds method game.
@Subscribe
public void game(CommandRegistry cr) {
final NewRateLimiter rateLimiter = new NewRateLimiter(Executors.newSingleThreadScheduledExecutor(), 4, 6, TimeUnit.SECONDS, 450, true) {
@Override
protected void onSpamDetected(String key, int times) {
log.warn("[Game] Spam detected for {} ({} times)!", key, times);
}
};
SimpleTreeCommand gameCommand = (SimpleTreeCommand) cr.register("game", new SimpleTreeCommand(Category.GAMES) {
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Guessing games.").addField("Games", "`~>game character` - **Starts an instance of Guess the character (anime)**.\n" + "`~>game pokemon` - **Starts an instance of who's that pokemon?**\n" + "`~>game number` - **Starts an instance of Guess The Number**`\n" + "`~>game lobby` - **Starts a chunk of different games, for example `~>game lobby pokemon, trivia` will start pokemon and then trivia.**\n" + "`~>game multiple` - **Starts multiple instances of one game, for example `~>game multiple trivia 5` will start trivia 5 times.**\n" + "`~>game wins` - **Shows how many times you've won in games**", false).addField("Considerations", "The pokemon guessing game has around *900 different pokemon* to guess, " + "where the anime guessing game has around 60. The number in the number guessing game is a random number between 0 and 150.\n" + "To start multiple trivia sessions please use `~>game trivia multiple`, not `~>trivia multiple`", false).build();
}
}.addSubCommand("character", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
startGame(new Character(), event);
}
}).addSubCommand("pokemon", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
startGame(new Pokemon(), event);
}
}).addSubCommand("number", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
startGame(new GuessTheNumber(), event);
}
}));
gameCommand.setPredicate(event -> Utils.handleDefaultNewRatelimit(rateLimiter, event.getAuthor(), event));
gameCommand.createSubCommandAlias("pokemon", "pokémon");
gameCommand.createSubCommandAlias("number", "guessthatnumber");
gameCommand.addSubCommand("wins", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
Member member = Utils.findMember(event, event.getMember(), content);
if (member == null)
return;
event.getChannel().sendMessage(EmoteReference.POPPER + member.getEffectiveName() + " has won " + MantaroData.db().getPlayer(member).getData().getGamesWon() + " games").queue();
}
});
gameCommand.addSubCommand("lobby", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
if (content.isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You didn't specify anything to play!").queue();
return;
}
// Stripe all mentions from this.
String[] split = mentionPattern.matcher(content).replaceAll("").split(", ");
if (split.length < 1 || split.length == 1) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify two games at least!").queue();
return;
}
LinkedList<Game> gameList = new LinkedList<>();
for (String s : split) {
switch(s.replace(" ", "")) {
case "pokemon":
gameList.add(new Pokemon());
break;
case "trivia":
gameList.add(new Trivia(null));
break;
case "number":
gameList.add(new GuessTheNumber());
break;
case "character":
gameList.add(new Character());
break;
}
}
if (gameList.isEmpty() || gameList.size() == 1) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify two games at least (Valid games: character, pokemon, number, trivia)!").queue();
return;
}
startMultipleGames(gameList, event);
}
});
gameCommand.addSubCommand("multiple", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
String[] values = SPLIT_PATTERN.split(content, 2);
if (values.length < 2) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the game and the number of times to run it").queue();
return;
}
int number;
try {
number = Integer.parseInt(values[1]);
} catch (Exception e) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid number of times!").queue();
return;
}
if (number > 10) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You can only start a maximum of 10 games of the same type at a time!").queue();
return;
}
LinkedList<Game> gameList = new LinkedList<>();
for (int i = 0; i < number; i++) {
switch(values[0].replace(" ", "")) {
case "pokemon":
gameList.add(new Pokemon());
break;
case "trivia":
gameList.add(new Trivia(null));
break;
case "number":
gameList.add(new GuessTheNumber());
break;
case "character":
gameList.add(new Character());
break;
}
}
if (gameList.isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a valid game! (Valid games: character, pokemon, number, trivia)").queue();
return;
}
startMultipleGames(gameList, event);
}
});
}
use of net.kodehawa.mantarobot.core.modules.commands.SubCommand 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();
}
});
}
use of net.kodehawa.mantarobot.core.modules.commands.SubCommand in project MantaroBot by Mantaro.
the class MoneyCmds method richest.
@Subscribe
public void richest(CommandRegistry cr) {
final RateLimiter rateLimiter = new RateLimiter(TimeUnit.SECONDS, 10);
final String pattern = ":g$";
ITreeCommand leaderboards = (ITreeCommand) cr.register("leaderboard", new TreeCommand(Category.CURRENCY) {
@Override
public Command defaultTrigger(GuildMessageReceivedEvent event, String mainCommand, String commandName) {
return new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
return;
OrderBy template = r.table("players").orderBy().optArg("index", r.desc("money"));
Cursor<Map> c1 = getGlobalRichest(template, pattern);
List<Map> c = c1.toList();
c1.close();
event.getChannel().sendMessage(baseEmbed(event, "Money leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), map.get("money").toString())).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - $%s", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
}
};
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Leaderboard").setDescription("**Returns the leaderboard.**").addField("Usage", "`~>leaderboard` - **Returns the money leaderboard.**\n" + "`~>leaderboard rep` - **Returns the reputation leaderboard.**\n" + "`~>leaderboard lvl` - **Returns the level leaderboard.**\n" + "~>leaderboard streak - **Returns the daily streak leaderboard.", false).build();
}
});
leaderboards.addSubCommand("lvl", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
return;
Cursor<Map> m;
try (Connection conn = Utils.newDbConnection()) {
m = r.table("players").orderBy().optArg("index", r.desc("level")).filter(player -> player.g("id").match(pattern)).map(player -> player.pluck("id", "level", r.hashMap("data", "experience"))).limit(10).run(conn, OptArgs.of("read_mode", "outdated"));
}
List<Map> c = m.toList();
m.close();
event.getChannel().sendMessage(baseEmbed(event, "Level leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), map.get("level").toString() + "\n - Experience: **" + ((Map) map.get("data")).get("experience") + "**")).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - %s", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
}
});
leaderboards.addSubCommand("rep", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
Cursor<Map> m;
try (Connection conn = Utils.newDbConnection()) {
m = r.table("players").orderBy().optArg("index", r.desc("reputation")).filter(player -> player.g("id").match(pattern)).map(player -> player.pluck("id", "reputation")).limit(10).run(conn, OptArgs.of("read_mode", "outdated"));
}
List<Map> c = m.toList();
m.close();
event.getChannel().sendMessage(baseEmbed(event, "Reputation leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), map.get("reputation").toString())).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - %s", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
}
});
leaderboards.addSubCommand("streak", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
Cursor<Map> m;
try (Connection conn = Utils.newDbConnection()) {
m = r.table("players").orderBy().optArg("index", r.desc("userDailyStreak")).filter(player -> player.g("id").match(pattern)).map(player -> player.pluck("id", r.hashMap("data", "dailyStrike"))).limit(10).run(conn, OptArgs.of("read_mode", "outdated"));
}
List<Map> c = m.toList();
m.close();
event.getChannel().sendMessage(baseEmbed(event, "Daily streak leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), ((HashMap) (map.get("data"))).get("dailyStrike").toString())).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - %sx", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
}
});
// TODO enable in 4.9
/*
leaderboards.addSubCommand("localxp", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
List<Map> l;
try(Connection conn = Utils.newDbConnection()) {
l = r.table("guilds")
.get(event.getGuild().getId())
.getField("data")
.getField("localPlayerExperience")
.run(conn, OptArgs.of("read_mode", "outdated"));
}
l.sort(Comparator.<Map>comparingLong(o -> (long) o.get("experience")).reversed());
event.getChannel().sendMessage(
baseEmbed(event,
"Local level leaderboard", event.getJDA().getSelfUser().getEffectiveAvatarUrl()
).setDescription(l.stream()
.map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("userId").toString()), map.get("level").toString() +
"\n - Experience: **" + map.get("experience") + "**\n"))
.map(p -> String.format("%s**%s** - %s", EmoteReference.MARKER,
p == null ? "User left guild" : p.getKey().getName() + "#" + p.getKey().getDiscriminator(), p.getValue()))
.collect(Collectors.joining("\n"))
).build()
).queue();
}
});
leaderboards.createSubCommandAlias("localxp", "local");
*/
leaderboards.createSubCommandAlias("rep", "reputation");
leaderboards.createSubCommandAlias("lvl", "level");
leaderboards.createSubCommandAlias("streak", "daily");
cr.registerAlias("leaderboard", "richest");
}
use of net.kodehawa.mantarobot.core.modules.commands.SubCommand in project MantaroBot by Mantaro.
the class OsuStatsCmd method osustats.
@Subscribe
public void osustats(CommandRegistry cr) {
ITreeCommand osuCommand = (SimpleTreeCommand) cr.register("osustats", new SimpleTreeCommand(Category.GAMES) {
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "osu! command").setDescription("**Retrieves information from osu! (Players and scores)**.").addField("Usage", "`~>osu best <player>` - **Retrieves best scores of the user specified in the specified game mode**.\n" + "`~>osu recent <player>` - **Retrieves recent scores of the user specified in the specified game mode.**\n" + "`~>osu user <player>` - **Retrieves information about a osu! player**.\n", false).addField("Parameters", "`player` - **The osu! player to look info for.**", false).build();
}
});
osuCommand.addSubCommand("best", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
event.getChannel().sendMessage(EmoteReference.STOPWATCH + "Retrieving information from osu! server...").queue(sentMessage -> {
Future<String> task = pool.submit(() -> best(content));
try {
sentMessage.editMessage(task.get(16, TimeUnit.SECONDS)).queue();
} catch (Exception e) {
if (e instanceof TimeoutException) {
task.cancel(true);
sentMessage.editMessage(EmoteReference.ERROR + "The osu! api seems to be taking a nap. Maybe try again later?").queue();
} else {
SentryHelper.captureException("Error retrieving results from osu!API", e, OsuStatsCmd.class);
}
}
});
}
});
osuCommand.addSubCommand("recent", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
event.getChannel().sendMessage(EmoteReference.STOPWATCH + "Retrieving information from server...").queue(sentMessage -> {
Future<String> task = pool.submit(() -> recent(content));
try {
sentMessage.editMessage(task.get(16, TimeUnit.SECONDS)).queue();
} catch (Exception e) {
if (e instanceof TimeoutException) {
task.cancel(true);
sentMessage.editMessage(EmoteReference.ERROR + "The osu! api seems to be taking a nap. Maybe try again later?").queue();
} else
log.warn("Exception thrown while fetching data", e);
}
});
}
});
osuCommand.addSubCommand("user", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
event.getChannel().sendMessage(user(content)).queue();
}
});
cr.registerAlias("osustats", "osu");
}
use of net.kodehawa.mantarobot.core.modules.commands.SubCommand in project MantaroBot by Mantaro.
the class PlayerCmds method badges.
@Subscribe
public void badges(CommandRegistry cr) {
final Random r = new Random();
ITreeCommand badgeCommand = (ITreeCommand) cr.register("badges", new TreeCommand(Category.CURRENCY) {
@Override
public Command defaultTrigger(GuildMessageReceivedEvent event, String mainCommand, String commandName) {
return new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
Map<String, Optional<String>> t = StringUtils.parse(content.isEmpty() ? new String[] {} : content.split("\\s+"));
content = Utils.replaceArguments(t, content, "brief");
Member member = Utils.findMember(event, event.getMember(), content);
if (member == null)
return;
User toLookup = member.getUser();
Player player = MantaroData.db().getPlayer(toLookup);
PlayerData playerData = player.getData();
if (!t.isEmpty() && t.containsKey("brief")) {
event.getChannel().sendMessage(String.format("**%s's badges:**\n%s", member.getEffectiveName(), playerData.getBadges().stream().map(b -> "*" + b.display + "*").collect(Collectors.joining(", ")))).queue();
return;
}
List<Badge> badges = playerData.getBadges();
Collections.sort(badges);
// Show the message that tells the person that they can get a free badge for upvoting mantaro one out of 3 times they use this command.
// The message stops appearing when they upvote.
String toShow = "If you think you got a new badge and it doesn't appear here, please use `~>profile` and then run this command again.\n" + "Use `~>badges info <badge name>` to get more information about a badge.\n" + ((r.nextInt(3) == 0 && !playerData.hasBadge(Badge.UPVOTER) ? "**You can get a free badge for " + "[up-voting Mantaro on discordbots.org](https://discordbots.org/bot/mantaro)!** (It might take some minutes to process)\n\n" : "\n")) + badges.stream().map(badge -> String.format("**%s:** *%s*", badge, badge.description)).collect(Collectors.joining("\n"));
if (toShow.isEmpty())
toShow = "No badges to show (yet!)";
List<String> parts = DiscordUtils.divideString(MessageEmbed.TEXT_MAX_LENGTH, toShow);
DiscordUtils.list(event, 30, false, (current, max) -> new EmbedBuilder().setAuthor("Badges achieved by " + toLookup.getName()).setColor(event.getMember().getColor() == null ? Color.PINK : event.getMember().getColor()).setThumbnail(toLookup.getEffectiveAvatarUrl()), parts);
}
};
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Badge list").setDescription("**Shows your (or another person)'s badges**\n" + "If you want to check out the badges of another person just mention them.\n" + "`~>badges info <name>` - Shows info about a badge.\n" + "You can use `~>badges -brief` to get a brief versions of the badge showcase.").build();
}
});
badgeCommand.addSubCommand("info", new SubCommand() {
@Override
protected void call(GuildMessageReceivedEvent event, String content) {
if (content.isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a badge to see the info of.").queue();
return;
}
Badge badge = Badge.lookupFromString(content);
if (badge == null) {
event.getChannel().sendMessage(EmoteReference.ERROR + "There's no such badge...").queue();
return;
}
Player p = MantaroData.db().getPlayer(event.getAuthor());
Message message = new MessageBuilder().setEmbed(new EmbedBuilder().setAuthor("Badge information for " + badge.display).setDescription(String.join("\n", EmoteReference.BLUE_SMALL_MARKER + "**Name:** " + badge.display, EmoteReference.BLUE_SMALL_MARKER + "**Description:** " + badge.description, EmoteReference.BLUE_SMALL_MARKER + "**Achieved:** " + p.getData().getBadges().stream().anyMatch(b -> b == badge))).setThumbnail("attachment://icon.png").setColor(Color.CYAN).build()).build();
event.getChannel().sendFile(badge.icon, "icon.png", message).queue();
}
});
}
Aggregations