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,7 +5,7 @@ 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";

View File

@@ -6,7 +6,7 @@ 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.";
@@ -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

@@ -53,7 +53,8 @@ internal static class PluginMethods
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn()
})
}
)
.StartAsync(async ctx =>
{
var downloadTask = ctx.AddTask("Downloading plugin...");
@@ -65,7 +66,8 @@ internal static class PluginMethods
downloadTask.Increment(100);
ctx.Refresh();
});
}
);
if (pluginRequirements == string.Empty)
{
@@ -82,7 +84,8 @@ internal static class PluginMethods
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn()
})
}
)
.StartAsync(async ctx =>
{
var gatherInformationTask = ctx.AddTask("Gathering info...");
@@ -90,7 +93,8 @@ internal static class PluginMethods
requirementsUrLs = await ServerCom.ReadTextFromURL(pluginRequirements);
gatherInformationTask.Increment(100);
});
}
);
List<Tuple<ProgressTask, IProgress<float>, string, string>> downloadTasks = new();
await AnsiConsole.Progress()
.Columns(new ProgressColumn[]
@@ -98,7 +102,8 @@ internal static class PluginMethods
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn()
})
}
)
.StartAsync(async ctx =>
{
@@ -114,7 +119,8 @@ internal static class PluginMethods
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));
@@ -137,11 +143,13 @@ internal static class PluginMethods
{
tuple.Item1.IsIndeterminate = false;
await ServerCom.DownloadFileAsync(tuple.Item3, $"./{tuple.Item4}", tuple.Item2);
});
}
);
});
}
);
@@ -166,13 +174,15 @@ internal static class PluginMethods
if (success)
{
Config.Logger.Log("Successfully loaded command : " + name, source: typeof(ICommandAction),
type: LogType.INFO);
type: LogType.INFO
);
}
else
{
Config.Logger.Log("Failed to load command : " + name + " because " + exception?.Message,
source: typeof(ICommandAction), type: LogType.ERROR);
source: typeof(ICommandAction), type: LogType.ERROR
);
}
Console.ForegroundColor = cc;
@@ -185,12 +195,14 @@ internal static class PluginMethods
if (success)
{
Config.Logger.Log("Successfully loaded event : " + name, source: typeof(ICommandAction),
type: LogType.INFO);
type: LogType.INFO
);
}
else
{
Config.Logger.Log("Failed to load event : " + name + " because " + exception?.Message,
source: typeof(ICommandAction), type: LogType.ERROR);
source: typeof(ICommandAction), type: LogType.ERROR
);
}
Console.ForegroundColor = cc;
@@ -204,12 +216,14 @@ internal static class PluginMethods
if (success)
{
Config.Logger.Log("Successfully loaded slash command : " + name, source: typeof(ICommandAction),
type: LogType.INFO);
type: LogType.INFO
);
}
else
{
Config.Logger.Log("Failed to load slash command : " + name + " because " + exception?.Message,
source: typeof(ICommandAction), type: LogType.ERROR);
source: typeof(ICommandAction), type: LogType.ERROR
);
}
Console.ForegroundColor = cc;

View File

@@ -22,7 +22,7 @@ internal static class SettingsConfigExtra
{
if (key is null) return;
if(!Config.AppSettings.ContainsKey(key))
if (!Config.AppSettings.ContainsKey(key))
return;
Config.AppSettings.Remove(key);

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";

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";

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";
@@ -27,21 +27,21 @@ 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;

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

View File

@@ -8,7 +8,7 @@ using PluginManager.Others;
namespace DiscordBot.Bot.Commands.SlashCommands;
public class Help : DBSlashCommand
public class Help: DBSlashCommand
{
public string Name => "help";
public string Description => "This command allows you to check all loaded commands";

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

@@ -78,7 +78,7 @@ public class Program
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 !");
"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);
source: typeof(Program), type: LogType.ERROR
);
}
}
}

View File

@@ -70,7 +70,8 @@ public static class ConsoleUtilities
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn(),
})
}
)
.StartAsync(async ctx =>
{
var task = ctx.AddTask(message);
@@ -78,7 +79,8 @@ public static class ConsoleUtilities
await function;
task.Increment(100);
});
}
);
}
private static readonly Dictionary<char, ConsoleColor> Colors = new()

View File

@@ -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

@@ -107,8 +107,10 @@ internal class CommandHandler
plug.Aliases is not null &&
plug.Aliases.Contains(message.CleanContent
.Substring(mentionPrefix.Length + 1)
.Split(' ')[0])
));
.Split(' ')[0]
)
)
);
cleanMessage = message.Content.Substring(mentionPrefix.Length + 1);
}
@@ -121,7 +123,9 @@ internal class CommandHandler
(p.Aliases is not null &&
p.Aliases.Contains(
message.Content.Split(' ')[0]
.Substring(botPrefix.Length))));
.Substring(botPrefix.Length)
))
);
cleanMessage = message.Content.Substring(botPrefix.Length);
}

View File

@@ -23,15 +23,16 @@ public class Config
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();

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>
@@ -576,7 +577,7 @@ 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();

View File

@@ -6,7 +6,6 @@ namespace PluginManager.Interfaces.Logger;
internal interface ILog
{
string Message { get; set; }
string OutputFile { get; set; }
Type? Source { get; set; }

View File

@@ -10,8 +10,10 @@ internal interface ILogger
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,7 +8,7 @@ using PluginManager.Others;
namespace PluginManager.Loaders;
internal class LoaderArgs : EventArgs
internal class LoaderArgs: EventArgs
{
internal string? PluginName { get; init; }
internal string? TypeName { get; init; }
@@ -122,7 +122,8 @@ internal class Loader
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());
}

View File

@@ -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

@@ -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,8 +135,9 @@ 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[0].ToLowerInvariant() == name.ToLowerInvariant())
{
if (contents.Length == 6)
return new[] { contents[2], contents[3], contents[5] };
@@ -144,7 +145,8 @@ public class PluginsManager
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

@@ -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

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

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 Log(string message, Type? source, LogType type, DateTime throwTime)
{
Message = message;
OutputFile = outputFile;
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;
}
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;
}
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;
}
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}";

View File

@@ -6,20 +6,31 @@ 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 string? OutputFile { get; init; }
private LogType LowestLogLevel { get; }
private bool UseShortVersion { get; }
public Logger(bool useShortVersion, bool outputToFile, LogType lowestLogLevel = LogType.INFO)
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;
@@ -34,11 +45,12 @@ public sealed class Logger : ILogger
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;
@@ -46,13 +58,11 @@ public sealed class Logger : ILogger
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));
}
@@ -62,8 +72,6 @@ public sealed class Logger : ILogger
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,7 +5,7 @@ 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;
@@ -37,7 +37,7 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
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)
@@ -116,7 +116,7 @@ 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!;

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>