Updated Logger and message handler. Updated to latest Discord.Net version

This commit is contained in:
2023-01-01 21:55:29 +02:00
parent 4a5e0ef2f3
commit 69d99b4189
11 changed files with 108 additions and 65 deletions

View File

@@ -66,7 +66,9 @@ internal class Boot
AlwaysDownloadUsers = true,
//Disable system clock checkup (for responses at slash commands)
UseInteractionSnowflakeDate = false
UseInteractionSnowflakeDate = false,
GatewayIntents = GatewayIntents.All
};
client = new DiscordSocketClient(config);

View File

@@ -30,6 +30,7 @@ internal class CommandHandler
this.client = client;
this.commandService = commandService;
this.botPrefix = botPrefix;
}
/// <summary>
@@ -76,12 +77,13 @@ internal class CommandHandler
{
try
{
if (Message.Author.IsBot) return;
if (Message as SocketUserMessage == null)
return;
var message = Message as SocketUserMessage;
if (message == null)
if (message is null)
return;
if (!message.Content.StartsWith(botPrefix))
@@ -95,9 +97,6 @@ internal class CommandHandler
return;
}
if (message.Author.IsBot)
return;
var context = new SocketCommandContext(client, message);
await commandService.ExecuteAsync(context, argPos, null);

View File

@@ -38,7 +38,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.7.2" />
<PackageReference Include="Discord.Net" Version="3.8.1" />
</ItemGroup>
<ItemGroup>

View File

@@ -33,7 +33,6 @@ public class Program
[STAThread]
public static void Startup(string[] args)
{
PreLoadComponents().Wait();
if (!Config.Variables.Exists("ServerID") || !Config.Variables.Exists("token") ||
@@ -56,9 +55,9 @@ public class Program
top.Add(win);
var labelInfo = new Label(
"Configuration file not found or invalid. " +
"Please fill the following fields to create a new configuration file."
)
"Configuration file not found or invalid. " +
"Please fill the following fields to create a new configuration file."
)
{
X = Pos.Center(),
Y = 2
@@ -251,12 +250,7 @@ public class Program
{
string token = "";
#if DEBUG
if (await Settings.sqlDatabase.TableExistsAsync("BetaTest"))
{
Logger.WriteLine("Starting in DEBUG MODE");
token = await Settings.sqlDatabase.GetValueAsync("BetaTest", "VariableName", "Token", "Value");
}
if (File.Exists("./Data/Resources/token.txt")) token = File.ReadAllText("./Data/Resources/token.txt");
else token = Config.Variables.GetValue("token");
#else
token = Config.Variables.GetValue("token");
@@ -307,8 +301,8 @@ public class Program
{
if (Config.Variables.Exists("LaunchMessage"))
Config.Variables.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 !",
false);
"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 !",
false);
Logger.WriteErrFile(ex.ToString());
}
}
@@ -318,7 +312,7 @@ public class Program
private static async Task PreLoadComponents()
{
Settings.sqlDatabase = new SqlDatabase(Functions.dataFolder + "SetDB.dat");
Settings.sqlDatabase = new SqlDatabase("SetDB.dat");
await Settings.sqlDatabase.Open();
await Config.Initialize();
@@ -326,10 +320,7 @@ public class Program
ArchiveManager.Initialize();
Logger.LogEvent += (message) =>
{
Console.Write(message);
};
Logger.LogEvent += (message) => { Console.Write(message); };
Logger.WriteLine("Loading resources ...");
var main = new Utilities.ProgressBar(ProgressBarType.NO_END);
@@ -348,9 +339,11 @@ public class Program
if (!await Config.Variables.ExistsAsync("Version"))
await Config.Variables.AddAsync("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(), false);
await Config.Variables.AddAsync("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(),
false);
else
await Config.Variables.SetValueAsync("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
await Config.Variables.SetValueAsync(
"Version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
foreach (var key in OnlineDefaultKeys)
@@ -397,21 +390,21 @@ public class Program
Console.ForegroundColor = ConsoleColor.Red;
Logger.WriteLine("A new version of the bot is available !");
Console.ForegroundColor = ConsoleColor.Yellow;
Logger.WriteLine("Current version : " + Assembly.GetExecutingAssembly().GetName().Version.ToString());
Logger.WriteLine("Current version : " +
Assembly.GetExecutingAssembly().GetName().Version.ToString());
Console.ForegroundColor = ConsoleColor.Green;
Logger.WriteLine("New version : " + newVersion);
Console.ForegroundColor = ConsoleColor.White;
Logger.WriteLine("Changelog :");
List<string> changeLog = await ServerCom.ReadTextFromURL("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/VersionData/DiscordBot");
List<string> changeLog = await ServerCom.ReadTextFromURL(
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/VersionData/DiscordBot");
foreach (var item in changeLog)
Utilities.WriteColorText(item);
Logger.WriteLine("Do you want to update the bot ? (y/n)");
if (Console.ReadKey().Key == ConsoleKey.Y)
{
if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS)
{
var url =
@@ -453,7 +446,7 @@ public class Program
"https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip",
"./Updater.zip");
await ArchiveManager.ExtractArchive("./Updater.zip", "./", null,
UnzipProgressType.PercentageFromTotalSize);
UnzipProgressType.PercentageFromTotalSize);
await Config.Variables.SetValueAsync("UpdaterVersion", updaternewversion);
File.Delete("Updater.zip");
bar.Stop("Updater has been updated !");
@@ -463,6 +456,7 @@ public class Program
break;
}
}
Console.Clear();
}
}

View File

@@ -2,6 +2,7 @@
using System.Data.SQLite;
using System.IO;
using System.Threading.Tasks;
namespace PluginManager.Database
{
public class SqlDatabase
@@ -11,6 +12,8 @@ namespace PluginManager.Database
public SqlDatabase(string fileName)
{
if (!fileName.StartsWith("./Data/Resources/"))
fileName = Path.Combine("./Data/Resources", fileName);
if (!File.Exists(fileName))
SQLiteConnection.CreateFile(fileName);
ConnectionString = $"URI=file:{fileName}";
@@ -27,7 +30,6 @@ namespace PluginManager.Database
public async Task InsertAsync(string tableName, params string[] values)
{
string query = $"INSERT INTO {tableName} VALUES (";
for (int i = 0; i < values.Length; i++)
{
@@ -35,6 +37,7 @@ namespace PluginManager.Database
if (i != values.Length - 1)
query += ", ";
}
query += ")";
SQLiteCommand command = new SQLiteCommand(query, Connection);
@@ -43,7 +46,6 @@ namespace PluginManager.Database
public void Insert(string tableName, params string[] values)
{
string query = $"INSERT INTO {tableName} VALUES (";
for (int i = 0; i < values.Length; i++)
{
@@ -51,34 +53,27 @@ namespace PluginManager.Database
if (i != values.Length - 1)
query += ", ";
}
query += ")";
SQLiteCommand command = new SQLiteCommand(query, Connection);
command.ExecuteNonQuery();
}
public async Task RemoveKeyAsync(string tableName, string KeyName, string KeyValue)
{
string query = $"DELETE FROM {tableName} WHERE {KeyName} = '{KeyValue}'";
SQLiteCommand command = new SQLiteCommand(query, Connection);
await command.ExecuteNonQueryAsync();
}
public void RemoveKey(string tableName, string KeyName, string KeyValue)
{
string query = $"DELETE FROM {tableName} WHERE {KeyName} = '{KeyValue}'";
SQLiteCommand command = new SQLiteCommand(query, Connection);
command.ExecuteNonQuery();
}
@@ -100,19 +95,21 @@ namespace PluginManager.Database
return true;
return false;
}
public async Task SetValueAsync(string tableName, string keyName, string KeyValue, string ResultColumnName, string ResultColumnValue)
public async Task SetValueAsync(string tableName, string keyName, string KeyValue, string ResultColumnName,
string ResultColumnValue)
{
if (!await TableExistsAsync(tableName))
throw new System.Exception($"Table {tableName} does not exist");
await ExecuteAsync($"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'");
await ExecuteAsync(
$"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'");
}
public void SetValue(string tableName, string keyName, string KeyValue, string ResultColumnName, string ResultColumnValue)
public void SetValue(string tableName, string keyName, string KeyValue, string ResultColumnName,
string ResultColumnValue)
{
if (!TableExists(tableName))
throw new System.Exception($"Table {tableName} does not exist");
@@ -121,7 +118,8 @@ namespace PluginManager.Database
}
public async Task<string> GetValueAsync(string tableName, string keyName, string KeyValue, string ResultColumnName)
public async Task<string> GetValueAsync(string tableName, string keyName, string KeyValue,
string ResultColumnName)
{
if (!await TableExistsAsync(tableName))
throw new System.Exception($"Table {tableName} does not exist");
@@ -144,7 +142,6 @@ namespace PluginManager.Database
public async Task AddColumnsToTableAsync(string tableName, string[] columns)
{
var command = Connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = await command.ExecuteReaderAsync();
@@ -164,7 +161,6 @@ namespace PluginManager.Database
public void AddColumnsToTable(string tableName, string[] columns)
{
var command = Connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = command.ExecuteReader();
@@ -180,12 +176,10 @@ namespace PluginManager.Database
command.ExecuteNonQuery();
}
}
}
public async Task<bool> TableExistsAsync(string tableName)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"SELECT name FROM sqlite_master WHERE type='table' AND name='{tableName}'";
var result = await cmd.ExecuteScalarAsync();
@@ -197,7 +191,6 @@ namespace PluginManager.Database
public bool TableExists(string tableName)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"SELECT name FROM sqlite_master WHERE type='table' AND name='{tableName}'";
var result = cmd.ExecuteScalar();
@@ -209,20 +202,16 @@ namespace PluginManager.Database
public async Task CreateTableAsync(string tableName, params string[] columns)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"CREATE TABLE IF NOT EXISTS {tableName} ({string.Join(", ", columns)})";
await cmd.ExecuteNonQueryAsync();
}
public void CreateTable(string tableName, params string[] columns)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"CREATE TABLE IF NOT EXISTS {tableName} ({string.Join(", ", columns)})";
cmd.ExecuteNonQuery();
}
public async Task<int> ExecuteAsync(string query)
@@ -257,6 +246,7 @@ namespace PluginManager.Database
reader.GetValues(values);
return string.Join<object>(" ", values);
}
return null;
}
@@ -273,6 +263,7 @@ namespace PluginManager.Database
reader.GetValues(values);
return string.Join<object>(" ", values);
}
return null;
}
@@ -289,9 +280,33 @@ namespace PluginManager.Database
reader.GetValues(values);
return values;
}
return null;
}
public async Task<List<string[]>> ReadAllRowsAsync(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
await Connection.OpenAsync();
var command = new SQLiteCommand(query, Connection);
var reader = await command.ExecuteReaderAsync();
if (!reader.HasRows)
return null;
List<string[]> rows = new();
while (await reader.ReadAsync())
{
string[] values = new string[reader.FieldCount];
reader.GetValues(values);
rows.Add(values);
}
if (rows.Count == 0) return null;
return rows;
}
public object[] ReadDataArray(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
@@ -305,7 +320,8 @@ namespace PluginManager.Database
reader.GetValues(values);
return values;
}
return null;
}
}
}
}

View File

@@ -56,10 +56,8 @@ public class ConsoleCommandsHandler
foreach (var command in commandList)
{
var pa = from p in command.Action.Method.GetParameters()
where p.Name != null
select p.ParameterType.FullName;
items.Add(new[] { command.CommandName, command.Description, command.Usage });
if (!command.CommandName.StartsWith("_"))
items.Add(new[] { command.CommandName, command.Description, command.Usage });
}
items.Add(new[] { "-", "-", "-" });
@@ -470,6 +468,20 @@ public class ConsoleCommandsHandler
return commandList.FirstOrDefault(t => t.CommandName == command);
}
/* public static async Task ExecuteSpecialCommand(string command)
{
if (!command.StartsWith("_")) return;
string[] args = command.Split(' ');
foreach (var item in commandList)
if (item.CommandName == args[0])
{
Logger.WriteLine();
item.Action(args);
}
}*/
public static async Task ExecuteCommad(string command)
{
if (!Logger.isConsole)
@@ -485,12 +497,16 @@ public class ConsoleCommandsHandler
public bool HandleCommand(string command, bool removeCommandExecution = true)
{
if (Logger.isConsole)
Console.ForegroundColor = ConsoleColor.White;
if (!Logger.isConsole)
throw new Exception("Can not use console based commands on non console based application !");
Console.ForegroundColor = ConsoleColor.White;
var args = command.Split(' ');
foreach (var item in commandList.ToList())
if (item.CommandName == args[0])
{
if (args[0].StartsWith("_"))
throw new Exception("This command is reserved for internal worker and can not be executed manually !");
if (Logger.isConsole)
if (removeCommandExecution)
{

View File

@@ -28,7 +28,7 @@ namespace PluginManager
isInitialized = true;
logFolder = Config.Variables.GetValue("LogFolder");
errFolder = Config.Variables.GetValue("ErrorFolder");
isConsole = console
isConsole = console;
}

View File

@@ -88,6 +88,8 @@ public static class Functions
var str = new MemoryStream();
await JsonSerializer.SerializeAsync(str, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllBytesAsync(file, str.ToArray());
await str.FlushAsync();
str.Close();
}
/// <summary>
@@ -105,6 +107,7 @@ public static class Functions
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

@@ -1,4 +1,5 @@
using System.Linq;
using Discord;
using Discord.WebSocket;

View File

@@ -16,8 +16,8 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.7.2" />
<PackageReference Include="System.Data.SQLite" Version="1.0.116" />
<PackageReference Include="Discord.Net" Version="3.8.1" />
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.117" />
<PackageReference Include="Terminal.Gui" Version="1.8.2" />
</ItemGroup>

View File

@@ -13,7 +13,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlashCommands", "..\Discord
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LevelingSystem", "..\DiscordBotItems\Plugins\LevelingSystem\LevelingSystem.csproj", "{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscordBotUI", "..\DiscordBotItems\DiscordBotUI\DiscordBotUI.csproj", "{3202CE21-BB39-452E-9B0C-740528CAFE43}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotUI", "..\DiscordBotItems\DiscordBotUI\DiscordBotUI.csproj", "{3202CE21-BB39-452E-9B0C-740528CAFE43}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Roles", "..\DiscordBotItems\Roles\Roles.csproj", "{0900B4CB-B531-4A8D-98D8-E709A7C2E098}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DBEconomy", "DBEconomy\DBEconomy.csproj", "{203464A2-8D25-4431-97BE-B9FF78F55850}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -45,6 +49,14 @@ Global
{3202CE21-BB39-452E-9B0C-740528CAFE43}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3202CE21-BB39-452E-9B0C-740528CAFE43}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3202CE21-BB39-452E-9B0C-740528CAFE43}.Release|Any CPU.Build.0 = Release|Any CPU
{0900B4CB-B531-4A8D-98D8-E709A7C2E098}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0900B4CB-B531-4A8D-98D8-E709A7C2E098}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0900B4CB-B531-4A8D-98D8-E709A7C2E098}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0900B4CB-B531-4A8D-98D8-E709A7C2E098}.Release|Any CPU.Build.0 = Release|Any CPU
{203464A2-8D25-4431-97BE-B9FF78F55850}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{203464A2-8D25-4431-97BE-B9FF78F55850}.Debug|Any CPU.Build.0 = Debug|Any CPU
{203464A2-8D25-4431-97BE-B9FF78F55850}.Release|Any CPU.ActiveCfg = Release|Any CPU
{203464A2-8D25-4431-97BE-B9FF78F55850}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE