use of com.google.common.eventbus.Subscribe 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 com.google.common.eventbus.Subscribe 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 com.google.common.eventbus.Subscribe 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 com.google.common.eventbus.Subscribe in project MantaroBot by Mantaro.
the class MiscCmds method createPoll.
@Subscribe
public void createPoll(CommandRegistry registry) {
registry.register("createpoll", new SimpleCommand(Category.MISC) {
@Override
protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
Map<String, Optional<String>> opts = StringUtils.parse(args);
PollBuilder builder = Poll.builder();
if (!opts.containsKey("time") || !opts.get("time").isPresent()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You didn't include either the `-time` argument or it was empty!\n" + "Example: `~>poll -options \"hi there\",\"wew\",\"owo what's this\" -time 10m20s -name \"test poll\"").queue();
return;
}
if (!opts.containsKey("options") || !opts.get("options").isPresent()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You didn't include either the `-options` argument or it was empty!\n" + "Example: ~>poll -options \"hi there\",\"wew\",\"owo what's this\" -time 10m20s -name \"test poll\"").queue();
return;
}
if (!opts.containsKey("name") || !opts.get("name").isPresent()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You didn't include either the `-name` argument or it was empty!\n" + "Example: ~>poll -options \"hi there\",\"wew\",\"owo what's this\" -time 10m20s -name \"test poll\"").queue();
return;
}
if (opts.containsKey("name") || opts.get("name").isPresent()) {
builder.setName(opts.get("name").get().replaceAll(String.valueOf('"'), ""));
}
String[] options = opts.get("options").get().replaceAll(String.valueOf('"'), "").split(",");
long timeout = Utils.parseTime(opts.get("time").get());
builder.setEvent(event).setTimeout(timeout).setOptions(options).build().startPoll();
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Poll Command").setDescription("**Creates a poll**").addField("Usage", "`~>poll [-options <options>] [-time <time>] [-name <name>]`", false).addField("Parameters", "`-options` The options to add. Minimum is 2 and maximum is 9. For instance: `Pizza,Spaghetti,Pasta,\"Spiral Nudels\"` (Enclose options with multiple words in double quotes).\n" + "`-time` The time the operation is gonna take. The format is as follows `1m29s` for 1 minute and 21 seconds. Maximum poll runtime is 45 minutes.\n" + "`-name` The name of the poll for reference.", false).addField("Considerations", "To cancel the running poll type &cancelpoll. Only the person who started it or an Admin can cancel it.", false).addField("Example", "~>poll -options \"hi there\",\"wew\",\"owo what's this\" -time 10m20s -name \"test poll\"", false).build();
}
});
registry.registerAlias("createpoll", "poll");
}
use of com.google.common.eventbus.Subscribe in project MantaroBot by Mantaro.
the class ModerationCmds method tempban.
@Subscribe
public void tempban(CommandRegistry cr) {
cr.register("tempban", new SimpleCommand(Category.MODERATION) {
@Override
protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
String reason = content;
Guild guild = event.getGuild();
User author = event.getAuthor();
TextChannel channel = event.getChannel();
Message receivedMessage = event.getMessage();
if (!guild.getMember(author).hasPermission(net.dv8tion.jda.core.Permission.BAN_MEMBERS)) {
channel.sendMessage(EmoteReference.ERROR + "Cannot ban: You have no Ban Members permission.").queue();
return;
}
if (event.getMessage().getMentionedUsers().isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to mention an user!").queue();
return;
}
for (User user : event.getMessage().getMentionedUsers()) {
reason = reason.replaceAll("(\\s+)?<@!?" + user.getId() + ">(\\s+)?", "");
}
int index = reason.indexOf("time:");
if (index < 0) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot temp ban an user without giving me the time!").queue();
return;
}
String time = reason.substring(index);
reason = reason.replace(time, "").trim();
time = time.replaceAll("time:(\\s+)?", "");
if (reason.isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot temp ban someone without a reason.!").queue();
return;
}
if (time.isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot temp ban someone without giving me the time!").queue();
return;
}
final DBGuild db = MantaroData.db().getGuild(event.getGuild());
long l = Utils.parseTime(time);
String finalReason = String.format("Temporally banned by %#s: %s", event.getAuthor(), reason);
String sTime = StringUtils.parseTime(l);
receivedMessage.getMentionedUsers().forEach(user -> guild.getController().ban(user, 7).queue(success -> user.openPrivateChannel().queue(privateChannel -> {
if (!user.isBot()) {
privateChannel.sendMessage(String.format("%sYou were **temporarily banned** by %s#%s with reason: %s on server **%s**.", EmoteReference.MEGA, event.getAuthor().getName(), event.getAuthor().getDiscriminator(), finalReason, event.getGuild().getName())).queue();
}
db.getData().setCases(db.getData().getCases() + 1);
db.saveAsync();
channel.sendMessage(String.format("%s%s (%s got temporarly banned)", EmoteReference.ZAP, modActionQuotes[r.nextInt(modActionQuotes.length)], user.getName())).queue();
ModLog.log(event.getMember(), user, finalReason, ModLog.ModAction.TEMP_BAN, db.getData().getCases(), sTime);
MantaroBot.getTempBanManager().addTempban(guild.getId() + ":" + user.getId(), l + System.currentTimeMillis());
TextChannelGround.of(event).dropItemWithChance(1, 2);
}), error -> {
if (error instanceof PermissionException) {
channel.sendMessage(String.format("%sError banning %s: (I need the permission %s)", EmoteReference.ERROR, user.getName(), ((PermissionException) error).getPermission())).queue();
} else {
channel.sendMessage(String.format("%sI encountered an unknown error while banning %s", EmoteReference.ERROR, user.getName())).queue();
log.warn("Encountered an unexpected error while trying to ban someone.", error);
}
}));
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Tempban Command").setDescription("**Temporarily bans an user**").addField("Usage", "`~>tempban <user> <reason> time:<time>`", false).addField("Example", "`~>tempban @Kodehawa example time:1d`", false).addField("Extended usage", "`time` - can be used with the following parameters: " + "d (days), s (second), m (minutes), h (hour). **For example time:1d1h will give a day and an hour.**", false).build();
}
});
}
Aggregations