From 6881029e0978acf423b6ad1ec39a02a6d0481f5a Mon Sep 17 00:00:00 2001 From: NeutronStars Date: Sun, 18 Mar 2018 15:56:19 +0100 Subject: [PATCH] Update NBot 2.0.4 --- src/main/java/fr/neutronstars/nbot/NBot.java | 2 +- .../java/fr/neutronstars/nbot/NBotServer.java | 5 + .../java/fr/neutronstars/nbot/NBotStart.java | 9 +- .../neutronstars/nbot/command/CommandMap.java | 41 +++++- .../nbot/command/defaut/DefaultCommand.java | 28 ++-- .../fr/neutronstars/nbot/entity/Guild.java | 11 ++ .../nbot/listener/NBotListener.java | 2 +- src/main/java/org/slf4j/impl/NBotLogger.java | 130 +++++++++++++++--- 8 files changed, 193 insertions(+), 35 deletions(-) diff --git a/src/main/java/fr/neutronstars/nbot/NBot.java b/src/main/java/fr/neutronstars/nbot/NBot.java index d5fdac5..40b1ef0 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.3", AUTHOR = "NeutronStars"; + private static final String NAME = "NBot", VERSION = "2.0.4", AUTHOR = "NeutronStars"; private static final NBotLogger logger = StaticLoggerBinder.getSingleton().getLoggerFactory().getLogger("NBot"); private static NBotServer server; diff --git a/src/main/java/fr/neutronstars/nbot/NBotServer.java b/src/main/java/fr/neutronstars/nbot/NBotServer.java index a343813..d1c0728 100644 --- a/src/main/java/fr/neutronstars/nbot/NBotServer.java +++ b/src/main/java/fr/neutronstars/nbot/NBotServer.java @@ -41,6 +41,11 @@ protected NBotServer(Configuration configuration, PluginManager pluginManager) t .addEventListener(new NBotListener(pluginManager)).buildAsync(); } + public NBotLogger getLogger() + { + return logger; + } + public JDA getJDA() { return jda; diff --git a/src/main/java/fr/neutronstars/nbot/NBotStart.java b/src/main/java/fr/neutronstars/nbot/NBotStart.java index 11fd3d7..1a295e4 100644 --- a/src/main/java/fr/neutronstars/nbot/NBotStart.java +++ b/src/main/java/fr/neutronstars/nbot/NBotStart.java @@ -20,13 +20,15 @@ public static void main(String... args) { System.setProperty("file.encoding", "UTF-8"); - logger.info(String.format("Starting %1$s v%2$s by %3$s...", NBot.getName(), NBot.getVersion(), NBot.getAuthor())); - loadFolders("guilds", "plugins", "config"); Configuration configuration = loadConfiguration(); setDefaultConfiguration(configuration); + NBotLogger.load(configuration); + + logger.info(String.format("Starting %1$s v%2$s by %3$s...", NBot.getName(), NBot.getVersion(), NBot.getAuthor())); + PluginManager pluginManager = new PluginManager(configuration.getString("loadedFormat"), configuration.getString("enabledFormat"), configuration.getString("disabledFormat")); CommandManager.registerCommand(new DefaultCommand(), null); pluginManager.registerCommands(); @@ -96,6 +98,9 @@ private static void setDefaultConfiguration(Configuration configuration) if(!configuration.has("enabledFormat")) configuration.set("enabledFormat", "%1$s v%2$s by %3$s is enabled."); if(!configuration.has("disabledFormat")) configuration.set("disabledFormat", "%1$s v%2$s by %3$s is disabled."); + if(!configuration.has("loggerTimeFormat")) configuration.set("loggerTimeFormat", "HH:mm:ss"); + if(!configuration.has("loggerLineFormat")) configuration.set("loggerLineFormat", "[{DATE}] [{LEVEL}-{NAME}] {MESSAGE}"); + configuration.save(); } diff --git a/src/main/java/fr/neutronstars/nbot/command/CommandMap.java b/src/main/java/fr/neutronstars/nbot/command/CommandMap.java index bcde90d..a741ac5 100644 --- a/src/main/java/fr/neutronstars/nbot/command/CommandMap.java +++ b/src/main/java/fr/neutronstars/nbot/command/CommandMap.java @@ -6,6 +6,7 @@ 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 fr.neutronstars.nbot.util.Configuration; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.entities.*; @@ -14,7 +15,9 @@ import java.io.File; import java.lang.reflect.Parameter; +import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -128,15 +131,21 @@ public boolean onCommand(User user, String command, Message message) Object[] objects = getCommands(command.split(" ")); if(objects[0] == null) return false; - NBot.getLogger().info("[Command] "+user.getName() + " -> "+command); - SimpleCommand simpleCommand = (SimpleCommand)objects[0]; if(!guild.hasPermission(user, simpleCommand.getPower())) return false; + if(simpleCommand.getPlugin() != null) + simpleCommand.getPlugin().getLogger().info("[Command] "+user.getName() + " -> "+command); + else + NBot.getLogger().info("[Command] "+user.getName() + " -> "+command); + try { execute(simpleCommand, command, (String[]) objects[1], message, user); }catch(Exception e) { - NBot.getLogger().error(e.getMessage(), e); + if(simpleCommand.getPlugin() != null) + simpleCommand.getPlugin().getLogger().error(e.getMessage(), e); + else + NBot.getLogger().error(e.getMessage(), e); } return true; } @@ -155,6 +164,32 @@ public List getCommands() return new ArrayList<>(commands); } + public List getDefaultCommands() + { + List defaultCommands = new ArrayList<>(); + List commands = getCommands(); + + for(SimpleCommand command : commands) + if(command.getPlugin() == null) defaultCommands.add(command); + + return defaultCommands; + } + + public Map> getPkuginCommands() + { + Map> pluginCommandMap = new HashMap<>(); + List commands = getCommands(); + + 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; + } + private void execute(SimpleCommand simpleCommand, String command, String[] args, Message message, User user) throws Exception{ Parameter[] parameters = simpleCommand.getMethod().getParameters(); Object[] objects = new Object[parameters.length]; 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 4ab29cf..250a8d7 100644 --- a/src/main/java/fr/neutronstars/nbot/command/defaut/DefaultCommand.java +++ b/src/main/java/fr/neutronstars/nbot/command/defaut/DefaultCommand.java @@ -15,21 +15,32 @@ import java.awt.*; import java.util.Collection; import java.util.List; +import java.util.Map; /** * Created by NeutronStars on 21/09/2017 */ public class DefaultCommand { - @Command(name = "help") + @Command(name = "help", description = "Send the commands list.") private void onHelp(User user, Channel channel, Guild guild) { - Collection commands = guild.getCommands(); + 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("Commands List"); + builder.setTitle(title); builder.setDescription("Commands for the guild "+guild.getName()+"\n -> Prefix : "+guild.getPrefix()); builder.setColor(Color.MAGENTA); - builder.setFooter("API "+NBot.getName()+" v"+NBot.getVersion()+" by "+NBot.getAuthor(), null); + builder.setFooter(NBot.getName()+" API v"+NBot.getVersion()+" by "+NBot.getAuthor(), NBot.getJDA().getSelfUser().getAvatarUrl()); for(SimpleCommand command : commands) { @@ -40,10 +51,9 @@ private void onHelp(User user, Channel channel, Guild guild) } user.sendMessageToChannel(builder.build()); - channel.sendMessageToChannel(user.getAsMention()+" check your private message !"); } - @Command(name="plugins") + @Command(name="plugins", description = "Show the list of plugins.") private void onPlugins(Channel channel) { Collection plugins = NBot.getPluginManager().getPlugins(); @@ -64,7 +74,7 @@ private void onPlugins(Channel channel) channel.sendMessageToChannel(builder.build()); } - @Command(name = "prefix", powers = 100) + @Command(name = "prefix", powers = 100, description = "Change the prefix for the commands of the guild.") private void onPrefix(Guild guild, Channel channel, String[] args) { String prefix = args.length == 0 || args[0].equalsIgnoreCase("null") ? null : args[0]; @@ -72,7 +82,7 @@ private void onPrefix(Guild guild, Channel channel, String[] args) channel.sendMessageToChannel("Prefix modified -> "+prefix); } - @Command(name="power", powers = 100) + @Command(name="power", powers = 100, description = "Change the permissions of commands, users or role of the guild.") private void onPower(SimpleCommand command, User user1, Message message, String[] args, Guild guild) { if(args.length < 2) @@ -121,7 +131,7 @@ private void onPower(SimpleCommand command, User user1, Message message, String[ message.getMessageChannel().sendMessageToChannel(builder.toString()); } - @Command(name = "commandname", powers = 100) + @Command(name = "commandname", powers = 100, description = "change the commands name of the guild.") private void onCommandName(SimpleCommand simpleCommand, User user, String[] args, Guild guild, Channel channel) { if(args.length < 2) diff --git a/src/main/java/fr/neutronstars/nbot/entity/Guild.java b/src/main/java/fr/neutronstars/nbot/entity/Guild.java index 0e72573..41486b5 100644 --- a/src/main/java/fr/neutronstars/nbot/entity/Guild.java +++ b/src/main/java/fr/neutronstars/nbot/entity/Guild.java @@ -3,6 +3,7 @@ import fr.neutronstars.nbot.NBot; import fr.neutronstars.nbot.command.CommandMap; import fr.neutronstars.nbot.command.SimpleCommand; +import fr.neutronstars.nbot.plugin.NBotPlugin; import fr.neutronstars.nbot.util.Configuration; import fr.neutronstars.nbot.util.JSONReader; import fr.neutronstars.nbot.util.JSONWriter; @@ -510,6 +511,16 @@ public Collection getCommands() return commandMap.getCommands(); } + public Collection getDefaultCommands() + { + return commandMap.getDefaultCommands(); + } + + public Map> getPluginCommands() + { + return commandMap.getPkuginCommands(); + } + public void setPrefix(String newPrefix) { commandMap.setPrefix(newPrefix); diff --git a/src/main/java/fr/neutronstars/nbot/listener/NBotListener.java b/src/main/java/fr/neutronstars/nbot/listener/NBotListener.java index 34637d8..fac13a5 100644 --- a/src/main/java/fr/neutronstars/nbot/listener/NBotListener.java +++ b/src/main/java/fr/neutronstars/nbot/listener/NBotListener.java @@ -42,7 +42,7 @@ public void onReady(ReadyEvent event) String playing = NBot.getConfiguration().getString("playing"); if(playing != null && !playing.equalsIgnoreCase("null")) - NBot.getJDA().getPresence().setGame(Game.listening(playing)); + NBot.getJDA().getPresence().setGame(Game.playing(playing)); logger.info(builder.toString()); diff --git a/src/main/java/org/slf4j/impl/NBotLogger.java b/src/main/java/org/slf4j/impl/NBotLogger.java index ed3aafd..a277cd1 100644 --- a/src/main/java/org/slf4j/impl/NBotLogger.java +++ b/src/main/java/org/slf4j/impl/NBotLogger.java @@ -1,5 +1,6 @@ package org.slf4j.impl; +import fr.neutronstars.nbot.util.Configuration; import org.slf4j.Logger; import org.slf4j.Marker; import org.slf4j.event.LoggingEvent; @@ -20,11 +21,28 @@ public class NBotLogger implements Logger protected static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT; protected static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT; + + private static final String ANSI_RESET = "\u001B[0m"; + private static final String ANSI_BLACK = "\u001B[30m"; + private static final String ANSI_RED = "\u001B[31m"; + private static final String ANSI_GREEN = "\u001B[32m"; + private static final String ANSI_YELLOW = "\u001B[33m"; + private static final String ANSI_BLUE = "\u001B[34m"; + private static final String ANSI_PURPLE = "\u001B[35m"; + private static final String ANSI_CYAN = "\u001B[36m"; + private static final String ANSI_WHITE = "\u001B[37m"; + + private static String lineFormat = "[{DATE}] [{LEVEL}-{NAME}] {MESSAGE}"; + private final NBotLoggerFactory source; private final String name; /** The current log level */ - protected int currentLogLevel = LOG_LEVEL_INFO; + private boolean debugLevel = false; + private boolean traceLevel = false; + private boolean infoLevel = true; + private boolean warnLevel = true; + private boolean errorLevel = true; public NBotLogger(String name, NBotLoggerFactory source) { @@ -38,6 +56,38 @@ public String getName() return name; } + public void setTraceLevel(boolean traceLevel) + { + this.traceLevel = traceLevel; + } + + public void setDebugLevel(boolean debugLevel) + { + this.debugLevel = debugLevel; + } + + public void setInfoLevel(boolean infoLevel) + { + this.infoLevel = infoLevel; + } + + public void setWarnLevel(boolean warnLevel) + { + this.warnLevel = warnLevel; + } + + public void setErrorLevel(boolean errorLevel) + { + this.errorLevel = errorLevel; + } + + public static void load(Configuration configuration) + { + if(configuration == null) return; + if(configuration.has("loggerTimeFormat")) simpleDate.applyPattern(configuration.getString("loggerTimeFormat")); + if(configuration.has("loggerLineFormat")) lineFormat = configuration.getString("loggerLineFormat"); + } + /** * This is our internal implementation for logging regular * (non-parameterized) log messages. @@ -54,18 +104,19 @@ private void log(int level, String message, Throwable t) { return; } - StringBuilder buf = new StringBuilder(32); - - // Append date-time if so configured - buf.append("[").append(simpleDate.format(new Date())).append("] "); - - // Append a readable representation of the log level and name - String levelStr = renderLevel(level); - buf.append("[").append(levelStr).append("-").append(computeShortName()).append("] "); + String date = simpleDate.format(new Date()); + String strLevel = renderLevel(level); + String line = formatLine(date, strLevel, message); // Append the message - buf.append(message); - write(buf, t); + write(date, strLevel, level, line, t); + } + + private String formatLine(String date, String level, String message) + { + return lineFormat.replace("{DATE}", date) + .replace("{LEVEL}", level).replace("{NAME}", computeShortName()) + .replace("{MESSAGE}", message); } protected String renderLevel(int level) { @@ -84,21 +135,50 @@ protected String renderLevel(int level) { throw new IllegalStateException("Unrecognized level [" + level + "]"); } - void write(StringBuilder buf, Throwable t) { + void write(String date, String strLevel, int level, String buf, Throwable t) { PrintStream targetStream = System.out; - String msg = buf.toString(); - targetStream.println(msg); - writeThrowable(t, targetStream); + String color = getColorByLevel(level); + + targetStream.println(color + buf); + source.log(buf); + + writeThrowable(date, strLevel, color, t, targetStream); targetStream.flush(); - source.log(msg); + } - protected void writeThrowable(Throwable t, PrintStream targetStream) { + protected void writeThrowable(String date, String strLevel, String color, Throwable t, PrintStream targetStream) { if (t != null) { - t.printStackTrace(targetStream); + StringBuilder builder = new StringBuilder(); + + builder.append(formatLine(date, strLevel, t.toString())); + + for (StackTraceElement traceElement : t.getStackTrace()) + builder.append("\n").append(formatLine(date, strLevel, "\tat "+traceElement.toString())); + + String msg = builder.toString(); + targetStream.println(color + msg); + source.log(msg); + } + } + + private String getColorByLevel(int level) + { + switch (level) { + case LOG_LEVEL_TRACE: + return NBotLogger.ANSI_CYAN; + case LOG_LEVEL_DEBUG: + return NBotLogger.ANSI_PURPLE; + case LOG_LEVEL_INFO: + return NBotLogger.ANSI_BLUE; + case LOG_LEVEL_WARN: + return NBotLogger.ANSI_YELLOW; + case LOG_LEVEL_ERROR: + return NBotLogger.ANSI_RED; } + return NBotLogger.ANSI_WHITE; } private String getFormattedDate() { @@ -144,7 +224,19 @@ private void formatAndLog(int level, String format, Object... arguments) { protected boolean isLevelEnabled(int logLevel) { // log level are numerically ordered so can use simple numeric // comparison - return (logLevel >= currentLogLevel); + switch (logLevel) { + case LOG_LEVEL_TRACE: + return traceLevel; + case LOG_LEVEL_DEBUG: + return debugLevel; + case LOG_LEVEL_INFO: + return infoLevel; + case LOG_LEVEL_WARN: + return warnLevel; + case LOG_LEVEL_ERROR: + return errorLevel; + } + return true; } /** Are {@code trace} messages currently enabled? */