Update to Discord.Net 3.8.1 (API v10)

This commit is contained in:
2022-10-22 13:55:48 +03:00
parent cad3bb5b75
commit ae7118e89a
12 changed files with 121 additions and 150 deletions

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

@@ -271,7 +271,7 @@ public class Program
if (len > 0 && args[0] == "/remplug")
{
var plugName = args.MergeStrings(1);
var plugName = string.Join(' ', args, 1, args.Length - 1);
Console.WriteLine("Starting to remove " + plugName);
await ConsoleCommandsHandler.ExecuteCommad("remplug " + plugName);
loadPluginsOnStartup = true;

View File

@@ -4,6 +4,7 @@ using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using PluginManager.Loaders;
using PluginManager.Others;
@@ -11,10 +12,10 @@ namespace PluginManager;
internal class AppConfig
{
public string? UpdaterVersion { get; set; }
public string? UpdaterVersion { get; set; }
public Dictionary<string, object>? ApplicationVariables { get; init; }
public List<string>? ProtectedKeyWords { get; init; }
public Dictionary<string, string>? PluginVersions { get; init; }
public List<string>? ProtectedKeyWords { get; init; }
public Dictionary<string, string>? PluginVersions { get; init; }
}
public static class Config
@@ -23,8 +24,8 @@ public static class Config
public static string UpdaterVersion
{
get => appConfig.UpdaterVersion;
set => appConfig.UpdaterVersion = value;
get => appConfig!.UpdaterVersion!;
set => appConfig!.UpdaterVersion = value;
}
public static string GetPluginVersion(string pluginName)
@@ -133,6 +134,25 @@ public static class Config
SaveConfig(SaveType.NORMAL);
}
public static bool TrySetValue<T>(string key, T value)
{
if (Config.ContainsKey(key))
{
try
{
Config.SetValue(key, value);
return true;
}
catch
{
return false;
}
}
Config.AddValueToVariables(key, value, false);
return true;
}
public static void RemoveKey(string key)
{
if (key == "Version" || key == "token" || key == "prefix")
@@ -176,7 +196,7 @@ public static class Config
{
File.Delete(path);
Console.WriteLine("An error occured while loading the settings. Importing from backup file...");
path = Functions.dataFolder + "config.json.bak";
path = Functions.dataFolder + "config.json.bak";
appConfig = await Functions.ConvertFromJson<AppConfig>(path);
Functions.WriteErrFile(ex.Message);
}
@@ -192,7 +212,7 @@ public static class Config
try
{
Console.WriteLine("An error occured while loading the settings. Importing from backup file...");
path = Functions.dataFolder + "config.json.bak";
path = Functions.dataFolder + "config.json.bak";
appConfig = await Functions.ConvertFromJson<AppConfig>(path);
return;
@@ -205,8 +225,10 @@ public static class Config
appConfig = new AppConfig
{
ApplicationVariables = new Dictionary<string, object>(), ProtectedKeyWords = new List<string>(),
PluginVersions = new Dictionary<string, string>(), UpdaterVersion = "-1"
ApplicationVariables = new Dictionary<string, object>(),
ProtectedKeyWords = new List<string>(),
PluginVersions = new Dictionary<string, string>(),
UpdaterVersion = "-1"
};
}
@@ -220,9 +242,9 @@ public static class Config
return appConfig!.ApplicationVariables!.ContainsKey(key);
}
public static IDictionary<string, object> GetAllVariables()
public static IDictionary<string, object>? GetAllVariables()
{
return appConfig.ApplicationVariables;
return appConfig?.ApplicationVariables;
}
public static class PluginConfig

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic;
using Discord.Commands;
namespace PluginManager.Interfaces;

View File

@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using Discord.WebSocket;
using PluginManager.Others;
namespace PluginManager.Items;
@@ -20,9 +20,9 @@ public class Command
{
Author = message.Author;
var data = message.Content.Split(' ');
Arguments = data.Length > 1 ? new List<string>(data.MergeStrings(1).Split(' ')) : new List<string>();
Arguments = data.Length > 1 ? new List<string>(string.Join(' ', data, 1, data.Length - 1).Split(' ')) : new List<string>();
CommandName = data[0].Substring(1);
PrefixUsed = data[0][0];
PrefixUsed = data[0][0];
}
/// <summary>
@@ -43,8 +43,8 @@ public class Command
public class ConsoleCommand
{
public string CommandName { get; init; }
public string Description { get; init; }
public string Usage { get; init; }
public Action<string[]> Action { get; init; }
public string CommandName { get; init; }
public string Description { get; init; }
public string Usage { get; init; }
public Action<string[]> Action { get; init; }
}

View File

@@ -1,11 +1,4 @@
using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Loaders;
using PluginManager.Online;
using PluginManager.Others;
using System;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
@@ -14,6 +7,13 @@ using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Loaders;
using PluginManager.Online;
using PluginManager.Others;
using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace PluginManager.Items;
@@ -101,7 +101,7 @@ public class ConsoleCommandsHandler
if (exception is null)
Console.WriteLine("An error occured while loading: " + name);
else
Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message);
Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message);
}
Console.ForegroundColor = cc;
@@ -143,7 +143,7 @@ public class ConsoleCommandsHandler
return;
}
var name = args.MergeStrings(1);
var name = string.Join(' ', args, 1, args.Length - 1);
// info[0] = plugin type
// info[1] = plugin link
// info[2] = if others are required, or string.Empty if none
@@ -313,7 +313,7 @@ public class ConsoleCommandsHandler
if (args.Length <= 1) return;
try
{
var pName = args.MergeStrings(1);
var pName = string.Join(' ', args, 1, args.Length - 1);
var client = new HttpClient();
var url = (await manager.GetPluginLinkByName(pName))[1];
if (url is null) throw new Exception($"Invalid plugin name {pName}.");
@@ -347,7 +347,7 @@ public class ConsoleCommandsHandler
if (args.Length <= 1) return;
isDownloading = true;
var plugName = args.MergeStrings(1);
var plugName = string.Join(' ', args, 1, args.Length - 1);
if (pluginsLoaded)
{
if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS)

View File

@@ -2,7 +2,9 @@
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Online;
using PluginManager.Online.Updates;
@@ -19,8 +21,8 @@ public class PluginLoader
private const string pluginCMDFolder = @"./Data/Plugins/Commands/";
private const string pluginEVEFolder = @"./Data/Plugins/Events/";
internal const string pluginCMDExtension = "dll";
internal const string pluginEVEExtension = "dll";
internal const string pluginCMDExtension = "dll";
internal const string pluginEVEExtension = "dll";
private readonly DiscordSocketClient _client;
/// <summary>
@@ -64,9 +66,12 @@ public class PluginLoader
await Task.Run(async () =>
{
var name = new FileInfo(file).Name.Split('.')[0];
var version = await ServerCom.GetVersionOfPackageFromWeb(name);
if (version is null)
return;
if (!Config.PluginVersionsContainsKey(name))
Config.SetPluginVersion(
name, (await ServerCom.GetVersionOfPackageFromWeb(name))?.PackageVersionID + ".0.0");
name, (version.PackageVersionID + ".0.0"));
if (await PluginUpdater.CheckForUpdates(name))
await PluginUpdater.Download(name);
@@ -78,9 +83,12 @@ public class PluginLoader
await Task.Run(async () =>
{
var name = new FileInfo(file).Name.Split('.')[0];
var version = await ServerCom.GetVersionOfPackageFromWeb(name);
if (version is null)
return;
if (!Config.PluginVersionsContainsKey(name))
Config.SetPluginVersion(
name, (await ServerCom.GetVersionOfPackageFromWeb(name))?.PackageVersionID + ".0.0");
name, (version.PackageVersionID + ".0.0"));
if (await PluginUpdater.CheckForUpdates(name))
await PluginUpdater.Download(name);
@@ -94,22 +102,24 @@ public class PluginLoader
//Load all plugins
Commands = new List<DBCommand>();
Events = new List<DBEvent>();
Events = new List<DBEvent>();
Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
Console.WriteLine("Loading plugins");
var commandsLoader = new Loader<DBCommand>(pluginCMDFolder, pluginCMDExtension);
var eventsLoader = new Loader<DBEvent>(pluginEVEFolder, pluginEVEExtension);
var eventsLoader = new Loader<DBEvent>(pluginEVEFolder, pluginEVEExtension);
commandsLoader.FileLoaded += OnCommandFileLoaded;
commandsLoader.FileLoaded += OnCommandFileLoaded;
commandsLoader.PluginLoaded += OnCommandLoaded;
eventsLoader.FileLoaded += EventFileLoaded;
eventsLoader.FileLoaded += EventFileLoaded;
eventsLoader.PluginLoaded += OnEventLoaded;
Commands = commandsLoader.Load();
Events = eventsLoader.Load();
Events = eventsLoader.Load();
}
private void EventFileLoaded(LoaderArgs e)
@@ -136,8 +146,8 @@ public class PluginLoader
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("Plugin: " + e.PluginName);
Console.WriteLine("Type: " + e.TypeName);
Console.WriteLine("Plugin: " + e.PluginName);
Console.WriteLine("Type: " + e.TypeName);
Console.WriteLine("IsLoaded: " + e.IsLoaded);
}
}

View File

@@ -13,19 +13,20 @@ public class VersionString
var data = version.Split('.');
try
{
PackageVersionID = int.Parse(data[0]);
PackageMainVersion = int.Parse(data[1]);
PackageVersionID = int.Parse(data[0]);
PackageMainVersion = int.Parse(data[1]);
PackageCheckVersion = int.Parse(data[2]);
}
catch (Exception ex)
{
Console.WriteLine(version);
throw new Exception("Failed to write Version", ex);
}
}
public override string ToString()
{
return "{PackageID: " + PackageVersionID + ", PackageVersion: " + PackageMainVersion +
return "{PackageID: " + PackageVersionID + ", PackageVersion: " + PackageMainVersion +
", PackageCheckVersion: " + PackageCheckVersion + "}";
}
@@ -45,7 +46,7 @@ public class VersionString
if (s1.PackageVersionID == s2.PackageVersionID)
{
if (s1.PackageMainVersion > s2.PackageMainVersion) return true;
if (s1.PackageMainVersion == s2.PackageMainVersion &&
if (s1.PackageMainVersion == s2.PackageMainVersion &&
s1.PackageCheckVersion > s2.PackageCheckVersion) return true;
}
@@ -59,7 +60,7 @@ public class VersionString
public static bool operator ==(VersionString s1, VersionString s2)
{
if (s1.PackageVersionID == s2.PackageVersionID && s1.PackageMainVersion == s2.PackageMainVersion &&
if (s1.PackageVersionID == s2.PackageVersionID && s1.PackageMainVersion == s2.PackageMainVersion &&
s1.PackageCheckVersion == s2.PackageCheckVersion) return true;
return false;
}

View File

@@ -1,7 +1,4 @@
using PluginManager.Online.Helpers;
using PluginManager.Others;
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
@@ -9,6 +6,9 @@ using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using PluginManager.Online.Helpers;
using PluginManager.Others;
namespace PluginManager.Online;
public static class ServerCom
@@ -100,10 +100,15 @@ public static class ServerCom
{
var url = "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/Versions";
var data = await ReadTextFromURL(url);
var version = (from item in data
where !item.StartsWith("#") && item.StartsWith(pakName)
select item.Split(',')[1]).FirstOrDefault();
if (version == default || version == null) return null;
return new VersionString(version);
foreach (var item in data)
{
if (item.StartsWith("#"))
continue;
string[] split = item.Split(',');
if (split[0] == pakName)
return new VersionString(split[1]);
}
return null;
}
}

View File

@@ -9,7 +9,9 @@ using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Discord.WebSocket;
using PluginManager.Items;
namespace PluginManager.Others;
@@ -113,31 +115,6 @@ public static class Functions
WriteErrFile(ex.ToString());
}
/// <summary>
/// Merge one array of strings into one string
/// </summary>
/// <param name="s">The array of strings</param>
/// <param name="indexToStart">The index from where the merge should start (included)</param>
/// <returns>A string built based on the array</returns>
public static string MergeStrings(this string[] s, int indexToStart)
{
return string.Join(' ', s, indexToStart, s.Length - 1);
/* string r = "";
int len = s.Length;
if (len <= indexToStart) return "";
for (int i = indexToStart; i < len - 1; ++i)
{
r += s[i] + " ";
}
r += s[len - 1];
return r;
*/
}
/// <summary>
/// Get the Operating system you are runnin on
/// </summary>
@@ -168,22 +145,21 @@ public static class Functions
/// <exception cref="ArgumentOutOfRangeException">Triggered if <paramref name="bufferSize" /> is less then or equal to 0</exception>
/// <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,
public static async Task CopyToOtherStreamAsync(this Stream stream, Stream destination, int bufferSize,
IProgress<long>? progress = null,
CancellationToken cancellationToken = default)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
if (stream == null) throw new ArgumentNullException(nameof(stream));
if (destination == null) throw new ArgumentNullException(nameof(destination));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize));
if (!stream.CanRead) throw new InvalidOperationException("The stream is not readable.");
if (!destination.CanWrite)
throw new ArgumentException("Destination stream is not writable", nameof(destination));
var buffer = new byte[bufferSize];
var buffer = new byte[bufferSize];
long totalBytesRead = 0;
int bytesRead;
while ((bytesRead =
await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
@@ -199,7 +175,7 @@ public static class Functions
/// <param name="progress">The progress that is updated as a file is processed</param>
/// <param name="type">The type of progress</param>
/// <returns></returns>
public static async Task ExtractArchive(string zip, string folder, IProgress<float> progress,
public static async Task ExtractArchive(string zip, string folder, IProgress<float> progress,
UnzipProgressType type)
{
Directory.CreateDirectory(folder);
@@ -207,7 +183,7 @@ public static class Functions
{
if (type == UnzipProgressType.PercentageFromNumberOfFiles)
{
var totalZIPFiles = archive.Entries.Count();
var totalZIPFiles = archive.Entries.Count();
var currentZIPFile = 0;
foreach (var entry in archive.Entries)
{
@@ -264,32 +240,6 @@ public static class Functions
}
}
/// <summary>
/// Convert Bytes to highest measurement unit possible
/// </summary>
/// <param name="bytes">The amount of bytes</param>
/// <returns></returns>
public static (double, string) ConvertBytes(long bytes)
{
var units = new List<string>
{
"B",
"KB",
"MB",
"GB",
"TB"
};
var i = 0;
while (bytes >= 1024)
{
i++;
bytes /= 1024;
}
return (bytes, units[i]);
}
/// <summary>
/// Save to JSON file
/// </summary>
@@ -323,36 +273,6 @@ public static class Functions
return (obj ?? default)!;
}
/// <summary>
/// Check if all words from <paramref name="str" /> are in <paramref name="baseString" /><br />
/// This function returns true if<br />
/// 1. The <paramref name="str" /> is part of <paramref name="baseString" /><br />
/// 2. The words (split by a space) of <paramref name="str" /> are located (separately) in
/// <paramref name="baseString" /> <br />
/// <example>
/// The following example will return <see langword="TRUE" /><br />
/// <c>STRContains("Hello World !", "I type word Hello and then i typed word World !")</c><br />
/// The following example will return <see langword="TRUE" /><br />
/// <c>STRContains("Hello World !", "I typed Hello World !" </c><br />
/// The following example will return <see langword="TRUE" /><br />
/// <c>STRContains("Hello World", "I type World then Hello")</c><br />
/// The following example will return <see langword="FALSE" /><br />
/// <c>STRContains("Hello World !", "I typed Hello World")</c><br />
/// </example>
/// </summary>
/// <param name="str">The string you are checking</param>
/// <param name="baseString">The main string that should contain <paramref name="str" /></param>
/// <returns></returns>
public static bool STRContains(this string str, string baseString)
{
if (baseString.Contains(str)) return true;
var array = str.Split(' ');
foreach (var s in array)
if (!baseString.Contains(s))
return false;
return true;
}
public static bool TryReadValueFromJson(string input, string codeName, out JsonElement element)
{
Stream text;
@@ -373,7 +293,7 @@ public static class Functions
using (var md5 = MD5.Create())
{
var inputBytes = Encoding.ASCII.GetBytes(input);
var hashBytes = md5.ComputeHash(inputBytes);
var hashBytes = md5.ComputeHash(inputBytes);
return Convert.ToHexString(hashBytes);
}
}

View File

@@ -16,7 +16,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.7.2" />
<PackageReference Include="Discord.Net" Version="3.8.1" />
<PackageReference Include="Terminal.Gui" Version="1.8.2" />
</ItemGroup>

View File

@@ -7,6 +7,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBot", "DiscordBot\Di
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginManager", "PluginManager\PluginManager.csproj", "{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MusicLibrary", "..\DiscordBotItems\Plugins\MusicLibrary\MusicLibrary.csproj", "{878DFE01-4596-4EBC-9651-0679598CE794}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MusicLibraryEvent", "..\DiscordBotItems\Plugins\MusicLibraryEvent\MusicLibraryEvent.csproj", "{3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -21,6 +25,14 @@ Global
{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.Build.0 = Release|Any CPU
{878DFE01-4596-4EBC-9651-0679598CE794}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{878DFE01-4596-4EBC-9651-0679598CE794}.Debug|Any CPU.Build.0 = Debug|Any CPU
{878DFE01-4596-4EBC-9651-0679598CE794}.Release|Any CPU.ActiveCfg = Release|Any CPU
{878DFE01-4596-4EBC-9651-0679598CE794}.Release|Any CPU.Build.0 = Release|Any CPU
{3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE