Reformatting code

This commit is contained in:
2023-11-21 22:04:38 +02:00
parent 79ecff971b
commit 944d59d9a3
37 changed files with 509 additions and 486 deletions

View File

@@ -5,12 +5,12 @@ using PluginManager.Others;
namespace DiscordBot.Bot.Actions;
public class Clear : ICommandAction
public class Clear: ICommandAction
{
public string ActionName => "clear";
public string Description => "Clears the console";
public string Usage => "clear";
public InternalActionRunType RunType => InternalActionRunType.ON_CALL;
public string ActionName => "clear";
public string Description => "Clears the console";
public string Usage => "clear";
public InternalActionRunType RunType => InternalActionRunType.ON_CALL;
public Task Execute(string[] args)
{

View File

@@ -6,12 +6,12 @@ using PluginManager.Others;
namespace DiscordBot.Bot.Actions;
public class Exit : ICommandAction
public class Exit: ICommandAction
{
public string ActionName => "exit";
public string Description => "Exits the bot and saves the config. Use exit help for more info.";
public string Usage => "exit [help|force (-f)]";
public InternalActionRunType RunType => InternalActionRunType.ON_CALL;
public string ActionName => "exit";
public string Description => "Exits the bot and saves the config. Use exit help for more info.";
public string Usage => "exit [help|force (-f)]";
public InternalActionRunType RunType => InternalActionRunType.ON_CALL;
public async Task Execute(string[] args)
{
@@ -23,7 +23,7 @@ public class Exit : ICommandAction
}
else
{
switch ( args[0] )
switch (args[0])
{
case "help":
Console.WriteLine("Usage : exit [help|force]");

View File

@@ -19,20 +19,20 @@ internal static class PluginMethods
internal static async Task List(PluginsManager manager)
{
var data = await ConsoleUtilities.ExecuteWithProgressBar(manager.GetAvailablePlugins(), "Loading plugins...");
TableData tableData = new(new List<string> { "Name", "Description", "Type", "Version" });
foreach (var plugin in data) tableData.AddRow(plugin);
tableData.HasRoundBorders = false;
tableData.PrintAsTable();
}
internal static async Task RefreshPlugins(bool quiet)
{
await Program.internalActionManager.Execute("plugin", "load", quiet ? "-q" : string.Empty);
await Program.internalActionManager.Refresh();
}
internal static async Task DownloadPlugin(PluginsManager manager, string pluginName)
{
var pluginData = await manager.GetPluginLinkByName(pluginName);
@@ -42,30 +42,32 @@ internal static class PluginMethods
return;
}
var pluginType = pluginData[0];
var pluginLink = pluginData[1];
var pluginType = pluginData[0];
var pluginLink = pluginData[1];
var pluginRequirements = pluginData[2];
await AnsiConsole.Progress()
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn()
})
.StartAsync(async ctx =>
{
var downloadTask = ctx.AddTask("Downloading plugin...");
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn()
}
)
.StartAsync(async ctx =>
{
var downloadTask = ctx.AddTask("Downloading plugin...");
IProgress<float> progress = new Progress<float>(p => { downloadTask.Value = p; });
IProgress<float> progress = new Progress<float>(p => { downloadTask.Value = p; });
await ServerCom.DownloadFileAsync(pluginLink, $"./Data/{pluginType}s/{pluginName}.dll", progress);
downloadTask.Increment(100);
ctx.Refresh();
});
await ServerCom.DownloadFileAsync(pluginLink, $"./Data/{pluginType}s/{pluginName}.dll", progress);
downloadTask.Increment(100);
ctx.Refresh();
}
);
if (pluginRequirements == string.Empty)
{
@@ -75,150 +77,162 @@ internal static class PluginMethods
}
List<string> requirementsUrLs = new();
await AnsiConsole.Progress()
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn()
})
.StartAsync(async ctx =>
{
var gatherInformationTask = ctx.AddTask("Gathering info...");
gatherInformationTask.IsIndeterminate = true;
requirementsUrLs = await ServerCom.ReadTextFromURL(pluginRequirements);
gatherInformationTask.Increment(100);
});
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn()
}
)
.StartAsync(async ctx =>
{
var gatherInformationTask = ctx.AddTask("Gathering info...");
gatherInformationTask.IsIndeterminate = true;
requirementsUrLs = await ServerCom.ReadTextFromURL(pluginRequirements);
gatherInformationTask.Increment(100);
}
);
List<Tuple<ProgressTask, IProgress<float>, string, string>> downloadTasks = new();
await AnsiConsole.Progress()
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn()
})
.StartAsync(async ctx =>
{
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn()
}
)
.StartAsync(async ctx =>
{
foreach (var info in requirementsUrLs)
{
if (info.Length < 2) continue;
string[] data = info.Split(',');
string url = data[0];
string fileName = data[1];
var task = ctx.AddTask($"Downloading {fileName}: ");
IProgress<float> progress = new Progress<float>(p =>
{
task.Value = p;
});
task.IsIndeterminate = true;
downloadTasks.Add(new Tuple<ProgressTask, IProgress<float>, string, string>(task, progress, url, fileName));
}
foreach (var info in requirementsUrLs)
{
if (info.Length < 2) continue;
string[] data = info.Split(',');
string url = data[0];
string fileName = data[1];
if (!int.TryParse(Config.AppSettings["MaxParallelDownloads"], out int maxParallelDownloads))
{
maxParallelDownloads = 5;
Config.AppSettings.Add("MaxParallelDownloads", "5");
await Config.AppSettings.SaveToFile();
}
var options = new ParallelOptions()
{
MaxDegreeOfParallelism = maxParallelDownloads,
TaskScheduler = TaskScheduler.Default
};
var task = ctx.AddTask($"Downloading {fileName}: ");
IProgress<float> progress = new Progress<float>(p =>
{
task.Value = p;
}
);
await Parallel.ForEachAsync(downloadTasks, options, async (tuple, token) =>
{
tuple.Item1.IsIndeterminate = false;
await ServerCom.DownloadFileAsync(tuple.Item3, $"./{tuple.Item4}", tuple.Item2);
});
task.IsIndeterminate = true;
downloadTasks.Add(new Tuple<ProgressTask, IProgress<float>, string, string>(task, progress, url, fileName));
}
if (!int.TryParse(Config.AppSettings["MaxParallelDownloads"], out int maxParallelDownloads))
{
maxParallelDownloads = 5;
Config.AppSettings.Add("MaxParallelDownloads", "5");
await Config.AppSettings.SaveToFile();
}
var options = new ParallelOptions()
{
MaxDegreeOfParallelism = maxParallelDownloads,
TaskScheduler = TaskScheduler.Default
};
await Parallel.ForEachAsync(downloadTasks, options, async (tuple, token) =>
{
tuple.Item1.IsIndeterminate = false;
await ServerCom.DownloadFileAsync(tuple.Item3, $"./{tuple.Item4}", tuple.Item2);
}
);
}
);
});
await RefreshPlugins(false);
}
internal static async Task<bool> LoadPlugins(string[] args)
{
var loader = new PluginLoader(Config.DiscordBot.client);
if (args.Length == 2 && args[1] == "-q")
{
loader.LoadPlugins();
return true;
}
var loader = new PluginLoader(Config.DiscordBot.client);
if (args.Length == 2 && args[1] == "-q")
{
loader.LoadPlugins();
return true;
}
var cc = Console.ForegroundColor;
loader.onCMDLoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
{
Config.Logger.Log("Successfully loaded command : " + name, source: typeof(ICommandAction),
type: LogType.INFO);
}
var cc = Console.ForegroundColor;
loader.onCMDLoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
{
Config.Logger.Log("Successfully loaded command : " + name, source: typeof(ICommandAction),
type: LogType.INFO
);
}
else
{
Config.Logger.Log("Failed to load command : " + name + " because " + exception?.Message,
source: typeof(ICommandAction), type: LogType.ERROR);
}
else
{
Config.Logger.Log("Failed to load command : " + name + " because " + exception?.Message,
source: typeof(ICommandAction), type: LogType.ERROR
);
}
Console.ForegroundColor = cc;
};
loader.onEVELoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
Console.ForegroundColor = cc;
};
loader.onEVELoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
{
Config.Logger.Log("Successfully loaded event : " + name, source: typeof(ICommandAction),
type: LogType.INFO);
}
else
{
Config.Logger.Log("Failed to load event : " + name + " because " + exception?.Message,
source: typeof(ICommandAction), type: LogType.ERROR);
}
if (success)
{
Config.Logger.Log("Successfully loaded event : " + name, source: typeof(ICommandAction),
type: LogType.INFO
);
}
else
{
Config.Logger.Log("Failed to load event : " + name + " because " + exception?.Message,
source: typeof(ICommandAction), type: LogType.ERROR
);
}
Console.ForegroundColor = cc;
};
Console.ForegroundColor = cc;
};
loader.onSLSHLoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
loader.onSLSHLoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
{
Config.Logger.Log("Successfully loaded slash command : " + name, source: typeof(ICommandAction),
type: LogType.INFO);
}
else
{
Config.Logger.Log("Failed to load slash command : " + name + " because " + exception?.Message,
source: typeof(ICommandAction), type: LogType.ERROR);
}
if (success)
{
Config.Logger.Log("Successfully loaded slash command : " + name, source: typeof(ICommandAction),
type: LogType.INFO
);
}
else
{
Config.Logger.Log("Failed to load slash command : " + name + " because " + exception?.Message,
source: typeof(ICommandAction), type: LogType.ERROR
);
}
Console.ForegroundColor = cc;
};
Console.ForegroundColor = cc;
};
loader.LoadPlugins();
Console.ForegroundColor = cc;
return true;
loader.LoadPlugins();
Console.ForegroundColor = cc;
return true;
}
}

View File

@@ -5,26 +5,26 @@ namespace DiscordBot.Bot.Actions.Extra;
internal static class SettingsConfigExtra
{
internal static void SetSettings(string key, params string[] value)
internal static void SetSettings(string key, params string[] value)
{
if (key is null) return;
if (value is null) return;
if (!Config.AppSettings.ContainsKey(key))
return;
Config.AppSettings[key] = string.Join(' ', value);
// Config.AppSettings.SaveToFile().Wait();
// Config.AppSettings.SaveToFile().Wait();
}
internal static void RemoveSettings(string key)
{
if (key is null) return;
if(!Config.AppSettings.ContainsKey(key))
if (!Config.AppSettings.ContainsKey(key))
return;
Config.AppSettings.Remove(key);
}
@@ -33,11 +33,11 @@ internal static class SettingsConfigExtra
if (key is null) return;
if (value is null) return;
if (Config.AppSettings.ContainsKey(key))
return;
Config.AppSettings.Add(key, string.Join(' ', value));
// Config.AppSettings.SaveToFile().Wait();
}
}
}

View File

@@ -7,7 +7,7 @@ using PluginManager.Others;
namespace DiscordBot.Bot.Actions;
public class Help : ICommandAction
public class Help: ICommandAction
{
public string ActionName => "help";
@@ -34,8 +34,8 @@ public class Help : ICommandAction
items.Add(new[] { "-", "-", "-" });
ConsoleUtilities.FormatAndAlignTable(items,
TableFormat.CENTER_EACH_COLUMN_BASED
);
TableFormat.CENTER_EACH_COLUMN_BASED
);
return;
}
@@ -56,7 +56,7 @@ public class Help : ICommandAction
};
ConsoleUtilities.FormatAndAlignTable(actionData,
TableFormat.CENTER_EACH_COLUMN_BASED
);
TableFormat.CENTER_EACH_COLUMN_BASED
);
}
}

View File

@@ -12,7 +12,7 @@ using Spectre.Console;
namespace DiscordBot.Bot.Actions;
public class Plugin : ICommandAction
public class Plugin: ICommandAction
{
private bool pluginsLoaded;
public string ActionName => "plugin";
@@ -46,7 +46,7 @@ public class Plugin : ICommandAction
case "refresh":
await PluginMethods.RefreshPlugins(true);
break;
case "list":
await PluginMethods.List(manager);
break;
@@ -56,7 +56,7 @@ public class Plugin : ICommandAction
Config.Logger.Log("Plugins already loaded", source: typeof(ICommandAction), type: LogType.WARNING);
break;
}
if (Config.DiscordBot is null)
{
Config.Logger.Log("DiscordBot is null", source: typeof(ICommandAction), type: LogType.WARNING);
@@ -84,4 +84,4 @@ public class Plugin : ICommandAction
break;
}
}
}
}

View File

@@ -7,7 +7,7 @@ using PluginManager.Others;
namespace DiscordBot.Bot.Actions;
public class SettingsConfig : ICommandAction
public class SettingsConfig: ICommandAction
{
public string ActionName => "config";
public string Description => "Change the settings of the bot";
@@ -19,7 +19,7 @@ public class SettingsConfig : ICommandAction
{
foreach (var settings in Config.AppSettings)
Console.WriteLine(settings.Key + ": " + settings.Value);
return Task.CompletedTask;
}
@@ -27,25 +27,25 @@ public class SettingsConfig : ICommandAction
{
case "-s":
case "set":
if(args.Length < 3)
if (args.Length < 3)
return Task.CompletedTask;
SettingsConfigExtra.SetSettings(args[1],args[2..]);
SettingsConfigExtra.SetSettings(args[1], args[2..]);
break;
case "-r":
case "remove":
if(args.Length < 2)
if (args.Length < 2)
return Task.CompletedTask;
SettingsConfigExtra.RemoveSettings(args[1]);
break;
case "-a":
case "add":
if(args.Length < 3)
if (args.Length < 3)
return Task.CompletedTask;
SettingsConfigExtra.AddSettings(args[1], args[2..]);
break;
case "-h":
case "-help":
Console.WriteLine("Options:");
@@ -54,14 +54,14 @@ public class SettingsConfig : ICommandAction
Console.WriteLine("-a <settingName> <newValue>: Add a setting");
Console.WriteLine("-h: Show this help message");
break;
default:
Console.WriteLine("Invalid option");
return Task.CompletedTask;
}
return Task.CompletedTask;
}
}
}

View File

@@ -10,7 +10,7 @@ namespace DiscordBot.Bot.Commands;
/// <summary>
/// The help command
/// </summary>
internal class Help : DBCommand
internal class Help: DBCommand
{
/// <summary>
/// Command name
@@ -76,7 +76,7 @@ internal class Help : DBCommand
var embedBuilder = new EmbedBuilder();
var cmd = PluginLoader.Commands.Find(p => p.Command == command ||
p.Aliases is not null && p.Aliases.Contains(command)
);
);
if (cmd == null) return null;
embedBuilder.AddField("Usage", Config.AppSettings["prefix"] + cmd.Usage);

View File

@@ -8,11 +8,11 @@ using PluginManager.Others;
namespace DiscordBot.Bot.Commands.SlashCommands;
public class Help : DBSlashCommand
public class Help: DBSlashCommand
{
public string Name => "help";
public string Name => "help";
public string Description => "This command allows you to check all loaded commands";
public bool canUseDM => true;
public bool canUseDM => true;
public List<SlashCommandOptionBuilder> Options =>
new()

View File

@@ -29,13 +29,13 @@
<None Remove="Data\**"/>
<None Remove="obj\**"/>
<None Remove="Output\**"/>
<None Remove="builder.bat" />
<None Remove="builder.sh" />
<None Remove="builder.bat"/>
<None Remove="builder.sh"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.11.0"/>
<PackageReference Include="pythonnet" Version="3.0.1" />
<PackageReference Include="Spectre.Console" Version="0.47.0" />
<PackageReference Include="pythonnet" Version="3.0.1"/>
<PackageReference Include="Spectre.Console" Version="0.47.0"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PluginManager\PluginManager.csproj"/>

View File

@@ -16,16 +16,16 @@ public static class Entry
File.Delete(plugin);
}
}
#endif
var currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += LoadFromSameFolder;
static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{
var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "./Libraries");
var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "./Libraries");
var assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll");
if (!File.Exists(assemblyPath)) return null;
var assembly = Assembly.LoadFrom(assemblyPath);

View File

@@ -9,9 +9,9 @@ public static class Installer
{
AnsiConsole.MarkupLine("Welcome to the [bold]SethBot[/] installer !");
AnsiConsole.MarkupLine("First, we need to configure the bot. Don't worry, it will be quick !");
var token = AnsiConsole.Ask<string>("Please enter the bot [yellow]token[/]:");
var prefix = AnsiConsole.Ask<string>("Please enter the bot [yellow]prefix[/]:");
var token = AnsiConsole.Ask<string>("Please enter the bot [yellow]token[/]:");
var prefix = AnsiConsole.Ask<string>("Please enter the bot [yellow]prefix[/]:");
var serverId = AnsiConsole.Ask<string>("Please enter the [yellow]Server ID[/]:");
if (string.IsNullOrWhiteSpace(serverId)) serverId = "NULL";
@@ -20,9 +20,9 @@ public static class Installer
Config.AppSettings.Add("ServerID", serverId);
Config.AppSettings.SaveToFile();
AnsiConsole.MarkupLine("[bold]Config saved ![/]");
Config.Logger.Log("Config Saved", source: typeof(Installer));
}
}

View File

@@ -22,9 +22,9 @@ public class Program
public static void Startup(string[] args)
{
PreLoadComponents(args).Wait();
if (!AppSettings.ContainsKey("ServerID") || !AppSettings.ContainsKey("token") || !AppSettings.ContainsKey("prefix"))
Installer.GenerateStartupConfig();
Installer.GenerateStartupConfig();
HandleInput().Wait();
}
@@ -37,8 +37,8 @@ public class Program
internalActionManager.Initialize().Wait();
internalActionManager.Execute("plugin", "load").Wait();
internalActionManager.Refresh().Wait();
while (true)
{
var cmd = Console.ReadLine();
@@ -64,21 +64,21 @@ public class Program
Console.WriteLine($"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}");
Console.WriteLine("Git SethBot: https://github.com/andreitdr/SethDiscordBot");
Console.WriteLine("Git Plugins: https://github.com/andreitdr/SethPlugins");
ConsoleUtilities.WriteColorText("&rRemember to close the bot using the ShutDown command (&yexit&r) or some settings won't be saved");
ConsoleUtilities.WriteColorText($"Running on &m{Functions.GetOperatingSystem()}");
Console.WriteLine("============================ LOG ============================");
Console.ForegroundColor = ConsoleColor.White;
try
{
var token = AppSettings["token"];
var token = AppSettings["token"];
var prefix = AppSettings["prefix"];
var discordbooter = new Boot(token, prefix);
await discordbooter.Awake();
}
catch ( Exception ex )
catch (Exception ex)
{
Logger.Log(ex.ToString(), source: typeof(Program), type: LogType.CRITICAL);
}
@@ -96,18 +96,20 @@ public class Program
internalActionManager = new InternalActionManager("./Data/Plugins", "*.dll");
NoGUI();
}
catch ( IOException ex )
catch (IOException ex)
{
if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9)
{
if (AppSettings.ContainsKey("LaunchMessage"))
AppSettings.Add("LaunchMessage",
"An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" +
"There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !");
"An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" +
"There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !"
);
Logger.Log("An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" +
"There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !",
source: typeof(Program), type: LogType.ERROR);
"There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !",
source: typeof(Program), type: LogType.ERROR
);
}
}
}
@@ -115,7 +117,7 @@ public class Program
private static async Task PreLoadComponents(string[] args)
{
await Initialize();
Logger.OnLog += (sender, logMessage) =>
{
string messageColor = logMessage.Type switch
@@ -133,10 +135,10 @@ public class Program
Console.WriteLine(logMessage.Message);
return;
}
AnsiConsole.MarkupLine($"{messageColor}{logMessage.ThrowTime} {logMessage.Message} [/]");
};
AppSettings["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}

View File

@@ -9,24 +9,24 @@ namespace DiscordBot.Utilities;
public class TableData
{
public List<string> Columns;
public List<string> Columns;
public List<string[]> Rows;
public bool IsEmpty => Rows.Count == 0;
public bool HasRoundBorders { get; set; } = true;
public TableData(List<string> columns)
{
Columns = columns;
Rows = new List<string[]>();
}
public TableData(string[] columns)
{
Columns = columns.ToList();
Rows = new List<string[]>();
}
public void AddRow(string[] row)
{
Rows.Add(row);
@@ -41,23 +41,23 @@ public static class ConsoleUtilities
T result = default;
await AnsiConsole.Progress()
.Columns(
new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn(),
}
)
new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn(),
}
)
.StartAsync(
async ctx =>
{
var task = ctx.AddTask(message);
task.IsIndeterminate = true;
result = await function;
task.Increment(100);
async ctx =>
{
var task = ctx.AddTask(message);
task.IsIndeterminate = true;
result = await function;
task.Increment(100);
}
);
}
);
return result;
}
@@ -66,21 +66,23 @@ public static class ConsoleUtilities
{
await AnsiConsole.Progress()
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn(),
})
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn(),
}
)
.StartAsync(async ctx =>
{
var task = ctx.AddTask(message);
task.IsIndeterminate = true;
await function;
task.Increment(100);
});
{
var task = ctx.AddTask(message);
task.IsIndeterminate = true;
await function;
task.Increment(100);
}
);
}
private static readonly Dictionary<char, ConsoleColor> Colors = new()
{
{ 'g', ConsoleColor.Green },
@@ -91,7 +93,7 @@ public static class ConsoleUtilities
};
private static readonly char ColorPrefix = '&';
private static bool CanAproximateTo(this float f, float y)
{
return MathF.Abs(f - y) < 0.000001;
@@ -104,7 +106,7 @@ public static class ConsoleUtilities
table.AddColumns(tableData.Columns.ToArray());
foreach (var row in tableData.Rows)
table.AddRow(row);
AnsiConsole.Write(table);
}
@@ -123,12 +125,12 @@ public static class ConsoleUtilities
data.RemoveAt(0);
foreach (var row in data)
table.AddRow(row);
AnsiConsole.Write(table);
return;
}
if (format == TableFormat.CENTER_EACH_COLUMN_BASED)
{
var tableLine = '-';
@@ -317,18 +319,18 @@ public static class ConsoleUtilities
Console.CursorVisible = false;
isRunning = true;
thread = new Thread(() =>
{
while (isRunning)
{
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(" " + Sequence[position] + " " + Message + " ");
position++;
if (position >= Sequence.Length)
position = 0;
Thread.Sleep(100);
}
}
);
{
while (isRunning)
{
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(" " + Sequence[position] + " " + Message + " ");
position++;
if (position >= Sequence.Length)
position = 0;
Thread.Sleep(100);
}
}
);
thread.Start();
}

View File

@@ -78,7 +78,7 @@ public class Boot
CommonTasks();
await client.LoginAsync(TokenType.Bot, botToken);
await client.StartAsync();
commandServiceHandler = new CommandHandler(client, service, botPrefix);
@@ -105,7 +105,7 @@ public class Boot
if (arg.Message.Contains("401"))
{
Config.AppSettings.Remove("token");
Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", source:typeof(Boot), type: LogType.CRITICAL);
Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", source: typeof(Boot), type: LogType.CRITICAL);
await Config.AppSettings.SaveToFile();
await Task.Delay(4000);
Environment.Exit(0);

View File

@@ -106,9 +106,11 @@ internal class CommandHandler
(
plug.Aliases is not null &&
plug.Aliases.Contains(message.CleanContent
.Substring(mentionPrefix.Length + 1)
.Split(' ')[0])
));
.Substring(mentionPrefix.Length + 1)
.Split(' ')[0]
)
)
);
cleanMessage = message.Content.Substring(mentionPrefix.Length + 1);
}
@@ -120,11 +122,13 @@ internal class CommandHandler
message.Content.Split(' ')[0].Substring(botPrefix.Length) ||
(p.Aliases is not null &&
p.Aliases.Contains(
message.Content.Split(' ')[0]
.Substring(botPrefix.Length))));
message.Content.Split(' ')[0]
.Substring(botPrefix.Length)
))
);
cleanMessage = message.Content.Substring(botPrefix.Length);
}
if (plugin is null)
return;
@@ -138,13 +142,13 @@ internal class CommandHandler
argsClean = string.Join(' ', split, 1, split.Length - 1).Split(' ');
DBCommandExecutingArguments cmd = new(context, cleanMessage, split[0], argsClean);
Config.Logger.Log(
message: $"User ({context.User.Username}) from Guild \"{context.Guild.Name}\" executed command \"{cmd.cleanContent}\"",
source: typeof(CommandHandler),
type: LogType.INFO
);
if (context.Channel is SocketDMChannel)
plugin.ExecuteDM(cmd);
else plugin.ExecuteServer(cmd);

View File

@@ -20,18 +20,19 @@ public class Config
public static async Task Initialize()
{
if (_isLoaded) return;
Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/PAKS");
Directory.CreateDirectory("./Data/Logs/Logs");
Directory.CreateDirectory("./Data/Logs/Errors");
Directory.CreateDirectory("./Data/Archives");
Directory.CreateDirectory("./Data/Logs");
AppSettings = new SettingsDictionary<string, string>("./Data/Resources/config.json");
AppSettings["LogFolder"] = "./Data/Logs/Logs";
AppSettings["LogFolder"] = "./Data/Logs";
Logger = new Logger(false, true);
Logger = new Logger(false, true,
AppSettings["LogFolder"] + $"/{DateTime.Today.ToShortDateString().Replace("/", "")}.log"
);
ArchiveManager.Initialize();
@@ -39,5 +40,5 @@ public class Config
Logger.Log(message: "Config initialized", source: typeof(Config));
}
}

View File

@@ -163,7 +163,8 @@ public class SqlDatabase
throw new Exception($"Table {tableName} does not exist");
await ExecuteAsync(
$"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'");
$"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'"
);
}
/// <summary>
@@ -238,7 +239,7 @@ public class SqlDatabase
{
var command = _connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = await command.ExecuteReaderAsync();
var reader = await command.ExecuteReaderAsync();
var tableColumns = new List<string>();
for (var i = 0; i < reader.FieldCount; i++)
tableColumns.Add(reader.GetName(i));
@@ -262,7 +263,7 @@ public class SqlDatabase
{
var command = _connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = command.ExecuteReader();
var reader = command.ExecuteReader();
var tableColumns = new List<string>();
for (var i = 0; i < reader.FieldCount; i++)
tableColumns.Add(reader.GetName(i));
@@ -343,7 +344,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
var answer = await command.ExecuteNonQueryAsync();
var answer = await command.ExecuteNonQueryAsync();
return answer;
}
@@ -357,7 +358,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
_connection.Open();
var command = new SQLiteCommand(query, _connection);
var r = command.ExecuteNonQuery();
var r = command.ExecuteNonQuery();
return r;
}
@@ -372,7 +373,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
var reader = await command.ExecuteReaderAsync();
var reader = await command.ExecuteReaderAsync();
var values = new object[reader.FieldCount];
if (reader.Read())
@@ -394,7 +395,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
_connection.Open();
var command = new SQLiteCommand(query, _connection);
var reader = command.ExecuteReader();
var reader = command.ExecuteReader();
var values = new object[reader.FieldCount];
if (reader.Read())
@@ -416,7 +417,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
var reader = await command.ExecuteReaderAsync();
var reader = await command.ExecuteReaderAsync();
var values = new object[reader.FieldCount];
if (reader.Read())
@@ -439,7 +440,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
_connection.Open();
var command = new SQLiteCommand(query, _connection);
var reader = command.ExecuteReader();
var reader = command.ExecuteReader();
var values = new object[reader.FieldCount];
if (reader.Read())
@@ -462,7 +463,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
var reader = await command.ExecuteReaderAsync();
var reader = await command.ExecuteReaderAsync();
if (!reader.HasRows)
return null;
@@ -479,7 +480,7 @@ public class SqlDatabase
return rows;
}
/// <summary>
/// Create a parameter for a query
/// </summary>
@@ -490,7 +491,7 @@ public class SqlDatabase
{
var parameter = new SQLiteParameter(name);
parameter.Value = value;
if (value is string)
parameter.DbType = DbType.String;
else if (value is int)
@@ -531,13 +532,13 @@ public class SqlDatabase
parameter.DbType = DbType.StringFixedLength;
else if (value is char[])
parameter.DbType = DbType.StringFixedLength;
else
else
return null;
return parameter;
}
/// <summary>
/// Create a parameter for a query. The function automatically detects the type of the value.
/// </summary>
@@ -545,7 +546,7 @@ public class SqlDatabase
/// <returns>The SQLiteParameter that has the name, value and DBType set according to your inputs</returns>
private SQLiteParameter? CreateParameter(KeyValuePair<string, object> parameterValues) =>
CreateParameter(parameterValues.Key, parameterValues.Value);
/// <summary>
/// Execute a query with parameters
/// </summary>
@@ -556,7 +557,7 @@ public class SqlDatabase
{
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
foreach (var parameter in parameters)
{
@@ -564,10 +565,10 @@ public class SqlDatabase
if (p is not null)
command.Parameters.Add(p);
}
return await command.ExecuteNonQueryAsync();
}
/// <summary>
/// Execute a query with parameters that returns a specific type of object. The function will return the first row of the result transformed into the specified type.
/// </summary>
@@ -576,11 +577,11 @@ public class SqlDatabase
/// <param name="parameters">The parameters of the query</param>
/// <typeparam name="T">The return object type</typeparam>
/// <returns>An object of type T that represents the output of the convertor function based on the array of objects that the first row of the result has</returns>
public async Task<T?> ReadObjectOfTypeAsync<T> (string query, Func<object[], T> convertor, params KeyValuePair<string, object>[] parameters)
public async Task<T?> ReadObjectOfTypeAsync<T>(string query, Func<object[], T> convertor, params KeyValuePair<string, object>[] parameters)
{
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
foreach (var parameter in parameters)
{
@@ -588,7 +589,7 @@ public class SqlDatabase
if (p is not null)
command.Parameters.Add(p);
}
var reader = await command.ExecuteReaderAsync();
var values = new object[reader.FieldCount];
if (reader.Read())
@@ -599,8 +600,8 @@ public class SqlDatabase
return default;
}
/// <summary>
/// Execute a query with parameters that returns a specific type of object. The function will return a list of objects of the specified type.
/// </summary>
@@ -614,7 +615,7 @@ public class SqlDatabase
{
if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection);
foreach (var parameter in parameters)
{
@@ -622,12 +623,12 @@ public class SqlDatabase
if (p is not null)
command.Parameters.Add(p);
}
var reader = await command.ExecuteReaderAsync();
//
if (!reader.HasRows)
return null;
List<T> rows = new();
while (await reader.ReadAsync())
{
@@ -638,4 +639,4 @@ public class SqlDatabase
return rows;
}
}
}

View File

@@ -6,7 +6,7 @@ namespace PluginManager.Interfaces;
public interface DBSlashCommand
{
string Name { get; }
string Name { get; }
string Description { get; }
bool canUseDM { get; }

View File

@@ -5,11 +5,10 @@ namespace PluginManager.Interfaces.Logger;
internal interface ILog
{
string Message { get; set; }
string OutputFile { get; set; }
string Message { get; set; }
Type? Source { get; set; }
LogType Type { get; set; }
LogType Type { get; set; }
DateTime ThrowTime { get; set; }
}

View File

@@ -7,11 +7,13 @@ namespace PluginManager.Interfaces.Logger;
internal interface ILogger
{
bool IsEnabled { get; init; }
bool OutputToFile { get; init; }
bool IsEnabled { get; init; }
bool OutputToFile { get; init; }
string OutputFile { get; init; }
event EventHandler<Log> OnLog;
void Log(
string message = "", string outputFile = "", Type? source = default, LogType type = LogType.INFO,
string message = "", Type? source = default, LogType type = LogType.INFO,
DateTime throwTime = default);
}

View File

@@ -8,13 +8,13 @@ using PluginManager.Others;
namespace PluginManager.Loaders;
internal class LoaderArgs : EventArgs
internal class LoaderArgs: EventArgs
{
internal string? PluginName { get; init; }
internal string? TypeName { get; init; }
internal bool IsLoaded { get; init; }
internal Exception? Exception { get; init; }
internal object? Plugin { get; init; }
internal string? PluginName { get; init; }
internal string? TypeName { get; init; }
internal bool IsLoaded { get; init; }
internal Exception? Exception { get; init; }
internal object? Plugin { get; init; }
}
internal class Loader
@@ -26,7 +26,7 @@ internal class Loader
}
private string Path { get; }
private string Path { get; }
private string Extension { get; }
internal event FileLoadedEventHandler? FileLoaded;
@@ -101,28 +101,29 @@ internal class Loader
if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs
{
Exception = null,
IsLoaded = true,
PluginName = type.FullName,
TypeName = typeof(T) == typeof(DBCommand) ? "DBCommand" :
typeof(T) == typeof(DBEvent) ? "DBEvent" :
typeof(T) == typeof(DBSlashCommand) ? "DBSlashCommand" :
null,
Plugin = plugin
}
);
{
Exception = null,
IsLoaded = true,
PluginName = type.FullName,
TypeName = typeof(T) == typeof(DBCommand) ? "DBCommand" :
typeof(T) == typeof(DBEvent) ? "DBEvent" :
typeof(T) == typeof(DBSlashCommand) ? "DBSlashCommand" :
null,
Plugin = plugin
}
);
}
catch (Exception ex)
{
if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs
{
Exception = ex,
IsLoaded = false,
PluginName = type.FullName,
TypeName = nameof(T)
});
{
Exception = ex,
IsLoaded = false,
PluginName = type.FullName,
TypeName = nameof(T)
}
);
}
return list;

View File

@@ -131,7 +131,8 @@ public class PluginLoader
builder.Options = slash.Options;
onSLSHLoad?.Invoke(((DBSlashCommand)args.Plugin!).Name, args.TypeName, args.IsLoaded,
args.Exception);
args.Exception
);
await _client.CreateGlobalApplicationCommandAsync(builder.Build());
}
@@ -161,7 +162,7 @@ public class PluginLoader
else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type))
{
var instance = (DBSlashCommand)Activator.CreateInstance(type);
var builder = new SlashCommandBuilder();
var builder = new SlashCommandBuilder();
builder.WithName(instance.Name);
builder.WithDescription(instance.Description);
builder.WithDMPermission(instance.canUseDM);
@@ -177,6 +178,6 @@ public class PluginLoader
//Console.WriteLine(ex.Message);
Config.Logger.Log(ex.Message, source: typeof(PluginLoader), type: LogType.ERROR);
}
}
}

View File

@@ -19,10 +19,10 @@ internal static class OnlineFunctions
/// <param name="cancellation">The cancellation token</param>
/// <returns></returns>
internal static async Task DownloadFileAsync(
this HttpClient client, string url, Stream destination,
IProgress<float>? progress = null,
IProgress<long>? downloadedBytes = null, int bufferSize = 81920,
CancellationToken cancellation = default)
this HttpClient client, string url, Stream destination,
IProgress<float>? progress = null,
IProgress<long>? downloadedBytes = null, int bufferSize = 81920,
CancellationToken cancellation = default)
{
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellation))
{
@@ -35,7 +35,7 @@ internal static class OnlineFunctions
if (progress == null || !contentLength.HasValue)
{
await download.CopyToAsync(destination, cancellation);
if(!contentLength.HasValue)
if (!contentLength.HasValue)
progress?.Report(100f);
return;
}

View File

@@ -10,7 +10,7 @@ namespace PluginManager.Online;
public class PluginsManager
{
#if DEBUG
/// <summary>
/// The Plugin Manager constructor
@@ -22,16 +22,16 @@ public class PluginsManager
PluginsLink = plink;
VersionsLink = vlink;
}
#endif
/// <summary>
/// The Plugin Manager constructor. It uses the default links and the default branch.
/// </summary>
/// <param name="branch">The main branch from where the plugin manager gets its info</param>
public PluginsManager(string? branch = "releases")
{
PluginsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/PluginsList";
PluginsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/PluginsList";
VersionsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/Versions";
}
@@ -95,7 +95,7 @@ public class PluginsManager
}
catch (Exception exception)
{
Config.Logger.Log(message: "Failed to execute command: listplugs\nReason: " + exception.Message, source: typeof(PluginsManager), type: LogType.ERROR );
Config.Logger.Log(message: "Failed to execute command: listplugs\nReason: " + exception.Message, source: typeof(PluginsManager), type: LogType.ERROR);
}
return null;
@@ -135,16 +135,18 @@ public class PluginsManager
for (var i = 0; i < len; i++)
{
var contents = lines[i].Split(',');
if(Functions.GetOperatingSystem() == OperatingSystem.WINDOWS && contents[4].Contains("Windows"))
{if (contents[0].ToLowerInvariant() == name.ToLowerInvariant())
if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS && contents[4].Contains("Windows"))
{
if (contents.Length == 6)
return new[] { contents[2], contents[3], contents[5] };
if (contents.Length == 5)
return new[] { contents[2], contents[3], string.Empty };
throw new Exception("Failed to download plugin. Invalid Argument Length");
if (contents[0].ToLowerInvariant() == name.ToLowerInvariant())
{
if (contents.Length == 6)
return new[] { contents[2], contents[3], contents[5] };
if (contents.Length == 5)
return new[] { contents[2], contents[3], string.Empty };
throw new Exception("Failed to download plugin. Invalid Argument Length");
}
}
}else if (Functions.GetOperatingSystem() == OperatingSystem.LINUX && contents[4].Contains("Linux"))
else if (Functions.GetOperatingSystem() == OperatingSystem.LINUX && contents[4].Contains("Linux"))
{
if (contents.Length == 6)
return new[] { contents[2], contents[3], contents[5] };

View File

@@ -30,7 +30,7 @@ public static class ServerCom
/// <param name="progress">The <see cref="IProgress{T}" /> to track the download</param>
/// <returns></returns>
public static async Task DownloadFileAsync(
string URL, string location, IProgress<float> progress,
string URL, string location, IProgress<float> progress,
IProgress<long>? downloadedBytes)
{
using (var client = new HttpClient())
@@ -48,15 +48,15 @@ public static class ServerCom
{
await DownloadFileAsync(URl, location, progress, null);
}
public static Task CreateDownloadTask(string URl, string location)
{
return DownloadFileAsync(URl, location, null, null);
}
public static Task CreateDownloadTask(string URl, string location, IProgress<float> progress)
{
return DownloadFileAsync(URl, location, progress, null);
}
}

View File

@@ -26,7 +26,7 @@ public class InternalActionManager
Actions.TryAdd(action.ActionName, action);
}
}
public async Task Refresh()
{
Actions.Clear();
@@ -59,7 +59,7 @@ public class InternalActionManager
}
catch (Exception e)
{
Config.Logger.Log(e.Message , type: LogType.ERROR, source: typeof(InternalActionManager));
Config.Logger.Log(e.Message, type: LogType.ERROR, source: typeof(InternalActionManager));
return e.Message;
}
}

View File

@@ -37,24 +37,24 @@ public static class ArchiveManager
if (!File.Exists(archName))
throw new Exception("Failed to load file !");
byte[]? data = null;
using (var zip = ZipFile.OpenRead(archName))
{
var entry = zip.Entries.FirstOrDefault(entry => entry.FullName == fileName || entry.Name == fileName);
if (entry is null) throw new Exception("File not found in archive");
var MemoryStream = new MemoryStream();
var stream = entry.Open();
await stream.CopyToAsync(MemoryStream);
data = MemoryStream.ToArray();
stream.Close();
MemoryStream.Close();
}
return data;
}
@@ -117,7 +117,7 @@ public static class ArchiveManager
{
if (type == UnzipProgressType.PERCENTAGE_FROM_NUMBER_OF_FILES)
{
var totalZIPFiles = archive.Entries.Count();
var totalZIPFiles = archive.Entries.Count();
var currentZIPFile = 0;
foreach (var entry in archive.Entries)
{
@@ -173,4 +173,4 @@ public static class ArchiveManager
}
}
}
}
}

View File

@@ -29,19 +29,19 @@ public class DBCommandExecutingArguments
{
this.cleanContent = message.Content.Substring(Config.DiscordBot.botPrefix.Length);
}
var split = this.cleanContent.Split(' ');
string[]? argsClean = null;
if (split.Length > 1)
argsClean = string.Join(' ', split, 1, split.Length - 1).Split(' ');
this.commandUsed = split[0];
this.arguments = argsClean;
this.arguments = argsClean;
}
public SocketCommandContext context { get; init; }
public string cleanContent { get; init; }
public string commandUsed { get; init; }
public string[]? arguments { get; init; }
public SocketCommandContext context { get; init; }
public string cleanContent { get; init; }
public string commandUsed { get; init; }
public string[]? arguments { get; init; }
}

View File

@@ -40,8 +40,8 @@ public enum InternalActionRunType
ON_CALL
}
internal enum ExceptionExitCode : int
internal enum ExceptionExitCode: int
{
CONFIG_FAILED_TO_LOAD = 1,
CONFIG_KEY_NOT_FOUND = 2,
CONFIG_KEY_NOT_FOUND = 2,
}

View File

@@ -54,8 +54,8 @@ public static class Functions
/// <exception cref="InvalidOperationException">Triggered if <paramref name="stream" /> is not readable</exception>
/// <exception cref="ArgumentException">Triggered in <paramref name="destination" /> is not writable</exception>
public static async Task CopyToOtherStreamAsync(
this Stream stream, Stream destination, int bufferSize,
IProgress<long>? progress = null,
this Stream stream, Stream destination, int bufferSize,
IProgress<long>? progress = null,
CancellationToken cancellationToken = default)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
@@ -76,7 +76,7 @@ public static class Functions
progress?.Report(totalBytesRead);
}
}
public static T SelectRandomValueOf<T>()
{

View File

@@ -38,10 +38,10 @@ public class JsonManager
else
text = new MemoryStream(Encoding.ASCII.GetBytes(input));
text.Position = 0;
var obj = await JsonSerializer.DeserializeAsync<T>(text);
await text.FlushAsync();
text.Close();
return (obj ?? default)!;
}
}
}

View File

@@ -4,60 +4,46 @@ using PluginManager.Interfaces.Logger;
namespace PluginManager.Others.Logger;
public class Log : ILog
public class Log: ILog
{
public string Message { get; set; }
public string OutputFile { get; set; }
public Type? Source { get; set; }
public LogType Type { get; set; }
public DateTime ThrowTime { get; set; }
public Log(string message, string outputFile, Type? source, LogType type, DateTime throwTime)
public string Message { get; set; }
public Type? Source { get; set; }
public LogType Type { get; set; }
public DateTime ThrowTime { get; set; }
public Log(string message, Type? source, LogType type, DateTime throwTime)
{
Message = message;
OutputFile = outputFile;
Source = source;
Type = type;
ThrowTime = throwTime;
Message = message;
Source = source;
Type = type;
ThrowTime = throwTime;
}
public Log(string message, string outputFile, Type? source, LogType type)
public Log(string message, Type? source, LogType type)
{
Message = message;
OutputFile = outputFile;
Source = source;
Type = type;
ThrowTime = DateTime.Now;
Message = message;
Source = source;
Type = type;
ThrowTime = DateTime.Now;
}
public Log(string message, string outputFile, Type? source)
public Log(string message, Type? source)
{
Message = message;
OutputFile = outputFile;
Source = source;
Type = LogType.INFO;
ThrowTime = DateTime.Now;
Message = message;
Source = source;
Type = LogType.INFO;
ThrowTime = DateTime.Now;
}
public Log(string message, string outputFile)
{
Message = message;
OutputFile = outputFile;
Source = typeof(Log);
Type = LogType.INFO;
ThrowTime = DateTime.Now;
}
public Log(string message)
{
Message = message;
OutputFile = "";
Source = typeof(Log);
Type = LogType.INFO;
ThrowTime = DateTime.Now;
Message = message;
Source = typeof(Log);
Type = LogType.INFO;
ThrowTime = DateTime.Now;
}
public static implicit operator Log(string message) => new (message);
public static implicit operator Log(string message) => new(message);
public static implicit operator string(Log log) => $"[{log.ThrowTime}] {log.Message}";
@@ -65,7 +51,7 @@ public class Log : ILog
{
return $"[{ThrowTime}] [{Source}] [{Type}] {Message}";
}
public string AsShortString()
{
return this;

View File

@@ -6,64 +6,72 @@ using PluginManager.Interfaces.Logger;
namespace PluginManager.Others.Logger;
public sealed class Logger : ILogger
public sealed class Logger: ILogger
{
public bool IsEnabled { get; init; }
public bool OutputToFile { get; init; }
public bool IsEnabled { get; init; }
public bool OutputToFile { get; init; }
public string? OutputFile { get; init; }
private LogType LowestLogLevel { get; }
private bool UseShortVersion { get; }
public Logger(bool useShortVersion, bool outputToFile, LogType lowestLogLevel = LogType.INFO)
private LogType LowestLogLevel { get; }
private bool UseShortVersion { get; }
public Logger(bool useShortVersion, bool outputToFile, string outputFile, LogType lowestLogLevel = LogType.INFO)
{
UseShortVersion = useShortVersion;
OutputToFile = outputToFile;
IsEnabled = true;
LowestLogLevel = lowestLogLevel;
OutputFile = outputFile;
}
public Logger(bool useShortVersion, LogType lowestLogLevel = LogType.INFO)
{
UseShortVersion = useShortVersion;
OutputToFile = false;
IsEnabled = true;
LowestLogLevel = lowestLogLevel;
OutputFile = null;
}
public event EventHandler<Log>? OnLog;
private async Task Log(Log logMessage)
{
if (!IsEnabled) return;
OnLog?.Invoke(this, logMessage);
if (logMessage.Type < LowestLogLevel) return;
if (OutputToFile)
await File.AppendAllTextAsync(
logMessage.OutputFile,
(UseShortVersion ? logMessage : logMessage.AsLongString()) + "\n");
OutputFile!,
(UseShortVersion ? logMessage : logMessage.AsLongString()) + "\n"
);
}
public async void Log(string message = "", string outputFile = "", Type? source = default, LogType type = LogType.INFO, DateTime throwTime = default)
public async void Log(string message = "", Type? source = default, LogType type = LogType.INFO, DateTime throwTime = default)
{
if (!IsEnabled) return;
if (type < LowestLogLevel) return;
if (string.IsNullOrEmpty(message)) return;
if (string.IsNullOrEmpty(outputFile)) outputFile = Config.AppSettings["LogFolder"] + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
if(throwTime == default) throwTime = DateTime.Now;
if (throwTime == default) throwTime = DateTime.Now;
if (source == default) source = typeof(Log);
await Log(new Log(message, outputFile, source, type, throwTime));
await Log(new Log(message, source, type, throwTime));
}
public async void Log(Exception exception, LogType logType = LogType.ERROR, Type? source = null)
{
if (!IsEnabled) return;
if (logType < LowestLogLevel) return;
await Log(new Log(exception.Message,
Config.AppSettings["LogFolder"] + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log",
source, logType, DateTime.Now));
await Log(new Log(exception.Message, source, logType, DateTime.Now));
}
}

View File

@@ -5,11 +5,11 @@ using System.Threading.Tasks;
namespace PluginManager.Others;
public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
public class SettingsDictionary<TKey, TValue>: IDictionary<TKey, TValue>
{
public string? _file { get; }
private IDictionary<TKey, TValue>? _dictionary;
public SettingsDictionary(string? file)
{
_file = file;
@@ -19,7 +19,7 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
SaveToFile();
}
}
public async Task SaveToFile()
{
if (!string.IsNullOrEmpty(_file))
@@ -36,8 +36,8 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
string FileContent = File.ReadAllText(_file);
if (string.IsNullOrEmpty(FileContent))
File.WriteAllText(_file, "{}");
if(!FileContent.Contains("{") || !FileContent.Contains("}"))
if (!FileContent.Contains("{") || !FileContent.Contains("}"))
File.WriteAllText(_file, "{}");
}
else
@@ -61,7 +61,7 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) _dictionary!).GetEnumerator();
return ((IEnumerable)_dictionary!).GetEnumerator();
}
public void Add(KeyValuePair<TKey, TValue> item)
@@ -89,7 +89,7 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
return this._dictionary!.Remove(item);
}
public int Count => _dictionary!.Count;
public int Count => _dictionary!.Count;
public bool IsReadOnly => _dictionary!.IsReadOnly;
public void Add(TKey key, TValue value)
{
@@ -116,9 +116,9 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
get
{
if (this._dictionary!.ContainsKey(key))
if(this._dictionary[key] is string s && !string.IsNullOrEmpty(s) && !string.IsNullOrWhiteSpace(s))
if (this._dictionary[key] is string s && !string.IsNullOrEmpty(s) && !string.IsNullOrWhiteSpace(s))
return this._dictionary[key];
return default!;
}
set => this._dictionary![key] = value;
@@ -126,4 +126,4 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
public ICollection<TKey> Keys => _dictionary!.Keys;
public ICollection<TValue> Values => _dictionary!.Values;
}
}

View File

@@ -9,10 +9,10 @@
<DebugSymbols>false</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<None Remove="BlankWindow1.xaml" />
<None Remove="BlankWindow1.xaml"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.11.0" />
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.118" />
<PackageReference Include="Discord.Net" Version="3.11.0"/>
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.118"/>
</ItemGroup>
</Project>

View File

@@ -22,12 +22,12 @@
</ItemGroup>
<ItemGroup>
<Folder Include="DiscordBot\" />
<Folder Include="DiscordBot\"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DiscordBot\DiscordBot.csproj" />
<ProjectReference Include="..\PluginManager\PluginManager.csproj" />
<ProjectReference Include="..\DiscordBot\DiscordBot.csproj"/>
<ProjectReference Include="..\PluginManager\PluginManager.csproj"/>
</ItemGroup>
</Project>