use of net.kodehawa.mantarobot.core.modules.commands.SimpleCommand 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.modules.commands.SimpleCommand 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.modules.commands.SimpleCommand 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.modules.commands.SimpleCommand in project MantaroBot by Mantaro.
the class PlayerCmds method rep.
@Subscribe
public void rep(CommandRegistry cr) {
cr.register("rep", new SimpleCommand(Category.CURRENCY) {
final RateLimiter rateLimiter = new RateLimiter(TimeUnit.HOURS, 12);
@Override
public void call(GuildMessageReceivedEvent event, String content, String[] args) {
long rl = rateLimiter.tryAgainIn(event.getMember());
User user;
if (content.isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to mention or put the name of at least one user.\n" + (rl > 0 ? "**You'll be able to use this command again in " + Utils.getVerboseTime(rateLimiter.tryAgainIn(event.getMember())) + ".**" : "You can rep someone now.")).queue();
return;
}
List<User> mentioned = event.getMessage().getMentionedUsers();
if (!mentioned.isEmpty() && mentioned.size() > 1) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You can only give reputation to one person!").queue();
return;
}
Member member = Utils.findMember(event, event.getMember(), content);
if (member == null)
return;
user = member.getUser();
if (user.isBot()) {
event.getChannel().sendMessage(EmoteReference.THINKING + "You cannot rep a bot.\n" + (rl > 0 ? "**You'll be able to use this command again in " + Utils.getVerboseTime(rateLimiter.tryAgainIn(event.getMember())) + ".**" : "You can rep someone now.")).queue();
return;
}
if (user.equals(event.getAuthor())) {
event.getChannel().sendMessage(EmoteReference.THINKING + "You cannot rep yourself.\n" + (rl > 0 ? "**You'll be able to use this command again in " + Utils.getVerboseTime(rateLimiter.tryAgainIn(event.getMember())) + ".**" : "You can rep someone now.")).queue();
return;
}
if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
return;
Player player = MantaroData.db().getPlayer(user);
player.addReputation(1L);
player.save();
event.getChannel().sendMessage(EmoteReference.CORRECT + "Added reputation to **" + member.getEffectiveName() + "**").queue();
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Reputation command").setDescription("**Reps an user**").addField("Usage", "`~>rep <@user>` - **Gives reputation to x user**", false).addField("Parameters", "`@user` - user to mention", false).addField("Important", "Only usable every 12 hours.", false).build();
}
});
cr.registerAlias("rep", "reputation");
}
use of net.kodehawa.mantarobot.core.modules.commands.SimpleCommand in project MantaroBot by Mantaro.
the class UtilsCmds method dictionary.
@Subscribe
public void dictionary(CommandRegistry registry) {
registry.register("dictionary", new SimpleCommand(Category.UTILS) {
@Override
protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
if (args.length == 0) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a word.").queue();
return;
}
String word = content;
JSONObject main;
String definition, part_of_speech, headword, example;
try {
main = new JSONObject(Utils.wgetResty("http://api.pearson.com/v2/dictionaries/laes/entries?headword=" + word, event));
JSONArray results = main.getJSONArray("results");
JSONObject result = results.getJSONObject(0);
JSONArray senses = result.getJSONArray("senses");
headword = result.getString("headword");
if (result.has("part_of_speech"))
part_of_speech = result.getString("part_of_speech");
else
part_of_speech = "Not found.";
if (senses.getJSONObject(0).get("definition") instanceof JSONArray)
definition = senses.getJSONObject(0).getJSONArray("definition").getString(0);
else
definition = senses.getJSONObject(0).getString("definition");
try {
if (senses.getJSONObject(0).getJSONArray("translations").getJSONObject(0).get("example") instanceof JSONArray) {
example = senses.getJSONObject(0).getJSONArray("translations").getJSONObject(0).getJSONArray("example").getJSONObject(0).getString("text");
} else {
example = senses.getJSONObject(0).getJSONArray("translations").getJSONObject(0).getJSONObject("example").getString("text");
}
} catch (Exception e) {
example = "Not found";
}
} catch (Exception e) {
event.getChannel().sendMessage(EmoteReference.ERROR + "No results.").queue();
return;
}
EmbedBuilder eb = new EmbedBuilder();
eb.setAuthor("Definition for " + word, null, event.getAuthor().getAvatarUrl()).setThumbnail("https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Wikt_dynamic_dictionary_logo.svg/1000px-Wikt_dynamic_dictionary_logo.svg.png").addField("Definition", "**" + definition + "**", false).addField("Example", "**" + example + "**", false).setDescription(String.format("**Part of speech:** `%s`\n" + "**Headword:** `%s`\n", part_of_speech, headword));
event.getChannel().sendMessage(eb.build()).queue();
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Dictionary command").setDescription("**Looks up a word in the dictionary.**").addField("Usage", "`~>dictionary <word>` - Searches a word in the dictionary.", false).addField("Parameters", "`word` - The word to look for", false).build();
}
});
}
Aggregations