use of com.google.common.eventbus.Subscribe 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 com.google.common.eventbus.Subscribe 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 com.google.common.eventbus.Subscribe 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 com.google.common.eventbus.Subscribe 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();
}
});
}
use of com.google.common.eventbus.Subscribe 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