use of net.kodehawa.mantarobot.core.CommandRegistry in project MantaroBot by Mantaro.
the class OptsCmd method register.
@Subscribe
public void register(CommandRegistry registry) {
registry.register("opts", optsCmd = new SimpleCommand(Category.MODERATION, CommandPermission.ADMIN) {
@Override
protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
if (args.length == 0) {
OptsCmd.onHelp(event);
return;
}
if (args.length == 1 && args[0].equalsIgnoreCase("list") || args[0].equalsIgnoreCase("ls")) {
StringBuilder builder = new StringBuilder();
for (String s : Option.getAvaliableOptions()) {
builder.append(s).append("\n");
}
List<String> m = DiscordUtils.divideString(builder);
List<String> messages = new LinkedList<>();
boolean hasReactionPerms = event.getGuild().getSelfMember().hasPermission(event.getChannel(), Permission.MESSAGE_ADD_REACTION);
for (String s1 : m) {
messages.add("**Mantaro's Options List**\n" + (hasReactionPerms ? "Use the arrow reactions to change pages. " : "Use &page >> and &page << to change pages and &cancel to end") + "*All options must be prefixed with `~>opts` when running them*\n" + String.format("```prolog\n%s```", s1));
}
if (hasReactionPerms) {
DiscordUtils.list(event, 45, false, messages);
} else {
DiscordUtils.listText(event, 45, false, messages);
}
return;
}
if (args.length < 2) {
event.getChannel().sendMessage(help(event)).queue();
return;
}
StringBuilder name = new StringBuilder();
if (args[0].equalsIgnoreCase("help")) {
for (int i = 1; i < args.length; i++) {
String s = args[i];
if (name.length() > 0)
name.append(":");
name.append(s);
Option option = Option.getOptionMap().get(name.toString());
if (option != null) {
try {
EmbedBuilder builder = new EmbedBuilder().setAuthor(option.getOptionName(), null, event.getAuthor().getEffectiveAvatarUrl()).setDescription(option.getDescription()).setThumbnail("https://cdn.pixabay.com/photo/2012/04/14/16/26/question-34499_960_720.png").addField("Type", option.getType().toString(), false);
event.getChannel().sendMessage(builder.build()).queue();
} catch (IndexOutOfBoundsException ignored) {
}
return;
}
}
event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid option help name.").queue(message -> message.delete().queueAfter(10, TimeUnit.SECONDS));
return;
}
for (int i = 0; i < args.length; i++) {
String s = args[i];
if (name.length() > 0)
name.append(":");
name.append(s);
Option option = Option.getOptionMap().get(name.toString());
if (option != null) {
BiConsumer<GuildMessageReceivedEvent, String[]> callable = Option.getOptionMap().get(name.toString()).getEventConsumer();
try {
String[] a;
if (++i < args.length)
a = Arrays.copyOfRange(args, i, args.length);
else
a = new String[0];
callable.accept(event, a);
Player p = MantaroData.db().getPlayer(event.getAuthor());
if (p.getData().addBadgeIfAbsent(Badge.DID_THIS_WORK)) {
p.saveAsync();
}
} catch (IndexOutOfBoundsException ignored) {
}
return;
}
}
event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid option or arguments.").queue(message -> message.delete().queueAfter(10, TimeUnit.SECONDS));
event.getChannel().sendMessage(help(event)).queue();
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Options and Configurations Command").setDescription("**This command allows you to change Mantaro settings for this server.**\n" + "All values set are local rather than global, meaning that they will only effect this server.").addField("Usage", "The command is so big that we moved the description to the wiki. [Click here](https://github.com/Mantaro/MantaroBot/wiki/Configuration) to go to the Wiki Article.", false).build();
}
}).addOption("check:data", new Option("Data check.", "Checks the data values you have set on this server. **THIS IS NOT USER-FRIENDLY**", OptionType.GENERAL).setAction(event -> {
DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
GuildData guildData = dbGuild.getData();
// Map as follows: name, value
Map<String, Object> fieldMap = mapObjects(guildData);
if (fieldMap == null) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot retrieve values. Weird thing...").queue();
return;
}
StringBuilder show = new StringBuilder();
show.append("Options set for server **").append(event.getGuild().getName()).append("**\n\n");
AtomicInteger ai = new AtomicInteger();
for (Entry e : fieldMap.entrySet()) {
if (e.getKey().equals("localPlayerExperience")) {
continue;
}
show.append(ai.incrementAndGet()).append(".- `").append(e.getKey()).append("`");
if (e.getValue() == null) {
show.append(" **is not set to anything.").append("**\n");
} else {
show.append(" is set to: **").append(e.getValue()).append("**\n");
}
}
List<String> toSend = DiscordUtils.divideString(1600, show);
toSend.forEach(message -> event.getChannel().sendMessage(message).queue());
}).setShortDescription("Checks the data values you have set on this server.")).addOption("reset:all", new Option("Options reset.", "Resets all options set on this server.", OptionType.GENERAL).setAction(event -> {
// Temporary stuff.
DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
GuildData temp = MantaroData.db().getGuild(event.getGuild()).getData();
// The persistent data we wish to maintain.
String premiumKey = temp.getPremiumKey();
long quoteLastId = temp.getQuoteLastId();
long ranPolls = temp.getQuoteLastId();
String gameTimeoutExpectedAt = temp.getGameTimeoutExpectedAt();
long cases = temp.getCases();
// Assign everything all over again
DBGuild newDbGuild = DBGuild.of(dbGuild.getId(), dbGuild.getPremiumUntil());
GuildData newTmp = newDbGuild.getData();
newTmp.setGameTimeoutExpectedAt(gameTimeoutExpectedAt);
newTmp.setRanPolls(ranPolls);
newTmp.setCases(cases);
newTmp.setPremiumKey(premiumKey);
newTmp.setQuoteLastId(quoteLastId);
// weee
newDbGuild.saveAsync();
event.getChannel().sendMessage(EmoteReference.CORRECT + "Correctly reset your options!").queue();
}));
}
use of net.kodehawa.mantarobot.core.CommandRegistry 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.CommandRegistry in project MantaroBot by Mantaro.
the class OwnerCmd method badge.
@Subscribe
public void badge(CommandRegistry cr) {
cr.register("addbadge", new SimpleCommand(Category.OWNER, CommandPermission.OWNER) {
@Override
protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
if (event.getMessage().getMentionedUsers().isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to give me an user to apply the badge to!").queue();
return;
}
if (args.length != 2) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Wrong args length").queue();
return;
}
String b = args[1];
List<User> users = event.getMessage().getMentionedUsers();
Badge badge = Badge.lookupFromString(b);
if (badge == null) {
event.getChannel().sendMessage(EmoteReference.ERROR + "No badge with that enum name! Valid badges: " + Arrays.stream(Badge.values()).map(b1 -> "`" + b1.name() + "`").collect(Collectors.joining(" ,"))).queue();
return;
}
for (User u : users) {
Player p = MantaroData.db().getPlayer(u);
p.getData().addBadgeIfAbsent(badge);
p.saveAsync();
}
event.getChannel().sendMessage(EmoteReference.CORRECT + "Added badge " + badge + " to " + users.stream().map(User::getName).collect(Collectors.joining(" ,"))).queue();
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return null;
}
});
cr.register("removebadge", new SimpleCommand(Category.OWNER, CommandPermission.OWNER) {
@Override
protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
if (event.getMessage().getMentionedUsers().isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to give me an user to remove the badge from!").queue();
return;
}
if (args.length != 2) {
event.getChannel().sendMessage(EmoteReference.ERROR + "Wrong args length").queue();
return;
}
String b = args[1];
List<User> users = event.getMessage().getMentionedUsers();
Badge badge = Badge.lookupFromString(b);
if (badge == null) {
event.getChannel().sendMessage(EmoteReference.ERROR + "No badge with that enum name! Valid badges: " + Arrays.stream(Badge.values()).map(b1 -> "`" + b1.name() + "`").collect(Collectors.joining(" ,"))).queue();
return;
}
for (User u : users) {
Player p = MantaroData.db().getPlayer(u);
p.getData().removeBadge(badge);
p.saveAsync();
}
event.getChannel().sendMessage(String.format("%sRemoved badge %s from %s", EmoteReference.CORRECT, badge, users.stream().map(User::getName).collect(Collectors.joining(" ,")))).queue();
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return null;
}
});
}
use of net.kodehawa.mantarobot.core.CommandRegistry in project MantaroBot by Mantaro.
the class OwnerCmd method eval.
@Subscribe
public void eval(CommandRegistry cr) {
// has no state
JavaEvaluator javaEvaluator = new JavaEvaluator();
Map<String, Evaluator> evals = new HashMap<>();
evals.put("js", (event, code) -> {
ScriptEngine script = new ScriptEngineManager().getEngineByName("nashorn");
script.put("mantaro", MantaroBot.getInstance());
script.put("db", MantaroData.db());
script.put("jda", event.getJDA());
script.put("event", event);
script.put("guild", event.getGuild());
script.put("channel", event.getChannel());
try {
return script.eval(String.join("\n", "load(\"nashorn:mozilla_compat.js\");", "imports = new JavaImporter(java.util, java.io, java.net);", "(function() {", "with(imports) {", code, "}", "})()"));
} catch (Exception e) {
return e;
}
});
evals.put("bsh", (event, code) -> {
Interpreter interpreter = new Interpreter();
try {
interpreter.set("mantaro", MantaroBot.getInstance());
interpreter.set("db", MantaroData.db());
interpreter.set("jda", event.getJDA());
interpreter.set("event", event);
interpreter.set("guild", event.getGuild());
interpreter.set("channel", event.getChannel());
return interpreter.eval(String.join("\n", "import *;", code));
} catch (Exception e) {
return e;
}
});
evals.put("java", (event, code) -> {
try {
CompilationResult r = javaEvaluator.compile().addCompilerOptions("-Xlint:unchecked").source("Eval", JAVA_EVAL_IMPORTS + "\n\n" + "public class Eval {\n" + " public static Object run(GuildMessageReceivedEvent event) {\n" + " try {\n" + " return null;\n" + " } finally {\n" + " " + (code + ";").replaceAll(";{2,}", ";") + "\n" + " }\n" + " }\n" + "}").execute();
EvalClassLoader ecl = new EvalClassLoader();
r.getClasses().forEach((name, bytes) -> ecl.define(bytes));
return ecl.loadClass("Eval").getMethod("run", GuildMessageReceivedEvent.class).invoke(null, event);
} catch (CompilationException e) {
StringBuilder sb = new StringBuilder("\n");
if (e.getCompilerOutput() != null)
sb.append(e.getCompilerOutput());
if (!e.getDiagnostics().isEmpty()) {
if (sb.length() > 0)
sb.append("\n\n");
e.getDiagnostics().forEach(d -> sb.append(d).append('\n'));
}
return new Error(sb.toString()) {
@Override
public String toString() {
return getMessage();
}
};
} catch (Exception e) {
return e;
}
});
cr.register("eval", new SimpleCommand(Category.OWNER, CommandPermission.OWNER) {
@Override
protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
Evaluator evaluator = evals.get(args[0]);
if (evaluator == null) {
onHelp(event);
return;
}
String[] values = SPLIT_PATTERN.split(content, 2);
if (values.length < 2) {
onHelp(event);
return;
}
String v = values[1];
Object result = evaluator.eval(event, v);
boolean errored = result instanceof Throwable;
event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Evaluated " + (errored ? "and errored" : "with success"), null, event.getAuthor().getAvatarUrl()).setColor(errored ? Color.RED : Color.GREEN).setDescription(result == null ? "Executed successfully with no objects returned" : ("Executed " + (errored ? "and errored: " : "successfully and returned: ") + result.toString())).setFooter("Asked by: " + event.getAuthor().getName(), null).build()).queue();
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Eval cmd").setDescription("**Evaluates stuff (A: js/bsh)**").build();
}
});
}
use of net.kodehawa.mantarobot.core.CommandRegistry 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