Moved items and reimplemented SettingsDictionary.cs

This commit is contained in:
2023-08-01 21:28:44 +03:00
parent 7107b17f19
commit b4f5e40f12
18 changed files with 268 additions and 273 deletions

View File

@@ -11,7 +11,7 @@ public class Clear : ICommandAction
public string Description => "Clears the console";
public string Usage => "clear";
public InternalActionRunType RunType => InternalActionRunType.ON_CALL;
public Task Execute(string[] args)
{
Console.Clear();

View File

@@ -17,21 +17,21 @@ public class Exit : ICommandAction
{
if (args is null || args.Length == 0)
{
Config.Logger.Log("Exiting...", "Exit", isInternal:false);
await Config.Data.Save();
Config.Logger.Log("Exiting...", "Exit", isInternal: false);
await Config.AppSettings.SaveToFile();
await Config.Logger.SaveToFile();
Environment.Exit(0);
}
else
{
switch (args[0])
switch ( args[0] )
{
case "help":
Console.WriteLine("Usage : exit [help|force]");
Console.WriteLine("help : Displays this message");
Console.WriteLine("force | -f : Exits the bot without saving the config");
break;
case "-f":
case "force":
Config.Logger.Log("Exiting (FORCE)...", "Exit", LogLevel.WARNING, false);

View File

@@ -34,7 +34,8 @@ public class Help : ICommandAction
items.Add(new[] { "-", "-", "-" });
Utilities.Utilities.FormatAndAlignTable(items,
TableFormat.CENTER_EACH_COLUMN_BASED);
TableFormat.CENTER_EACH_COLUMN_BASED
);
return;
}
@@ -55,6 +56,7 @@ public class Help : ICommandAction
};
Utilities.Utilities.FormatAndAlignTable(actionData,
TableFormat.CENTER_EACH_COLUMN_BASED);
TableFormat.CENTER_EACH_COLUMN_BASED
);
}
}

View File

@@ -31,7 +31,7 @@ public class Plugin : ICommandAction
return;
}
switch (args[0])
switch ( args[0] )
{
case "list":
var manager =
@@ -75,7 +75,8 @@ public class Plugin : ICommandAction
Console.WriteLine("An error occured while loading: " + name);
else
Console.WriteLine("[CMD] Failed to load command : " + name + " because " +
exception!.Message);
exception!.Message
);
}
Console.ForegroundColor = cc;
@@ -113,7 +114,8 @@ public class Plugin : ICommandAction
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[SLASH] Failed to load command : " + name + " because " +
exception!.Message);
exception!.Message
);
}
Console.ForegroundColor = cc;
@@ -156,7 +158,7 @@ public class Plugin : ICommandAction
//download plugin progress bar for linux and windows terminals
var spinner = new Utilities.Utilities.Spinner();
spinner.Start();
IProgress<float> progress = new Progress<float>(p => { spinner.Message = $"Downloading {pluginName}... {Math.Round(p,2)}% " ; });
IProgress<float> progress = new Progress<float>(p => { spinner.Message = $"Downloading {pluginName}... {Math.Round(p, 2)}% "; });
await ServerCom.DownloadFileAsync(pluginLink, $"./Data/{pluginType}s/{pluginName}.dll", progress);
spinner.Stop();
Console.WriteLine();

View File

@@ -75,10 +75,11 @@ 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)));
p.Aliases is not null && p.Aliases.Contains(command)
);
if (cmd == null) return null;
embedBuilder.AddField("Usage", Config.Data["prefix"] + cmd.Usage);
embedBuilder.AddField("Usage", Config.AppSettings["prefix"] + cmd.Usage);
embedBuilder.AddField("Description", cmd.Description);
if (cmd.Aliases is null)
return embedBuilder;

View File

@@ -3,8 +3,8 @@
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>disable</Nullable>
<ApplicationIcon />
<StartupObject />
<ApplicationIcon/>
<StartupObject/>
<SignAssembly>False</SignAssembly>
<IsPublishable>True</IsPublishable>
<AssemblyVersion>1.0.2.2</AssemblyVersion>
@@ -16,25 +16,25 @@
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Data\**" />
<Compile Remove="obj\**" />
<Compile Remove="Output\**" />
<Compile Remove="Data\**"/>
<Compile Remove="obj\**"/>
<Compile Remove="Output\**"/>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Remove="Data\**" />
<EmbeddedResource Remove="obj\**" />
<EmbeddedResource Remove="Output\**" />
<EmbeddedResource Remove="Data\**"/>
<EmbeddedResource Remove="obj\**"/>
<EmbeddedResource Remove="Output\**"/>
</ItemGroup>
<ItemGroup>
<None Remove="Data\**" />
<None Remove="obj\**" />
<None Remove="Output\**" />
<None Remove="Data\**"/>
<None Remove="obj\**"/>
<None Remove="Output\**"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.11.0" />
<PackageReference Include="Sodium.Core" Version="1.3.3" />
<PackageReference Include="Discord.Net" Version="3.11.0"/>
<PackageReference Include="Sodium.Core" Version="1.3.3"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PluginManager\PluginManager.csproj" />
<ProjectReference Include="..\PluginManager\PluginManager.csproj"/>
</ItemGroup>
</Project>

View File

@@ -14,7 +14,8 @@ public class Entry
static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{
var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"./Libraries");
"./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

@@ -15,30 +15,30 @@ public static class Installer
Console.WriteLine("The following information will be stored in the config.json file in the ./Data/Resources folder. You can change it later from there.");
Console.WriteLine("The bot token is required to run the bot. You can get it from the Discord Developer Portal. (https://discord.com/developers/applications)");
if (!Config.Data.ContainsKey("token"))
if (!Config.AppSettings.ContainsKey("token"))
{
Console.WriteLine("Please enter the bot token :");
var token = Console.ReadLine();
Config.Data.Add("token", token);
Config.AppSettings.Add("token", token);
}
if (!Config.Data.ContainsKey("prefix"))
if (!Config.AppSettings.ContainsKey("prefix"))
{
Console.WriteLine("Please enter the bot prefix :");
var prefix = Console.ReadLine();
Config.Data.Add("prefix", prefix);
Config.AppSettings.Add("prefix", prefix);
}
if (!Config.Data.ContainsKey("ServerID"))
if (!Config.AppSettings.ContainsKey("ServerID"))
{
Console.WriteLine("Please enter the Server ID :");
var serverId = Console.ReadLine();
Config.Data.Add("ServerID", serverId);
Config.AppSettings.Add("ServerID", serverId);
}
Config.Logger.Log("Config Saved", "Installer", isInternal:true);
Config.Logger.Log("Config Saved", "Installer", isInternal: true);
Config.Data.Save();
Config.AppSettings.SaveToFile();
Console.WriteLine("Config saved !");
}
@@ -94,7 +94,8 @@ public static class Installer
""LinuxBot"": """",
""WindowsLauncher"": """",
}
".Replace(" ", ""));
".Replace(" ", "")
);
Environment.Exit(0);
}
}

View File

@@ -15,8 +15,8 @@ namespace DiscordBot;
public class Program
{
public static Json<string, string> URLs;
public static InternalActionManager internalActionManager;
public static SettingsDictionary<string, string> URLs;
public static InternalActionManager internalActionManager;
/// <summary>
/// The main entry point for the application.
@@ -26,12 +26,12 @@ public class Program
{
PreLoadComponents(args).Wait();
if (!Data.ContainsKey("ServerID") || !Data.ContainsKey("token") ||
Data["token"] == null ||
(Data["token"]?.Length != 70 && Data["token"]?.Length != 59) ||
!Data.ContainsKey("prefix") || Data["prefix"] == null ||
Data["prefix"]?.Length != 1 ||
(args.Length == 1 && args[0] == "/reset"))
if (!AppSettings.ContainsKey("ServerID") || !AppSettings.ContainsKey("token") ||
AppSettings["token"] == null ||
AppSettings["token"]?.Length != 70 && AppSettings["token"]?.Length != 59 ||
!AppSettings.ContainsKey("prefix") || AppSettings["prefix"] == null ||
AppSettings["prefix"]?.Length != 1 ||
args.Length == 1 && args[0] == "/reset")
Installer.GenerateStartupConfig();
HandleInput(args.ToList()).Wait();
@@ -49,9 +49,9 @@ public class Program
while (true)
{
string cmd = Console.ReadLine();
string[] args = cmd.Split(' ');
string command = args[0];
var cmd = Console.ReadLine();
var args = cmd.Split(' ');
var command = args[0];
args = args.Skip(1).ToArray();
if (args.Length == 0)
args = null;
@@ -76,19 +76,22 @@ public class Program
Console.WriteLine(message);
Console.WriteLine(
$"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}");
Console.WriteLine($"Git URL: {Data["GitURL"]}");
$"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"
);
Console.WriteLine($"Git URL: {AppSettings["GitURL"]}");
Utilities.Utilities.WriteColorText(
"&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n");
"&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n"
);
Console.ForegroundColor = ConsoleColor.White;
if (Data.ContainsKey("LaunchMessage"))
Utilities.Utilities.WriteColorText(Data["LaunchMessage"]);
if (AppSettings.ContainsKey("LaunchMessage"))
Utilities.Utilities.WriteColorText(AppSettings["LaunchMessage"]);
Utilities.Utilities.WriteColorText(
"Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)");
"Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)"
);
Console.WriteLine("Running on " + Functions.GetOperatingSystem());
Console.WriteLine("============================ LOG ============================");
@@ -98,16 +101,16 @@ public class Program
var token = "";
#if DEBUG
if (File.Exists("./Data/Resources/token.txt")) token = File.ReadAllText("./Data/Resources/token.txt");
else token = Data["token"];
else token = AppSettings["token"];
#else
token = Config.Data["token"];
#endif
var prefix = Data["prefix"];
var prefix = AppSettings["prefix"];
var discordbooter = new Boot(token, prefix);
await discordbooter.Awake();
return discordbooter;
}
catch (Exception ex)
catch ( Exception ex )
{
Logger.Log(ex.ToString(), "Bot", LogLevel.ERROR);
return null;
@@ -141,16 +144,18 @@ public class Program
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 (Data.ContainsKey("LaunchMessage"))
Data.Add("LaunchMessage",
"An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !");
if (AppSettings.ContainsKey("LaunchMessage"))
AppSettings.Add("LaunchMessage",
"An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere 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 &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !",
"Bot", LogLevel.ERROR);
"Bot", LogLevel.ERROR
);
}
}
}
@@ -163,7 +168,9 @@ public class Program
await Installer.SetupPluginDatabase();
URLs = new Json<string, string>("./Data/Resources/URLs.json");
URLs = new SettingsDictionary<string, string>("./Data/Resources/URLs.json");
File.WriteAllText("temp.txt", string.Join(" ", URLs.Keys));
Logger.LogEvent += (message, type, isInternal) =>
{
@@ -174,28 +181,25 @@ public class Program
Console.ForegroundColor = ConsoleColor.DarkYellow;
else if (type == LogLevel.ERROR)
Console.ForegroundColor = ConsoleColor.Red;
else if(type == LogLevel.CRITICAL)
else if (type == LogLevel.CRITICAL)
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine($"[{type.ToString()}] {message}");
Console.ResetColor();
};
Console.WriteLine("Loading resources ...");
if (Data.ContainsKey("DeleteLogsAtStartup"))
if (Data["DeleteLogsAtStartup"] == "true")
if (AppSettings.ContainsKey("DeleteLogsAtStartup"))
if (AppSettings["DeleteLogsAtStartup"] == "true")
foreach (var file in Directory.GetFiles("./Output/Logs/"))
File.Delete(file);
var OnlineDefaultKeys =
await ServerCom.ReadTextFromURL(URLs["SetupKeys"]);
var OnlineDefaultKeys = await ServerCom.ReadTextFromURL(URLs["SetupKeys"]);
Data["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString();
AppSettings["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString();
foreach (var key in OnlineDefaultKeys)
{
@@ -203,9 +207,9 @@ public class Program
var s = key.Split(' ');
try
{
Data[s[0]] = s[1];
AppSettings[s[0]] = s[1];
}
catch (Exception ex)
catch ( Exception ex )
{
Logger.Log(ex.ToString(), "Bot", LogLevel.ERROR);
}
@@ -218,10 +222,10 @@ public class Program
if (key.Length <= 3 || !key.Contains(' ')) continue;
var s = key.Split(' ');
switch (s[0])
switch ( s[0] )
{
case "CurrentVersion":
var currentVersion = Data["Version"];
var currentVersion = AppSettings["Version"];
var newVersion = s[1];
if (new VersionString(newVersion) != new VersionString(newVersion))
{

View File

@@ -203,9 +203,9 @@ public static class Utilities
{
private readonly string[] Sequence;
private bool isRunning;
public string Message;
private int position;
private Thread thread;
public string Message;
public Spinner()
{
@@ -218,17 +218,18 @@ public static class Utilities
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();
}