This commit is contained in:
2023-03-11 00:07:11 +02:00
parent 873855937f
commit 7e2fa02d07
8 changed files with 105 additions and 100 deletions

View File

@@ -1,8 +1,6 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using Discord; using Discord;
using Discord.Commands;
using PluginManager; using PluginManager;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Loaders; using PluginManager.Loaders;
@@ -60,7 +58,7 @@ internal class Help : DBCommand
var adminCommands = ""; var adminCommands = "";
var normalCommands = ""; var normalCommands = "";
foreach (var cmd in PluginLoader.Commands!) foreach (var cmd in PluginLoader.Commands)
if (cmd.requireAdmin) if (cmd.requireAdmin)
adminCommands += cmd.Command + " "; adminCommands += cmd.Command + " ";
else else
@@ -77,7 +75,7 @@ internal class Help : DBCommand
private EmbedBuilder GenerateHelpCommand(string command) private EmbedBuilder GenerateHelpCommand(string command)
{ {
var embedBuilder = new EmbedBuilder(); var embedBuilder = new EmbedBuilder();
var cmd = PluginLoader.Commands!.Find(p => p.Command == command || 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; if (cmd == null) return null;

View File

@@ -1,5 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
@@ -8,41 +7,33 @@
<StartupObject /> <StartupObject />
<SignAssembly>False</SignAssembly> <SignAssembly>False</SignAssembly>
<IsPublishable>True</IsPublishable> <IsPublishable>True</IsPublishable>
<AssemblyVersion>1.0.2.0</AssemblyVersion> <AssemblyVersion>1.0.2.1</AssemblyVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>none</DebugType> <DebugType>none</DebugType>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>none</DebugType> <DebugType>none</DebugType>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Remove="Data\**" /> <Compile Remove="Data\**" />
<Compile Remove="obj\**" /> <Compile Remove="obj\**" />
<Compile Remove="Output\**" /> <Compile Remove="Output\**" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<EmbeddedResource Remove="Data\**" /> <EmbeddedResource Remove="Data\**" />
<EmbeddedResource Remove="obj\**" /> <EmbeddedResource Remove="obj\**" />
<EmbeddedResource Remove="Output\**" /> <EmbeddedResource Remove="Output\**" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Remove="Data\**" /> <None Remove="Data\**" />
<None Remove="obj\**" /> <None Remove="obj\**" />
<None Remove="Output\**" /> <None Remove="Output\**" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Discord.Net" Version="3.9.0" /> <PackageReference Include="Discord.Net" Version="3.9.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\PluginManager\PluginManager.csproj" /> <ProjectReference Include="..\PluginManager\PluginManager.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -6,10 +6,8 @@ using System.Reflection;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using DiscordBot.Discord.Core;
using PluginManager; using PluginManager;
using PluginManager.Database; using PluginManager.Bot;
using PluginManager.Items; using PluginManager.Items;
using PluginManager.Online; using PluginManager.Online;
using PluginManager.Online.Helpers; using PluginManager.Online.Helpers;
@@ -105,6 +103,9 @@ public class Program
Utilities.WriteColorText( 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)");
Logger.WriteLine();
Logger.WriteLine("Running on " + Functions.GetOperatingSystem().ToString());
Logger.WriteLine("============================ LOG ============================"); Logger.WriteLine("============================ LOG ============================");
try try
@@ -174,9 +175,7 @@ public class Program
private static async Task PreLoadComponents(string[] args) private static async Task PreLoadComponents(string[] args)
{ {
Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/PAKS");
if (!File.Exists(Functions.dataFolder + "loader.json")) if (!File.Exists(Functions.dataFolder + "loader.json"))
{ {
@@ -186,16 +185,7 @@ public class Program
else else
Entry.startupArguments = await Functions.ConvertFromJson<StartupArguments>(Functions.dataFolder + "loader.json"); Entry.startupArguments = await Functions.ConvertFromJson<StartupArguments>(Functions.dataFolder + "loader.json");
await Config.Initialize("SetDB.dat", true);
Settings.sqlDatabase = new SqlDatabase("SetDB.dat");
await Settings.sqlDatabase.Open();
await Config.Initialize();
Logger.Initialize(true);
ArchiveManager.Initialize();
Logger.LogEvent += (message) => { Console.Write(message); };
Logger.WriteLine("Loading resources ..."); Logger.WriteLine("Loading resources ...");
var main = new Utilities.ProgressBar(ProgressBarType.NO_END); var main = new Utilities.ProgressBar(ProgressBarType.NO_END);

View File

@@ -1,15 +1,14 @@
using System; using System.Net.Mime;
using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager; namespace PluginManager.Bot;
namespace DiscordBot.Discord.Core; public class Boot
internal class Boot
{ {
/// <summary> /// <summary>
/// The bot prefix /// The bot prefix
@@ -57,10 +56,12 @@ internal class Boot
/// <summary> /// <summary>
/// The start method for the bot. This method is used to load the bot /// The start method for the bot. This method is used to load the bot
/// </summary> /// </summary>
/// <param name="config">The discord socket config. If null then the default one will be applied (AlwaysDownloadUsers=true, UseInteractionSnowflakeDate=false, GatewayIntents=GatewayIntents.All)</param>
/// <returns>Task</returns> /// <returns>Task</returns>
public async Task Awake() public async Task Awake(DiscordSocketConfig? config = null)
{ {
var config = new DiscordSocketConfig if(config is null)
config = new DiscordSocketConfig
{ {
AlwaysDownloadUsers = true, AlwaysDownloadUsers = true,
@@ -100,16 +101,17 @@ internal class Boot
client.Disconnected += Client_Disconnected; client.Disconnected += Client_Disconnected;
} }
private Task Client_Disconnected(Exception arg) private async Task Client_Disconnected(Exception arg)
{ {
if (arg.Message.Contains("401")) if (arg.Message.Contains("401"))
{ {
Config.Variables.RemoveKey("token"); Config.Variables.RemoveKey("token");
Program.GenerateStartUI("The token is invalid"); Logger.LogError("The token is invalid. Please restart the bot and enter a valid token.");
await Task.Delay(4000);
Environment.Exit(0);
} }
Logger.WriteErrFile(arg); Logger.WriteErrFile(arg);
return Task.CompletedTask;
} }
private async Task Client_LoggedOut() private async Task Client_LoggedOut()
@@ -128,9 +130,6 @@ internal class Boot
private Task LoggedIn() private Task LoggedIn()
{ {
Console.Title = "CONNECTED"; Console.Title = "CONNECTED";
Logger.WriteLine("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" +
DateTime.Now.ToShortTimeString() + ")"
);
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -141,20 +140,14 @@ internal class Boot
case LogSeverity.Error: case LogSeverity.Error:
case LogSeverity.Critical: case LogSeverity.Critical:
Logger.WriteErrFile(message.Message); Logger.WriteErrFile(message.Message);
Logger.WriteColored(message.Message + "\n", ConsoleColor.Red);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] " + message.Message);
Console.ForegroundColor = ConsoleColor.White;
break; break;
case LogSeverity.Info: case LogSeverity.Info:
case LogSeverity.Debug: case LogSeverity.Debug:
Logger.WriteLogFile(message.Message); Logger.WriteLogFile(message.Message);
Logger.WriteColored(message.Message + "\n", ConsoleColor.White);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("[INFO] " + message.Message);
Console.ForegroundColor = ConsoleColor.White;
break; break;

View File

@@ -1,4 +1,4 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -10,9 +10,7 @@ using PluginManager.Loaders;
using PluginManager.Others; using PluginManager.Others;
using PluginManager.Others.Permissions; using PluginManager.Others.Permissions;
using static PluginManager.Logger; namespace PluginManager.Bot;
namespace DiscordBot.Discord.Core;
internal class CommandHandler internal class CommandHandler
{ {

View File

@@ -1,36 +1,52 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.IO;
using PluginManager.Online.Helpers; using PluginManager.Online.Helpers;
using PluginManager.Database;
namespace PluginManager; namespace PluginManager;
public static class Config public static class Config
{ {
private static bool IsLoaded = false; private static bool IsLoaded = false;
public static async Task Initialize() public static async Task Initialize(string DatabaseName, bool isConsole)
{ {
if (IsLoaded) if (IsLoaded)
return; return;
Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/PAKS");
Settings.sqlDatabase = new SqlDatabase(DatabaseName);
await Settings.sqlDatabase.Open();
if (!await Settings.sqlDatabase.TableExistsAsync("Plugins")) if (!await Settings.sqlDatabase.TableExistsAsync("Plugins"))
await Settings.sqlDatabase.CreateTableAsync("Plugins", "PluginName", "Version"); await Settings.sqlDatabase.CreateTableAsync("Plugins", "PluginName", "Version");
if (!await Settings.sqlDatabase.TableExistsAsync("Variables")) if (!await Settings.sqlDatabase.TableExistsAsync("Variables"))
await Settings.sqlDatabase.CreateTableAsync("Variables", "VarName", "Value", "ReadOnly"); await Settings.sqlDatabase.CreateTableAsync("Variables", "VarName", "Value", "ReadOnly");
IsLoaded = true; IsLoaded = true;
Logger.Initialize(isConsole);
PluginManager.Others.ArchiveManager.Initialize();
if(isConsole)
Logger.LogEvent += (message) => { Console.Write(message); };
} }
public static class Variables public static class Variables
{ {
public static async Task<string> GetValueAsync(string VarName) public static async Task<string?> GetValueAsync(string VarName)
{ {
if (!IsLoaded) if (!IsLoaded)
throw new Exception("Config is not loaded"); throw new Exception("Config is not loaded");
return await Settings.sqlDatabase.GetValueAsync("Variables", "VarName", VarName, "Value"); return await Settings.sqlDatabase.GetValueAsync("Variables", "VarName", VarName, "Value");
} }
public static string GetValue(string VarName) public static string? GetValue(string VarName)
{ {
if (!IsLoaded) if (!IsLoaded)
throw new Exception("Config is not loaded"); throw new Exception("Config is not loaded");

View File

@@ -96,6 +96,25 @@ namespace PluginManager
LogEvent?.Invoke($"{c}"); LogEvent?.Invoke($"{c}");
} }
public static void Write<T>(T c, params object[] Args)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
LogEvent?.Invoke(string.Format($"{c}", Args));
}
public static void WriteColored(string message, ConsoleColor color)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
if(!isConsole) {
LogEvent?.Invoke(message);
return;
}
var oldColor = Console.ForegroundColor;
Console.ForegroundColor = color;
LogEvent?.Invoke(message);
Console.ForegroundColor = oldColor;
}
/// <summary> /// <summary>
/// Write logs to file /// Write logs to file
/// </summary> /// </summary>

View File

@@ -9,7 +9,7 @@ namespace PluginManager.Others
public static class ArchiveManager public static class ArchiveManager
{ {
public static bool isInitialized { get; private set; } public static bool isInitialized { get; private set; }
private static string archiveFolder; private static string? archiveFolder;
public static void Initialize() public static void Initialize()
{ {
@@ -28,7 +28,7 @@ namespace PluginManager.Others
/// <param name="FileName">The file name that is inside the archive or its full path</param> /// <param name="FileName">The file name that is inside the archive or its full path</param>
/// <param name="archFile">The archive location from the PAKs folder</param> /// <param name="archFile">The archive location from the PAKs folder</param>
/// <returns>A string that represents the content of the file or null if the file does not exists or it has no content</returns> /// <returns>A string that represents the content of the file or null if the file does not exists or it has no content</returns>
public static async Task<string> ReadFromPakAsync(string FileName, string archFile) public static async Task<string?> ReadFromPakAsync(string FileName, string archFile)
{ {
if (!isInitialized) throw new Exception("ArchiveManager is not initialized"); if (!isInitialized) throw new Exception("ArchiveManager is not initialized");
archFile = archiveFolder + archFile; archFile = archiveFolder + archFile;
@@ -37,7 +37,7 @@ namespace PluginManager.Others
try try
{ {
string textValue = null; string? textValue = null;
using (var fs = new FileStream(archFile, FileMode.Open)) using (var fs = new FileStream(archFile, FileMode.Open))
using (var zip = new ZipArchive(fs, ZipArchiveMode.Read)) using (var zip = new ZipArchive(fs, ZipArchiveMode.Read))
{ {