diff --git a/build.gradle b/build.gradle index 404acea..8344362 100644 --- a/build.gradle +++ b/build.gradle @@ -10,5 +10,5 @@ repositories { } dependencies { - compile 'net.dv8tion:JDA:3.5.1_348' + compile 'net.dv8tion:JDA:3.6.0_354' } diff --git a/src/main/java/fr/neutronstars/nbot/NBot.java b/src/main/java/fr/neutronstars/nbot/NBot.java index 40b1ef0..33194e7 100644 --- a/src/main/java/fr/neutronstars/nbot/NBot.java +++ b/src/main/java/fr/neutronstars/nbot/NBot.java @@ -20,7 +20,7 @@ */ public final class NBot { - private static final String NAME = "NBot", VERSION = "2.0.4", AUTHOR = "NeutronStars"; + private static final String NAME = "NBot", VERSION = "2.1.0", AUTHOR = "NeutronStars", JDA_VERSION = "3.6.0_354"; private static final NBotLogger logger = StaticLoggerBinder.getSingleton().getLoggerFactory().getLogger("NBot"); private static NBotServer server; @@ -50,6 +50,11 @@ public static String getVersion() return VERSION; } + public static String getJdaVersion() + { + return JDA_VERSION; + } + public static String getAuthor() { return AUTHOR; diff --git a/src/main/java/fr/neutronstars/nbot/NBotStart.java b/src/main/java/fr/neutronstars/nbot/NBotStart.java index 1a295e4..f9fdc39 100644 --- a/src/main/java/fr/neutronstars/nbot/NBotStart.java +++ b/src/main/java/fr/neutronstars/nbot/NBotStart.java @@ -1,7 +1,10 @@ package fr.neutronstars.nbot; +import fr.neutronstars.nbot.command.CommandBuilder; import fr.neutronstars.nbot.command.CommandManager; +import fr.neutronstars.nbot.command.defaut.ConsoleCommand; import fr.neutronstars.nbot.command.defaut.DefaultCommand; +import fr.neutronstars.nbot.command.defaut.HelpCommand; import fr.neutronstars.nbot.exception.NBotConfigurationException; import fr.neutronstars.nbot.plugin.PluginManager; import fr.neutronstars.nbot.util.Configuration; @@ -20,7 +23,7 @@ public static void main(String... args) { System.setProperty("file.encoding", "UTF-8"); - loadFolders("guilds", "plugins", "config"); + loadFolders("guilds", "plugins", "config", "tmp"); Configuration configuration = loadConfiguration(); setDefaultConfiguration(configuration); @@ -28,9 +31,10 @@ public static void main(String... args) NBotLogger.load(configuration); logger.info(String.format("Starting %1$s v%2$s by %3$s...", NBot.getName(), NBot.getVersion(), NBot.getAuthor())); + logger.info(String.format("Loading libraries of JDA v%1$s...", NBot.getJdaVersion())); PluginManager pluginManager = new PluginManager(configuration.getString("loadedFormat"), configuration.getString("enabledFormat"), configuration.getString("disabledFormat")); - CommandManager.registerCommand(new DefaultCommand(), null); + CommandManager.registerCommands(null, new DefaultCommand(), new ConsoleCommand(), new HelpCommand()); pluginManager.registerCommands(); try diff --git a/src/main/java/fr/neutronstars/nbot/command/Command.java b/src/main/java/fr/neutronstars/nbot/command/Command.java index e68f9b1..e0bac27 100644 --- a/src/main/java/fr/neutronstars/nbot/command/Command.java +++ b/src/main/java/fr/neutronstars/nbot/command/Command.java @@ -16,5 +16,13 @@ int powers() default 0; long[] guilds() default {}; - long[] channels() default {}; + + boolean toPrivate() default false; + boolean privateOnly() default false; + + ExecutorType executor() default ExecutorType.USER; + + enum ExecutorType{ + USER, CONSOLE, ALL + } } diff --git a/src/main/java/fr/neutronstars/nbot/command/CommandArgs.java b/src/main/java/fr/neutronstars/nbot/command/CommandArgs.java new file mode 100644 index 0000000..5723ca4 --- /dev/null +++ b/src/main/java/fr/neutronstars/nbot/command/CommandArgs.java @@ -0,0 +1,115 @@ +package fr.neutronstars.nbot.command; + +import fr.neutronstars.nbot.entity.*; +import fr.neutronstars.nbot.entity.Channel; +import fr.neutronstars.nbot.entity.Guild; +import fr.neutronstars.nbot.entity.Message; +import fr.neutronstars.nbot.entity.User; +import net.dv8tion.jda.core.JDA; +import net.dv8tion.jda.core.entities.*; + +public class CommandArgs +{ + private final JDA jda; + private final String commandToString; + private final String[] args; + private final Message message; + private final Guild guild; + private final Channel channel; + private final User user; + private final CommandSender commandSender; + private final SimpleCommand simpleCommand; + private final Category category; + private final Member member; + private final PrivateChannel privateChannel; + private final TextChannel textChannel; + private final SelfUser selfUser; + + protected CommandArgs(JDA jda, String commandToString, String[] args, Message message, Guild guild, Channel channel, User user, CommandSender commandSender, SimpleCommand simpleCommand, Category category, Member member, PrivateChannel privateChannel, TextChannel textChannel, SelfUser selfUser) + { + this.jda = jda; + this.commandToString = commandToString; + this.args = args; + this.message = message; + this.guild = guild; + this.channel = channel; + this.user = user; + this.commandSender = commandSender; + this.simpleCommand = simpleCommand; + this.category = category; + this.member = member; + this.privateChannel = privateChannel; + this.textChannel = textChannel; + this.selfUser = selfUser; + } + + public JDA getJda() + { + return jda; + } + + public User getUser() + { + return user; + } + + public TextChannel getTextChannel() + { + return textChannel; + } + + public String[] getArgs() + { + return args; + } + + public String getCommand() + { + return commandToString; + } + + public SimpleCommand getSimpleCommand() + { + return simpleCommand; + } + + public SelfUser getSelfUser() + { + return selfUser; + } + + public PrivateChannel getPrivateChannel() + { + return privateChannel; + } + + public Member getMember() + { + return member; + } + + public Guild getGuild() + { + return guild; + } + + public CommandSender getCommandSender() + { + return commandSender; + } + + public Channel getChannel() + { + return channel; + } + + public Category getCategory() + { + return category; + } + + public Message getMessage() + { + return message; + } +} diff --git a/src/main/java/fr/neutronstars/nbot/command/CommandBuilder.java b/src/main/java/fr/neutronstars/nbot/command/CommandBuilder.java new file mode 100644 index 0000000..a55253c --- /dev/null +++ b/src/main/java/fr/neutronstars/nbot/command/CommandBuilder.java @@ -0,0 +1,114 @@ +package fr.neutronstars.nbot.command; + +import fr.neutronstars.nbot.plugin.NBotPlugin; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +public class CommandBuilder +{ + private final String name, description; + private final List guilds = new ArrayList<>(); + private final List aliases = new ArrayList<>(); + private final Command.ExecutorType executor; + private final boolean toPrivate, privateOnly; + + private int power; + private Consumer consumer; + + public CommandBuilder(String name, String description) + { + this(name, description, 0); + } + + public CommandBuilder(String name, String description, int power) + { + this(name, description, 0, Command.ExecutorType.USER, false, false); + } + + public CommandBuilder(String name, String description, boolean toPrivate, boolean privateOnly) + { + this(name, description, 0, toPrivate, privateOnly); + } + + public CommandBuilder(String name, String description, int power, boolean toPrivate, boolean privateOnly) + { + this(name, description, 0, Command.ExecutorType.USER, toPrivate, privateOnly); + } + + public CommandBuilder(String name, String description, int power, Command.ExecutorType executor, boolean toPrivate, boolean privateOnly) + { + this.name = name; + this.description = description; + this.power = power; + this.executor = executor; + this.toPrivate = toPrivate; + this.privateOnly = privateOnly; + } + + public String getName() + { + return name; + } + + public String getDescription() + { + return description; + } + + public Command.ExecutorType getExecutor() + { + return executor; + } + + public int getPower() + { + return power; + } + + public List getGuilds() + { + return guilds; + } + + public List getAliases() + { + return aliases; + } + + public CommandBuilder addGuild(long guildId) + { + guilds.add(guildId); + return this; + } + + public boolean isToPrivate() + { + return toPrivate; + } + + public boolean isPrivateOnly() + { + return privateOnly; + } + + public CommandBuilder setExecutor(Consumer consumer) + { + this.consumer = consumer; + return this; + } + + protected void execute(CommandArgs args) + { + if(consumer != null) consumer.accept(args); + } + + public void register(NBotPlugin plugin) + { + if(plugin == null) + CommandManager.registerCommand(this, null); + else + plugin.registerCommand(this); + } +} diff --git a/src/main/java/fr/neutronstars/nbot/command/CommandManager.java b/src/main/java/fr/neutronstars/nbot/command/CommandManager.java index 62deebb..d774286 100644 --- a/src/main/java/fr/neutronstars/nbot/command/CommandManager.java +++ b/src/main/java/fr/neutronstars/nbot/command/CommandManager.java @@ -1,6 +1,10 @@ package fr.neutronstars.nbot.command; +import fr.neutronstars.nbot.NBot; +import fr.neutronstars.nbot.entity.Console; import fr.neutronstars.nbot.entity.Guild; +import fr.neutronstars.nbot.entity.Message; +import fr.neutronstars.nbot.entity.User; import fr.neutronstars.nbot.plugin.NBotPlugin; import java.lang.reflect.Method; @@ -12,6 +16,8 @@ public class CommandManager { private static final List defaultCommand = new ArrayList<>(); + private static final Map consoleCommand = new HashMap<>(); + private static final Map privateCommand = new HashMap<>(); public static void registerCommands(NBotPlugin plugin, Object... objects) { @@ -19,12 +25,27 @@ public static void registerCommands(NBotPlugin plugin, Object... objects) } public static void registerCommand(Object commandManager, NBotPlugin plugin){ + + if(commandManager instanceof CommandBuilder) + { + SimpleCommand command = new SimpleCommand((CommandBuilder) commandManager, plugin); + defaultCommand.add(command); + + if(command.canExecute(Command.ExecutorType.CONSOLE)) consoleCommand.put(command.getSimpleName(), command); + if(command.isPrivate()) privateCommand.put(command.getSimpleName(), command); + return; + } + for(Method method : commandManager.getClass().getDeclaredMethods()){ if(method.isAnnotationPresent(Command.class)){ Command command = method.getAnnotation(Command.class); method.setAccessible(true); - SimpleCommand simpleCommand = new SimpleCommand(command.name(), command.description(), command.powers(), command.guilds(), command.channels(), method, commandManager, plugin); + SimpleCommand simpleCommand = new SimpleCommand(command.name(), command.description(), command.powers(), command.guilds(), method, commandManager, command.executor(), command.toPrivate(), command.privateOnly(), plugin); defaultCommand.add(simpleCommand); + if(simpleCommand.canExecute(Command.ExecutorType.CONSOLE)) + consoleCommand.put(simpleCommand.getSimpleName(), simpleCommand); + if(simpleCommand.isPrivate()) + privateCommand.put(simpleCommand.getSimpleName(), simpleCommand); } } } @@ -35,11 +56,111 @@ protected static Map getCommandMap(Guild guild) for(SimpleCommand simpleCommand : defaultCommand) { - if(simpleCommand.getGuilds().size() != 0 && !simpleCommand.guildCanExecute(guild)) continue; + if(simpleCommand.isPrivateOnly() || !simpleCommand.canExecute(Command.ExecutorType.USER) || (simpleCommand.getGuilds().size() != 0 && !simpleCommand.guildCanExecute(guild))) + continue; commandMap.put(simpleCommand.getSimpleName(), simpleCommand.clone(guild)); } return commandMap; } + public static void onPrivateCommand(User user, Message message, String command) + { + if(command == null) return; + Object[] object = CommandMap.getCommands(privateCommand, command.split(" ")); + if(object[0] == null) return; + + if(object[0] instanceof List) + { + List list = (List) object[0]; + + StringBuilder builder = new StringBuilder(32); + for(int i = 0; i < list.size(); i++) + { + if(i != 0) builder.append(", "); + builder.append(list.get(i)); + } + builder.append("."); + user.sendMessageToSender(builder.toString()); + return; + } + + SimpleCommand simpleCommand = (SimpleCommand)object[0]; + if(simpleCommand.getPlugin() != null) + simpleCommand.getPlugin().getLogger().info("[Private-Command] "+user.getName()+" -> "+command); + else + NBot.getLogger().info("[Private-Command] "+user.getName()+" -> "+command); + + try { + CommandMap.execute(simpleCommand, command, (String[]) object[1], message, user); + }catch(Throwable e) { + if(simpleCommand.getPlugin() != null) + simpleCommand.getPlugin().getLogger().error(e.getMessage(), e); + else + NBot.getLogger().error(e.getMessage(), e); + } + } + + public static void onConsoleCommand(Console console, String command) + { + if(command == null) return; + Object[] object = CommandMap.getCommands(consoleCommand, command.split(" ")); + if(object[0] == null) return; + + if(object[0] instanceof List) + { + List list = (List) object[0]; + + StringBuilder builder = new StringBuilder(32); + for(int i = 0; i < list.size(); i++) + { + if(i != 0) builder.append(", "); + builder.append(list.get(i)); + } + builder.append("."); + console.sendMessageToSender(builder.toString()); + return; + } + + SimpleCommand simpleCommand = (SimpleCommand)object[0]; + if(simpleCommand.getPlugin() != null) + simpleCommand.getPlugin().getLogger().info("[Command-Console] -> "+command); + else + NBot.getLogger().info("[Command-Console] -> "+command); + + try { + CommandMap.execute(simpleCommand, command, (String[]) object[1], null, console); + }catch(Throwable e) { + if(simpleCommand.getPlugin() != null) + simpleCommand.getPlugin().getLogger().error(e.getMessage(), e); + else + NBot.getLogger().error(e.getMessage(), e); + } + } + + public static List getDefaultCommands(boolean console) + { + List defaultCommands = new ArrayList<>(); + Collection commands = console ? consoleCommand.values() : privateCommand.values(); + + for(SimpleCommand command : commands) + if(command.getPlugin() == null) defaultCommands.add(command); + + return defaultCommands; + } + + public static Map> getPluginCommands(boolean console) + { + Map> pluginCommandMap = new HashMap<>(); + Collection commands = console ? consoleCommand.values() : privateCommand.values(); + + for(SimpleCommand command : commands) + { + if(command.getPlugin() == null) continue; + if(!pluginCommandMap.containsKey(command.getPlugin())) + pluginCommandMap.put(command.getPlugin(), new ArrayList<>()); + pluginCommandMap.get(command.getPlugin()).add(command); + } + return pluginCommandMap; + } } diff --git a/src/main/java/fr/neutronstars/nbot/command/CommandMap.java b/src/main/java/fr/neutronstars/nbot/command/CommandMap.java index a741ac5..396170e 100644 --- a/src/main/java/fr/neutronstars/nbot/command/CommandMap.java +++ b/src/main/java/fr/neutronstars/nbot/command/CommandMap.java @@ -29,9 +29,11 @@ public final class CommandMap private final List commands = new ArrayList<>(); private final Map commandMap; private final Configuration commandsDefaultConfig; - private String prefix = "bot."; private final Guild guild; + private String prefix = "bot."; + private boolean deleteCommand; + public CommandMap(Guild guild) { this.guild = guild; @@ -41,6 +43,7 @@ public CommandMap(Guild guild) commands.addAll(commandMap.values()); if(guild.getConfiguration().has("prefix")) prefix = guild.getConfiguration().getString("prefix"); + if(guild.getConfiguration().has("deleteCommand")) deleteCommand = guild.getConfiguration().getBoolean("deleteCommand"); loadCommands(); } @@ -61,22 +64,16 @@ private void loadCommands() if(!customName.equalsIgnoreCase("null")) setCustomNameCommand(command.getSimpleName(), customName.toLowerCase()); } - if(object.has("aliases")) + if(object.has("power")) command.setPower(object.getInt("power")); + + if(object.has("channels")) { - JSONArray array = object.getJSONArray("aliases"); + JSONArray array = object.getJSONArray("channels"); for(int i = 0; i < array.length(); i++) { - String alias = array.getString(i).toLowerCase(); - if(alias.equalsIgnoreCase("")) continue; - if(!commandMap.containsKey(alias)) - { - command.addAlias(alias); - commandMap.put(alias, command); - } + command.addChannel(array.getLong(i)); } } - - if(object.has("power")) command.setPower(object.getInt("power")); } } } @@ -91,6 +88,11 @@ public String getPrefix() return prefix; } + public boolean isDeleteCommand() + { + return deleteCommand; + } + public void setPrefix(String prefix) { if(prefix == null) prefix = "bot."; @@ -98,6 +100,12 @@ public void setPrefix(String prefix) guild.getConfiguration().set("prefix", prefix); } + public void setDeleteCommand(boolean deleteCommand) + { + this.deleteCommand = deleteCommand; + guild.getConfiguration().set("deleteCommand", deleteCommand); + } + public SimpleCommand getCommand(String name) { return commandMap.get(name); @@ -128,11 +136,27 @@ public void save() public boolean onCommand(User user, String command, Message message) { if(command == null) return false; - Object[] objects = getCommands(command.split(" ")); + Object[] objects = getCommands(commandMap, command.split(" ")); if(objects[0] == null) return false; + if(objects[0] instanceof List) + { + List list = (List) objects[0]; + + StringBuilder builder = new StringBuilder(32); + builder.append(user.getAsMention()).append(" -> "); + for(int i = 0; i < list.size(); i++) + { + if(i != 0) builder.append(", "); + builder.append(list.get(i)); + } + builder.append("."); + message.getChannel().sendMessage(builder.toString()).queue(); + return true; + } + SimpleCommand simpleCommand = (SimpleCommand)objects[0]; - if(!guild.hasPermission(user, simpleCommand.getPower())) return false; + if(!guild.hasPermission(user, simpleCommand.getPower()) || !simpleCommand.canExecuteToChannel(message.getMessageChannel())) return false; if(simpleCommand.getPlugin() != null) simpleCommand.getPlugin().getLogger().info("[Command] "+user.getName() + " -> "+command); @@ -141,7 +165,7 @@ public boolean onCommand(User user, String command, Message message) try { execute(simpleCommand, command, (String[]) objects[1], message, user); - }catch(Exception e) { + }catch(Throwable e) { if(simpleCommand.getPlugin() != null) simpleCommand.getPlugin().getLogger().error(e.getMessage(), e); else @@ -150,13 +174,21 @@ public boolean onCommand(User user, String command, Message message) return true; } - public Object[] getCommands(String[] commandSplit) + public static Object[] getCommands(Map commandMap, String[] commandSplit) { if(commandSplit.length == 0) return null; String label = commandSplit[0].toLowerCase(); String[] args = new String[commandSplit.length-1]; for(int i = 1; i < commandSplit.length; i++) args[i-1] = commandSplit[i]; - return new Object[]{commandMap.get(label), args}; + + SimpleCommand command = commandMap.get(label); + if(command != null) return new Object[]{command, args}; + + List list = new ArrayList<>(); + for(Map.Entry entry : commandMap.entrySet()) + if(entry.getKey().toLowerCase().startsWith(label)) list.add(entry.getKey()); + + return new Object[]{!list.isEmpty() ? list.size() == 1 ? commandMap.get(list.get(0)) : list : null, args}; } public List getCommands() @@ -175,7 +207,7 @@ public List getDefaultCommands() return defaultCommands; } - public Map> getPkuginCommands() + public Map> getPluginCommands() { Map> pluginCommandMap = new HashMap<>(); List commands = getCommands(); @@ -190,7 +222,17 @@ public Map> getPkuginCommands() return pluginCommandMap; } - private void execute(SimpleCommand simpleCommand, String command, String[] args, Message message, User user) throws Exception{ + protected static void execute(SimpleCommand simpleCommand, String command, String[] args, Message message, CommandSender sender) throws Exception{ + if(simpleCommand.getCommandBuilder() != null) + { + CommandArgs commandArgs = new CommandArgs(NBot.getJDA(), command, args, message, message == null ? null : NBot.getGuild(message.getGuild()), + message == null ? null : message.getMessageChannel(), sender.isUser() ? (User) sender : null, sender, simpleCommand, message == null ? null : message.getCategory(), + message == null || sender.isConsole() ? null : message.getGuild() == null ? null : message.getGuild().getMember((User) sender), sender.isConsole() ? null : (PrivateChannel) ((User)sender).getMessageChannel(), + message == null ? null : message.getChannel() instanceof TextChannel ? (TextChannel) message.getChannel() : null, NBot.getJDA().getSelfUser()); + simpleCommand.getCommandBuilder().execute(commandArgs); + return; + } + Parameter[] parameters = simpleCommand.getMethod().getParameters(); Object[] objects = new Object[parameters.length]; for(int i = 0; i < parameters.length; i++){ @@ -201,14 +243,14 @@ private void execute(SimpleCommand simpleCommand, String command, String[] args, else if(parameters[i].getType() == Guild.class || parameters[i].getType() == net.dv8tion.jda.core.entities.Guild.class) objects[i] = message == null ? null : NBot.getGuild(message.getGuild()); else if(parameters[i].getType() == Channel.class || parameters[i].getType() == MessageChannel.class) objects[i] = message == null ? null : message.getMessageChannel(); - else if(parameters[i].getType() == User.class || parameters[i].getType() == net.dv8tion.jda.core.entities.User.class) objects[i] = user; - else if(parameters[i].getType() == CommandSender.class) objects[i] = user; + else if(parameters[i].getType() == User.class || parameters[i].getType() == net.dv8tion.jda.core.entities.User.class) objects[i] = sender.isUser() ? (User)sender : null; + else if(parameters[i].getType() == CommandSender.class) objects[i] = sender; else if(parameters[i].getType() == SimpleCommand.class) objects[i] = simpleCommand; else if(parameters[i].getType() == Category.class) objects[i] = message == null ? null : message.getCategory(); - else if(parameters[i].getType() == Member.class) objects[i] = message == null ? null : message.getGuild() == null ? null : message.getGuild().getMember(user); + else if(parameters[i].getType() == Member.class) objects[i] = message == null || sender.isConsole() ? null : message.getGuild() == null ? null : message.getGuild().getMember((User) sender); - else if(parameters[i].getType() == PrivateChannel.class) objects[i] = user == null ? null : (PrivateChannel) user.getMessageChannel(); + else if(parameters[i].getType() == PrivateChannel.class) objects[i] = sender.isConsole() ? null : (PrivateChannel) ((User) sender).getMessageChannel(); else if(parameters[i].getType() == TextChannel.class) objects[i] = message == null ? null : message.getChannel() instanceof TextChannel ? (TextChannel) message.getChannel() : null; else if(parameters[i].getType() == SelfUser.class) objects[i] = NBot.getJDA().getSelfUser(); diff --git a/src/main/java/fr/neutronstars/nbot/command/SimpleCommand.java b/src/main/java/fr/neutronstars/nbot/command/SimpleCommand.java index 6766c1f..4d46de1 100644 --- a/src/main/java/fr/neutronstars/nbot/command/SimpleCommand.java +++ b/src/main/java/fr/neutronstars/nbot/command/SimpleCommand.java @@ -1,7 +1,10 @@ package fr.neutronstars.nbot.command; +import fr.neutronstars.nbot.NBot; +import fr.neutronstars.nbot.entity.Channel; import fr.neutronstars.nbot.entity.Guild; import fr.neutronstars.nbot.plugin.NBotPlugin; +import net.dv8tion.jda.core.entities.MessageChannel; import java.lang.reflect.Method; import java.util.ArrayList; @@ -16,36 +19,59 @@ public class SimpleCommand { private final String name, description; private final List guilds = new ArrayList<>(), channels = new ArrayList<>(); - private final List aliases = new ArrayList<>(); + private final CommandBuilder commandBuilder; private final NBotPlugin plugin; private final Method method; private final Object object; + private final Command.ExecutorType executor; + private final boolean toPrivate, privateOnly; private String customName; private int power; - protected SimpleCommand(String name, String description, int power, List guilds, List channels, Method method, Object object, NBotPlugin plugin) + protected SimpleCommand(String name, String description, int power, List guilds, Method method, Object object, Command.ExecutorType executor, boolean toPrivate, boolean privateOnly, NBotPlugin plugin) { this.name = name.toLowerCase(); this.description = description; this.power = power; this.guilds.addAll(guilds); - this.channels.addAll(channels); this.method = method; this.object = object; this.plugin = plugin; + this.commandBuilder = null; + this.executor = executor; + this.toPrivate = toPrivate; + this.privateOnly = privateOnly; } - protected SimpleCommand(String name, String description, int power, long[] guilds, long[] channels, Method method, Object object, NBotPlugin plugin) + protected SimpleCommand(String name, String description, int power, long[] guilds, Method method, Object object, Command.ExecutorType executor, boolean toPrivate, boolean privateOnly, NBotPlugin plugin) { this.name = name.toLowerCase(); this.description = description; this.power = power; for(long l : guilds) this.guilds.add(l); - for(long l : channels) this.channels.add(l); this.method = method; this.object = object; this.plugin = plugin; + this.commandBuilder = null; + this.executor = executor; + this.toPrivate = toPrivate; + this.privateOnly = privateOnly; + } + + protected SimpleCommand(CommandBuilder commandBuilder, NBotPlugin plugin) + { + this.name = commandBuilder.getName(); + this.description = commandBuilder.getDescription(); + this.power = commandBuilder.getPower(); + this.guilds.addAll(commandBuilder.getGuilds()); + this.method = null; + this.object = null; + this.plugin = plugin; + this.commandBuilder = commandBuilder; + this.executor = commandBuilder.getExecutor(); + this.toPrivate = commandBuilder.isToPrivate(); + this.privateOnly = commandBuilder.isPrivateOnly(); } public String getName() @@ -78,6 +104,28 @@ public Method getMethod() return method; } + public CommandBuilder getCommandBuilder() + { + return commandBuilder; + } + + public boolean canExecuteToChannel(Channel channel) + { + updateChannels(); + return channels.isEmpty() || channels.contains(channel.getIdLong()); + } + + private void updateChannels() + { + if(channels.isEmpty()) return; + List clone = new ArrayList<>(channels); + for(long id : clone) + { + if(NBot.getJDA().getTextChannelById(id) == null) + channels.remove(id); + } + } + public Object getObject() { return object; @@ -93,11 +141,6 @@ public String getCustomName() return customName; } - public List getAliases() - { - return aliases; - } - public String getSimpleName() { return customName == null ? name : customName; @@ -108,50 +151,50 @@ public boolean guildCanExecute(Guild guild) return guilds.contains(guild.getIdLong()); } - public void setCustomName(String customName) + public void addChannel(MessageChannel channel) { - this.customName = customName; + if(!channels.contains(channel.getIdLong())) channels.add(channel.getIdLong()); } - public void setPower(int power) + public void addChannel(long id) { - this.power = power; + if(!channels.contains(id)) channels.add(id); } - public void addAlias(String... aliases) + public void removeChannel(MessageChannel channel) { - for(String alias : aliases) - if(!this.aliases.contains(alias)) this.aliases.add(alias); + channels.remove(channel.getIdLong()); } - public void addAlias(Collection aliases) + public void setCustomName(String customName) { - for(String alias : aliases) - if(!this.aliases.contains(alias)) this.aliases.add(alias); + this.customName = customName; } - public String getAliasesToString() + public void setPower(int power) { - StringBuilder builder = new StringBuilder(); + this.power = power; + } - for(String alias : aliases) - { - if(builder.length() > 0) builder.append(", "); - builder.append(alias); - } + public boolean isPrivate() + { + return toPrivate; + } - return builder.length() == 0 ? "Not Alias" : builder.toString(); + public boolean isPrivateOnly() + { + return privateOnly; } - public void removeAlias(String... aliases) + public boolean canExecute(Command.ExecutorType type) { - for(String alias : aliases) - if(!this.aliases.contains(alias)) this.aliases.remove(alias); + return executor == Command.ExecutorType.ALL || executor == type; } public SimpleCommand clone(Guild guild) { - return new SimpleCommand(name, description, power, Arrays.asList(guild.getIdLong()), new ArrayList<>(channels), method, object, plugin); + if(commandBuilder != null) return new SimpleCommand(commandBuilder, plugin); + return new SimpleCommand(name, description, power, Arrays.asList(guild.getIdLong()), method, object, executor, toPrivate, privateOnly, plugin); } public String toString() @@ -163,8 +206,6 @@ public String toString() .append("\",\"power\":").append(power) .append(",\"guilds\":").append(guilds.toString()) .append(",\"channels\":").append(channels.toString()) - .append(",\"aliases\":") - .append(aliases.toString().replace(" ", "").replace("[", "[\"").replace(",", "\",\"").replace("]", "\"]")) .append("}").toString(); } } diff --git a/src/main/java/fr/neutronstars/nbot/command/defaut/ConsoleCommand.java b/src/main/java/fr/neutronstars/nbot/command/defaut/ConsoleCommand.java new file mode 100644 index 0000000..6368e88 --- /dev/null +++ b/src/main/java/fr/neutronstars/nbot/command/defaut/ConsoleCommand.java @@ -0,0 +1,25 @@ +package fr.neutronstars.nbot.command.defaut; + +import fr.neutronstars.nbot.NBot; +import fr.neutronstars.nbot.command.Command; +import fr.neutronstars.nbot.entity.CommandSender; + +public class ConsoleCommand +{ + @Command(name = "stop", description = "Stop NBot API", executor = Command.ExecutorType.CONSOLE) + private void onStop(CommandSender sender) + { + sender.sendMessageToSender("Stopping bot..."); + + NBot.getPluginManager().disablePlugins(); + + for(net.dv8tion.jda.core.entities.Guild guild : NBot.getJDA().getGuilds()) + NBot.getGuild(guild).save(); + + NBot.getJDA().shutdown(); + NBot.getLogger().info(NBot.getName()+ " is down."); + + NBot.saveLogger(); + System.exit(0); + } +} diff --git a/src/main/java/fr/neutronstars/nbot/command/defaut/DefaultCommand.java b/src/main/java/fr/neutronstars/nbot/command/defaut/DefaultCommand.java index 250a8d7..6e39029 100644 --- a/src/main/java/fr/neutronstars/nbot/command/defaut/DefaultCommand.java +++ b/src/main/java/fr/neutronstars/nbot/command/defaut/DefaultCommand.java @@ -11,6 +11,7 @@ import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.entities.Role; import net.dv8tion.jda.core.entities.SelfUser; +import net.dv8tion.jda.core.entities.TextChannel; import java.awt.*; import java.util.Collection; @@ -22,37 +23,6 @@ */ public class DefaultCommand { - @Command(name = "help", description = "Send the commands list.") - private void onHelp(User user, Channel channel, Guild guild) - { - channel.sendMessageToChannel(user.getAsMention()+" check your private message !"); - - sendHelp("Default Commands", user, guild, guild.getDefaultCommands()); - - Map> pluginCommandsMap = guild.getPluginCommands(); - for(Map.Entry> entry : pluginCommandsMap.entrySet()) - sendHelp(entry.getKey().getName()+" Commands", user, guild, entry.getValue()); - } - - private void sendHelp(String title, User user, Guild guild, Collection commands) - { - EmbedBuilder builder = new EmbedBuilder(); - builder.setTitle(title); - builder.setDescription("Commands for the guild "+guild.getName()+"\n -> Prefix : "+guild.getPrefix()); - builder.setColor(Color.MAGENTA); - builder.setFooter(NBot.getName()+" API v"+NBot.getVersion()+" by "+NBot.getAuthor(), NBot.getJDA().getSelfUser().getAvatarUrl()); - - for(SimpleCommand command : commands) - { - if(!guild.hasPermission(user, command.getPower())) continue; - String value = "[>](1) Description : "+command.getDescription(); - if(command.getAliases().size() > 0) value += "\n[>](2) Aliases : "+command.getAliasesToString(); - builder.addField(command.getSimpleName(), value, false); - } - - user.sendMessageToChannel(builder.build()); - } - @Command(name="plugins", description = "Show the list of plugins.") private void onPlugins(Channel channel) { @@ -179,4 +149,76 @@ private void info(SelfUser user, Channel channel) builder.setColor(Color.RED); channel.sendMessageToChannel(builder.build()); } + + @Command(name = "deleteCommand", description = "Deletes the user's command when executed.", powers = 100) + private void onDeleteCommand(User user, String[] args, Channel channel, Guild guild, SimpleCommand simpleCommand) + { + if (args.length == 0) { + channel.sendMessageToChannel(user.getAsMention() + ", " + guild.getPrefix() + simpleCommand.getSimpleName() + " "); + return; + } + + if (args[0].equalsIgnoreCase("true") || args[0].equalsIgnoreCase("-t")) + { + guild.setDeleteCommand(true); + channel.sendMessageToChannel(user.getAsMention()+", the commands are now deleted after execution."); + return; + } + if (args[0].equalsIgnoreCase("false") || args[0].equalsIgnoreCase("-f")) + { + guild.setDeleteCommand(false); + channel.sendMessageToChannel(user.getAsMention()+", the commands are no longer deleted after execution."); + return; + } + + channel.sendMessageToChannel(user.getAsMention() + ", " + guild.getPrefix() + simpleCommand.getSimpleName() + " "); + } + + @Command(name = "cmdchan", description = "Set channels for command.", powers = 100) + private void onCmdChan(Channel channel, String[] args, Message message, User user, Guild guild, SimpleCommand simpleCommand) + { + if(args.length < 3) + { + channel.sendMessageToChannel(user.getAsMention()+", "+guild.getPrefix()+simpleCommand.getSimpleName()+" <#Channel>"); + return; + } + + if(message.getMentionedChannels().isEmpty()) + { + channel.sendMessageToChannel(user.getAsMention()+", "+guild.getPrefix()+simpleCommand.getSimpleName()+" <#Channel>"); + return; + } + + TextChannel textChannel = message.getMentionedChannels().get(0); + + boolean add; + + if(args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("-a")) + add = true; + else if(args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("-r")) + add = false; + else + { + channel.sendMessageToChannel(user.getAsMention()+", "+guild.getPrefix()+simpleCommand.getSimpleName()+" <#Channel>"); + return; + } + + SimpleCommand targetCommand = guild.getCommand(args[1].toLowerCase()); + + if(targetCommand == null) + { + channel.sendMessageToChannel(user.getAsMention()+", command not found !"); + return; + } + + if(add) + { + targetCommand.addChannel(textChannel); + channel.sendMessageToChannel(user.getAsMention()+", adding channel "+textChannel.getName()+" for the command "+targetCommand.getSimpleName()+" !"); + return; + } + + targetCommand.removeChannel(textChannel); + channel.sendMessageToChannel(user.getAsMention()+", removing channel "+textChannel.getName()+" for the command "+targetCommand.getSimpleName()+" !"); + } } diff --git a/src/main/java/fr/neutronstars/nbot/command/defaut/HelpCommand.java b/src/main/java/fr/neutronstars/nbot/command/defaut/HelpCommand.java new file mode 100644 index 0000000..f82dcdf --- /dev/null +++ b/src/main/java/fr/neutronstars/nbot/command/defaut/HelpCommand.java @@ -0,0 +1,115 @@ +package fr.neutronstars.nbot.command.defaut; + +import fr.neutronstars.nbot.NBot; +import fr.neutronstars.nbot.command.Command; +import fr.neutronstars.nbot.command.CommandManager; +import fr.neutronstars.nbot.command.SimpleCommand; +import fr.neutronstars.nbot.entity.*; +import fr.neutronstars.nbot.plugin.NBotPlugin; +import net.dv8tion.jda.core.EmbedBuilder; + +import java.awt.*; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public class HelpCommand +{ + @Command(name = "help", description = "Send the commands list.", toPrivate = true, executor = Command.ExecutorType.ALL) + private void onHelp(CommandSender sender, Channel channel, Guild guild) + { + if(sender.isConsole()) + { + sendConsoleHelp((Console) sender, CommandManager.getDefaultCommands(true), CommandManager.getPluginCommands(true)); + return; + } + + if(guild == null) + { + sendPrivateHelp("Default Commands", (User) sender, CommandManager.getDefaultCommands(false)); + + Map> pluginCommandsMap = CommandManager.getPluginCommands(false); + for(Map.Entry> entry : pluginCommandsMap.entrySet()) + sendPrivateHelp(entry.getKey().getName()+" Commands", (User) sender, CommandManager.getDefaultCommands(false)); + return; + } + + channel.sendMessageToChannel(sender.getAsMention()+" check your private message !"); + + sendGuildHelp("Default Commands", (User) sender, guild, guild.getDefaultCommands()); + + Map> pluginCommandsMap = guild.getPluginCommands(); + for(Map.Entry> entry : pluginCommandsMap.entrySet()) + sendGuildHelp(entry.getKey().getName()+" Commands", (User) sender, guild, entry.getValue()); + } + + private void sendGuildHelp(String title, User user, Guild guild, Collection commands) + { + if(commands.isEmpty()) return; + EmbedBuilder builder = new EmbedBuilder(); + builder.setTitle(title); + builder.setDescription("Commands for the guild "+guild.getName()+"\n -> Prefix : "+guild.getPrefix()); + builder.setColor(Color.MAGENTA); + builder.setFooter(NBot.getName()+" API v"+NBot.getVersion()+" by "+NBot.getAuthor(), NBot.getJDA().getSelfUser().getAvatarUrl()); + + for(SimpleCommand command : commands) + { + if(!guild.hasPermission(user, command.getPower())) continue; + String value = "[>](1) Description : "+command.getDescription(); + builder.addField(command.getSimpleName(), value, false); + } + + user.sendMessageToChannel(builder.build()); + } + + private void sendPrivateHelp(String title, User user, Collection commands) + { + if(commands.isEmpty()) return; + EmbedBuilder builder = new EmbedBuilder(); + builder.setTitle(title); + builder.setDescription("Commands for private channel."); + builder.setColor(Color.GREEN); + builder.setFooter(NBot.getName()+" API v"+NBot.getVersion()+" by "+NBot.getAuthor(), NBot.getJDA().getSelfUser().getAvatarUrl()); + + for(SimpleCommand command : commands) + { + String value = "[>](1) Description : "+command.getDescription(); + builder.addField(command.getSimpleName(), value, false); + } + + user.sendMessageToChannel(builder.build()); + } + + private void sendConsoleHelp(Console console, Collection defaultCommands, Map> pluginCommands) + { + StringBuilder builder = new StringBuilder(32); + builder.append("\n----------------------------------------"); + builder.append("\n\t\t\tCommands List"); + builder.append("\n----------------------------------------"); + + appendCommand(builder, "Default Commands", defaultCommands); + + for(Map.Entry> entry : pluginCommands.entrySet()) + appendCommand(builder, entry.getKey().getName()+" Commands", entry.getValue()); + + builder.append("\n\t").append(NBot.getName()).append(" API v").append(NBot.getVersion()).append(" by ").append(NBot.getAuthor()); + + builder.append("\n----------------------------------------"); + + console.sendMessageToSender(builder.toString()); + } + + private void appendCommand(StringBuilder builder, String title, Collection commands) + { + if(!commands.isEmpty()) { + builder.append("\n").append(title).append("\n"); + + for (SimpleCommand command : commands) { + builder.append("\n\t-> ").append(command.getSimpleName()); + builder.append("\n\t\tDescription : ").append(command.getDescription()); + } + + builder.append("\n\n----------------------------------------"); + } + } +} diff --git a/src/main/java/fr/neutronstars/nbot/entity/Console.java b/src/main/java/fr/neutronstars/nbot/entity/Console.java index 94f4f76..2453393 100644 --- a/src/main/java/fr/neutronstars/nbot/entity/Console.java +++ b/src/main/java/fr/neutronstars/nbot/entity/Console.java @@ -1,6 +1,7 @@ package fr.neutronstars.nbot.entity; import fr.neutronstars.nbot.NBot; +import fr.neutronstars.nbot.command.CommandManager; import fr.neutronstars.nbot.plugin.PluginManager; import org.slf4j.impl.NBotLogger; @@ -28,7 +29,7 @@ public String getName() public void performCommand(String command) { - + CommandManager.onConsoleCommand(this, command); } public void run() @@ -37,28 +38,14 @@ public void run() { if(scanner.hasNextLine()) { - if(scanner.nextLine().equalsIgnoreCase("stop")) - { - break; - } + performCommand(scanner.nextLine().toLowerCase()); } } - - pluginManager.disablePlugins(); - - for(net.dv8tion.jda.core.entities.Guild guild : NBot.getJDA().getGuilds()) - NBot.getGuild(guild).save(); - - NBot.getJDA().shutdown(); - logger.info(NBot.getName()+ " is down."); - - NBot.saveLogger(); - System.exit(0); } public void sendMessageToSender(String message) { - logger.info(message); + logger.console(message); } public String getAsMention() diff --git a/src/main/java/fr/neutronstars/nbot/entity/Guild.java b/src/main/java/fr/neutronstars/nbot/entity/Guild.java index 41486b5..0f6c2ad 100644 --- a/src/main/java/fr/neutronstars/nbot/entity/Guild.java +++ b/src/main/java/fr/neutronstars/nbot/entity/Guild.java @@ -440,6 +440,16 @@ public Configuration getConfiguration() return configuration; } + public boolean isDeleteCommand() + { + return commandMap.isDeleteCommand(); + } + + public void setDeleteCommand(boolean deleteCommand) + { + commandMap.setDeleteCommand(deleteCommand); + } + public int getPermissionUser(User user) { if(!usersPower.containsKey(user.getId())) setPermission(user, 0); @@ -518,7 +528,7 @@ public Collection getDefaultCommands() public Map> getPluginCommands() { - return commandMap.getPkuginCommands(); + return commandMap.getPluginCommands(); } public void setPrefix(String newPrefix) diff --git a/src/main/java/fr/neutronstars/nbot/entity/User.java b/src/main/java/fr/neutronstars/nbot/entity/User.java index 6382a11..ed0ecc1 100644 --- a/src/main/java/fr/neutronstars/nbot/entity/User.java +++ b/src/main/java/fr/neutronstars/nbot/entity/User.java @@ -1,5 +1,6 @@ package fr.neutronstars.nbot.entity; +import fr.neutronstars.nbot.command.CommandManager; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.PrivateChannel; @@ -116,7 +117,7 @@ public void sendMessageToSender(String message) public void performCommand(String command) { - + CommandManager.onPrivateCommand(this, null, command); } public boolean isUser() diff --git a/src/main/java/fr/neutronstars/nbot/listener/NBotListener.java b/src/main/java/fr/neutronstars/nbot/listener/NBotListener.java index fac13a5..749d235 100644 --- a/src/main/java/fr/neutronstars/nbot/listener/NBotListener.java +++ b/src/main/java/fr/neutronstars/nbot/listener/NBotListener.java @@ -1,6 +1,7 @@ package fr.neutronstars.nbot.listener; import fr.neutronstars.nbot.NBot; +import fr.neutronstars.nbot.command.CommandManager; import fr.neutronstars.nbot.entity.Guild; import fr.neutronstars.nbot.entity.Message; import fr.neutronstars.nbot.entity.User; @@ -8,6 +9,7 @@ import net.dv8tion.jda.core.entities.Game; import net.dv8tion.jda.core.events.ReadyEvent; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import net.dv8tion.jda.core.events.message.react.MessageReactionAddEvent; import net.dv8tion.jda.core.hooks.ListenerAdapter; import org.slf4j.impl.NBotLogger; @@ -59,7 +61,13 @@ public void onReady(ReadyEvent event) public void onMessageReceived(MessageReceivedEvent event) { - if(event.getAuthor().isBot() || event.getTextChannel() == null) return; + if(event.getAuthor().isBot()) return; + if(event.getTextChannel() == null) + { + CommandManager.onPrivateCommand(new User(event.getAuthor()), new Message(event.getMessage()), event.getMessage().getContentRaw()); + return; + } + Guild guild = NBot.getGuild(event.getGuild()); String message = event.getMessage().getContentRaw(); if(!message.startsWith(guild.getPrefix())) return; @@ -67,7 +75,7 @@ public void onMessageReceived(MessageReceivedEvent event) message = message.replaceFirst(guild.getPrefix(), ""); Message message1 = new Message(event.getMessage()); - if(guild.executeCommand(new User(event.getAuthor()), message, message1)) + if(guild.executeCommand(new User(event.getAuthor()), message, message1) && guild.isDeleteCommand()) message1.deleteTheMessage(); } @@ -81,4 +89,10 @@ private void deleteFile(File file) } file.delete(); } + + @Override + public void onMessageReactionAdd(MessageReactionAddEvent event) + { + System.out.println(event.getReactionEmote()); + } } diff --git a/src/main/java/fr/neutronstars/nbot/util/ImageBuilder.java b/src/main/java/fr/neutronstars/nbot/util/ImageBuilder.java new file mode 100644 index 0000000..815a0dd --- /dev/null +++ b/src/main/java/fr/neutronstars/nbot/util/ImageBuilder.java @@ -0,0 +1,190 @@ +package fr.neutronstars.nbot.util; + +import fr.neutronstars.nbot.NBot; +import fr.neutronstars.nbot.entity.Channel; +import fr.neutronstars.nbot.entity.Message; +import net.dv8tion.jda.core.MessageBuilder; +import net.dv8tion.jda.core.entities.Guild; +import net.dv8tion.jda.core.entities.MessageChannel; + +import javax.imageio.ImageIO; +import javax.swing.*; +import java.awt.*; +import java.awt.font.FontRenderContext; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.io.*; +import java.net.URL; +import java.net.URLConnection; + +public class ImageBuilder +{ + private final BufferedImage image; + private final Graphics graphics; + private final File folder; + + public ImageBuilder(Guild guild, int width, int length) + { + image = new BufferedImage(width, length, BufferedImage.TYPE_INT_ARGB); + graphics = image.getGraphics(); + folder = new File("tmp/"+guild.getId()); + + if(!folder.exists()) folder.mkdir(); + } + + public Graphics getGraphics() + { + return graphics; + } + + public ImageBuilder setBackground(Image image) + { + getGraphics().drawImage(image, 0, 0, this.image.getWidth(), this.image.getHeight(), null); + return this; + } + + public ImageBuilder setColor(Color color) + { + getGraphics().setColor(color); + return this; + } + + public ImageBuilder setFont(Font font) + { + getGraphics().setFont(font); + return this; + } + + public int getWidth() + { + return image.getWidth(); + } + + public int getHeight() + { + return image.getHeight(); + } + + public ImageBuilder drawString(String text, float x, float y, Font font, Color color) + { + Graphics graphics = getGraphics(); + graphics.setColor(color); + graphics.setFont(font); + + Rectangle2D rect = getTextBox(text); + + float px = ((getWidth() / 100.0f) * x) - ((float) rect.getWidth() / 2.0f); + float py = ((getHeight() / 100.0f) * y) + ((float) rect.getHeight() / 2.0f); + + graphics.drawString(text, (int) px, (int) py); + return this; + } + + public ImageBuilder fillRect(int x, int y, int width, int height) + { + return fillRect(x, y, width, height, 1); + } + + public ImageBuilder fillRect(int x, int y, int width, int height, int borderSize) + { + for(int i = 0; i < borderSize; i++) + graphics.fillRect(x+i, y+i, width - (i*2), height - (i*2)); + return this; + } + + public ImageBuilder drawString(String text, int x, int y, Color color) + { + getGraphics().setColor(color); + getGraphics().drawString(text, x, y); + return this; + } + + public ImageBuilder drawImage(Image image, int x, int y, int width, int height) + { + getGraphics().drawImage(image, x, y, width, height, null); + return this; + } + + public Rectangle2D getTextBox(String text) + { + FontRenderContext context = new FontRenderContext(getGraphics().getFont().getTransform(), false, false); + return getGraphics().getFont().getStringBounds(text, context); + } + + private File buildFile() + { + File file = createFile(folder); + + try { + ImageIO.write(image, "PNG", file); + } catch (IOException e) { + NBot.getLogger().error(e.getMessage(), e); + } + + return file; + } + + private static File createFile(File folder) + { + File file = null; + + int x = 0; + + do { + file = new File(folder, "image-creator-"+x+".png"); + x++; + }while (file.exists()); + + return file; + } + + public void sendChannel(MessageChannel channel, net.dv8tion.jda.core.entities.Message message) + { + File file = buildFile(); + channel.sendFile(file, message).queue(msg -> file.delete()); + } + + public void sendChannel(MessageChannel channel) + { + sendChannel(channel, (net.dv8tion.jda.core.entities.Message) null); + } + + public void sendChannel(MessageChannel channel, String message) + { + sendChannel(channel, new MessageBuilder(message).build()); + } + + public static Image getImageURL(Guild guild, String sourceUrl) + { + URL imageUrl; + URLConnection uc = null; + try { + imageUrl = new URL(sourceUrl); + uc = imageUrl.openConnection(); + uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); + } catch (IOException e) { + e.printStackTrace(); + } + + File folder = new File("tmp/"+guild.getId()); + if(!folder.exists()) folder.mkdir(); + + File file = createFile(folder); + + try (InputStream imageReader = new BufferedInputStream(uc.getInputStream()); + OutputStream imageWriter = new BufferedOutputStream(new FileOutputStream(file))){ + int readByte; + while ((readByte = imageReader.read()) != -1) { + imageWriter.write(readByte); + } + imageWriter.flush(); + }catch (IOException e) { + System.out.println(e.getMessage()); + } + + Image image = new ImageIcon(file.getAbsolutePath()).getImage(); + file.delete(); + + return image; + } +} diff --git a/src/main/java/org/slf4j/impl/NBotLogger.java b/src/main/java/org/slf4j/impl/NBotLogger.java index a277cd1..c2a172e 100644 --- a/src/main/java/org/slf4j/impl/NBotLogger.java +++ b/src/main/java/org/slf4j/impl/NBotLogger.java @@ -12,6 +12,11 @@ import java.text.SimpleDateFormat; import java.util.Date; +/** + * Origin Code by SLF4J-Simple [Link=https://github.com/qos-ch/slf4j/tree/master/slf4j-simple] + * Modified by NeutronStars + */ + public class NBotLogger implements Logger { protected static final SimpleDateFormat simpleDate = new SimpleDateFormat("HH:mm:ss"); @@ -20,6 +25,7 @@ public class NBotLogger implements Logger protected static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT; protected static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT; protected static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT; + protected static final int LOG_LEVEL_CONSOLE = 50; private static final String ANSI_RESET = "\u001B[0m"; @@ -116,7 +122,7 @@ private String formatLine(String date, String level, String message) { return lineFormat.replace("{DATE}", date) .replace("{LEVEL}", level).replace("{NAME}", computeShortName()) - .replace("{MESSAGE}", message); + .replace("{MESSAGE}", String.valueOf(message)); } protected String renderLevel(int level) { @@ -131,6 +137,8 @@ protected String renderLevel(int level) { return "WARN"; case LOG_LEVEL_ERROR: return "ERROR"; + case LOG_LEVEL_CONSOLE: + return "CONSOLE"; } throw new IllegalStateException("Unrecognized level [" + level + "]"); } @@ -145,8 +153,6 @@ void write(String date, String strLevel, int level, String buf, Throwable t) { writeThrowable(date, strLevel, color, t, targetStream); targetStream.flush(); - - } protected void writeThrowable(String date, String strLevel, String color, Throwable t, PrintStream targetStream) { @@ -177,6 +183,8 @@ private String getColorByLevel(int level) return NBotLogger.ANSI_YELLOW; case LOG_LEVEL_ERROR: return NBotLogger.ANSI_RED; + case LOG_LEVEL_CONSOLE: + return NBotLogger.ANSI_GREEN; } return NBotLogger.ANSI_WHITE; } @@ -336,6 +344,11 @@ public void info(String msg) { log(LOG_LEVEL_INFO, msg, null); } + public void console(String msg) + { + log(LOG_LEVEL_CONSOLE, msg, null); + } + /** * Perform single parameter substitution before logging the message of level * INFO according to the format outlined above. diff --git a/src/main/java/org/slf4j/impl/NBotLoggerFactory.java b/src/main/java/org/slf4j/impl/NBotLoggerFactory.java index 45b6d6a..b103d98 100644 --- a/src/main/java/org/slf4j/impl/NBotLoggerFactory.java +++ b/src/main/java/org/slf4j/impl/NBotLoggerFactory.java @@ -10,6 +10,11 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +/** + * Origin Code by SLF4J-Simple [Link=https://github.com/qos-ch/slf4j/tree/master/slf4j-simple] + * Modified by NeutronStars + */ + public class NBotLoggerFactory implements ILoggerFactory { private final ConcurrentMap loggerMap = new ConcurrentHashMap<>(); diff --git a/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index 36669c6..9d678ab 100644 --- a/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -2,6 +2,11 @@ import org.slf4j.spi.LoggerFactoryBinder; +/** + * Origin Code by SLF4J-Simple [Link=https://github.com/qos-ch/slf4j/tree/master/slf4j-simple] + * Modified by NeutronStars + */ + public class StaticLoggerBinder implements LoggerFactoryBinder { private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); diff --git a/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/src/main/java/org/slf4j/impl/StaticMDCBinder.java index ac30ae7..6d87d72 100644 --- a/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -3,6 +3,11 @@ import org.slf4j.helpers.NOPMDCAdapter; import org.slf4j.spi.MDCAdapter; +/** + * Origin Code by SLF4J-Simple [Link=https://github.com/qos-ch/slf4j/tree/master/slf4j-simple] + * Modified by NeutronStars + */ + public class StaticMDCBinder { /**