From 40b85340ae93f6bd3044b7ba54a7af07ac8b458e Mon Sep 17 00:00:00 2001 From: Brett Hewitson Date: Sat, 18 Dec 2021 10:10:43 +1000 Subject: [PATCH] Bot cleanup Language file updates --- src/ARKServerManager/App.xaml.cs | 14 +++- .../Globalization/pt-BR/pt-BR.xaml | 9 +++ .../Globalization/ru-RU/ru-RU.xaml | 15 +++- src/ARKServerManager/VersionFeed.xml | 8 +- src/ARKServerManager/VersionFeedBeta.xml | 25 +++++++ src/ConanServerManager/App.xaml.cs | 14 +++- src/ConanServerManager/VersionFeed.xml | 8 +- src/ConanServerManager/VersionFeedBeta.xml | 23 ++++++ .../Attributes/RequireRoleAttribute.cs | 41 ++++++++++ src/ServerManager.Discord/Enums/LogLevel.cs | 5 ++ .../Interfaces/IServerManagerBot.cs | 5 +- .../Models/DiscordBotConfig.cs | 13 +++- .../Models/DiscordBotWhitelist.cs | 7 -- .../Modules/HelpModule.cs | 20 ++--- .../Modules/ServerCommandModule.cs | 11 +-- .../Modules/ServerQueryModule.cs | 10 +-- src/ServerManager.Discord/ServerManagerBot.cs | 34 +++------ .../Services/CommandHandlerService.cs | 75 ++++++++++++------- .../Services/LoggingService.cs | 16 ++-- .../Services/ShutdownService.cs | 10 +-- .../Services/StartupService.cs | 24 +++--- 21 files changed, 258 insertions(+), 129 deletions(-) create mode 100644 src/ServerManager.Discord/Attributes/RequireRoleAttribute.cs delete mode 100644 src/ServerManager.Discord/Models/DiscordBotWhitelist.cs diff --git a/src/ARKServerManager/App.xaml.cs b/src/ARKServerManager/App.xaml.cs index aded5630..c89867ed 100644 --- a/src/ARKServerManager/App.xaml.cs +++ b/src/ARKServerManager/App.xaml.cs @@ -5,6 +5,7 @@ using NLog.Targets; using ServerManagerTool.Common; using ServerManagerTool.Common.Utils; using ServerManagerTool.DiscordBot; +using ServerManagerTool.DiscordBot.Models; using ServerManagerTool.Enums; using ServerManagerTool.Lib; using ServerManagerTool.Plugin.Common; @@ -606,13 +607,20 @@ namespace ServerManagerTool Task discordTask = Task.Run(async () => { - var discordWhiteList = new List(); + var config = new DiscordBotConfig + { + LogLevel = Config.Default.DiscordBotLogLevel, + DiscordToken = Config.Default.DiscordBotToken, + CommandPrefix = Config.Default.DiscordBotPrefix, + DataDirectory = Config.Default.DataDir, + AllowAllBots = Config.Default.DiscordBotAllowAllBots, + }; if (Config.Default.DiscordBotWhitelist != null) { - discordWhiteList.AddRange(Config.Default.DiscordBotWhitelist.Cast()); + config.DiscordBotWhitelists = Config.Default.DiscordBotWhitelist.Cast(); } - await ServerManagerBotFactory.GetServerManagerBot()?.StartAsync(Config.Default.DiscordBotLogLevel, Config.Default.DiscordBotToken, Config.Default.DiscordBotPrefix, Config.Default.DataDir, Config.Default.DiscordBotAllowAllBots, discordWhiteList, DiscordBotHelper.HandleDiscordCommand, DiscordBotHelper.HandleTranslation, _tokenSourceDiscordBot.Token); + await ServerManagerBotFactory.GetServerManagerBot().RunAsync(config, DiscordBotHelper.HandleDiscordCommand, DiscordBotHelper.HandleTranslation, _tokenSourceDiscordBot.Token); if (_tokenSourceDiscordBot != null) { diff --git a/src/ARKServerManager/Globalization/pt-BR/pt-BR.xaml b/src/ARKServerManager/Globalization/pt-BR/pt-BR.xaml index e7e3acdb..52b6627c 100644 --- a/src/ARKServerManager/Globalization/pt-BR/pt-BR.xaml +++ b/src/ARKServerManager/Globalization/pt-BR/pt-BR.xaml @@ -634,6 +634,8 @@ Nível de registro: Obter Token... Ajuda... + Permitir todos os bots + Se ativado, o bot do gerenciador do servidor responderá a todos os outros bots, caso contrário, eles serão ignorados, a menos que estejam na lista de permissões. Bot Whitelist Bot ID O id do bot a ser colocado na whitelist. @@ -790,12 +792,18 @@ Habilitar Ativar a tarefa agendada de atualização automática Próximo tempo de execução: + Discord Bot: + Iniciar + Inicia o discord bot + Parar + Para o discord bot Desconhecido Desativado Na fila Pronto Running + Parado O perfil não foi carregado O perfil em {0} falhou ao carregar. O erro foi: {1}\r\n{2} @@ -5612,6 +5620,7 @@ Discord Bot Error O discord bot requer um token válido para que possa se conectar ao servidor discord\r\nIsso pode ser definido nas configurações globais. + O discord bot requer um prefixo válido.\r\nIsso pode ser definido nas configurações globais. O prefixo discord bot contém caracteres inválidos. Somente letras e números são permitidos. O comando '{0}' não foi habilitado. diff --git a/src/ARKServerManager/Globalization/ru-RU/ru-RU.xaml b/src/ARKServerManager/Globalization/ru-RU/ru-RU.xaml index c4328ce3..6a3da5a2 100644 --- a/src/ARKServerManager/Globalization/ru-RU/ru-RU.xaml +++ b/src/ARKServerManager/Globalization/ru-RU/ru-RU.xaml @@ -9,7 +9,7 @@ Последнее обновление: - 16.12.2021 от Varlonec, Эдван + 17.12.2021 от Varlonec, Эдван Ошибка @@ -634,6 +634,8 @@ Лог уровня: Получить токен ... Помощь... + Разрешить всем ботам + Если включено, менеджер сервера будет отвечать всем остальным ботам, в противном случае они будут игнорироваться, если только они не находятся в белом списке. Белый лист бота Бот ID ID бота для внесения в белый список. @@ -790,13 +792,19 @@ Включить Включить Авто-Обновленя по заданному времени Следующее время выполнения: - + Discord бот: + Старт + Запуск бота Discord + Стоп + Остановить бот Discord + Отключено Выключено В очереди Активно Запущено - + Остановлено + Профиль не загружен Не удалось загрузить профиль в {0}. Ошибка: {1}\r\n{2} Удалить Профиль {0}? @@ -5689,6 +5697,7 @@ Ошибка бота Discord Бот Discord требует действующий токен, чтобы он мог войти на сервер Discord\r\nЭто можно установить в глобальных настройках. + Для бота discord требуется действительный префикс.\r\nЭто можно установить в глобальных настройках. Префикс бота Discord содержит недопустимые символы. Разрешены только буквы и цифры. Команда '{0}' не активирована. diff --git a/src/ARKServerManager/VersionFeed.xml b/src/ARKServerManager/VersionFeed.xml index eb307a69..8052dd3e 100644 --- a/src/ARKServerManager/VersionFeed.xml +++ b/src/ARKServerManager/VersionFeed.xml @@ -5,14 +5,14 @@ Ark Server Manager Version Feed This is the Ark Server Manager release version feed. - 2021-12-17T00:00:00Z + 2021-12-18T00:00:00Z urn:uuid:3E33DCB2-ECFE-4489-B1A4-56F5D386F9DC - 1.1.413 (1.1.413.8) - 1.1.413.8 + 1.1.413 (1.1.413.9) + 1.1.413.9 - 2021-12-17T00:00:00Z + 2021-12-18T00:00:00Z

diff --git a/src/ARKServerManager/VersionFeedBeta.xml b/src/ARKServerManager/VersionFeedBeta.xml index 0f5abe1b..adc91cb6 100644 --- a/src/ARKServerManager/VersionFeedBeta.xml +++ b/src/ARKServerManager/VersionFeedBeta.xml @@ -7,6 +7,31 @@ 2021-12-16T00:00:00Z + + urn:uuid:1B7448FB-E4E0-4E0F-BF87-AE8661AA7D93 + 1.1.413 (1.1.413.9) +

1.1.413.9 + + 2021-12-18T00:00:00Z + +
+

+ CHANGE +
+

    +
  • Discord Bot - added some additional logging and some code cleanup.
  • +
  • pt-BR Translation file updated.
  • +
  • ru-RU Translation file updated.
  • +
+

+
+
+ + bletch + bletch1971@hotmail.com + + + urn:uuid:8EE5659C-18E6-47D3-941D-C32B129D2E06 1.1.413 (1.1.413.8) diff --git a/src/ConanServerManager/App.xaml.cs b/src/ConanServerManager/App.xaml.cs index 55b63548..7d5fc685 100644 --- a/src/ConanServerManager/App.xaml.cs +++ b/src/ConanServerManager/App.xaml.cs @@ -4,6 +4,7 @@ using NLog.Targets; using ServerManagerTool.Common; using ServerManagerTool.Common.Utils; using ServerManagerTool.DiscordBot; +using ServerManagerTool.DiscordBot.Models; using ServerManagerTool.Enums; using ServerManagerTool.Lib; using ServerManagerTool.Plugin.Common; @@ -587,13 +588,20 @@ namespace ServerManagerTool Task discordTask = Task.Run(async () => { - var discordWhiteList = new List(); + var config = new DiscordBotConfig + { + LogLevel = Config.Default.DiscordBotLogLevel, + DiscordToken = Config.Default.DiscordBotToken, + CommandPrefix = Config.Default.DiscordBotPrefix, + DataDirectory = Config.Default.DataPath, + AllowAllBots = Config.Default.DiscordBotAllowAllBots, + }; if (Config.Default.DiscordBotWhitelist != null) { - discordWhiteList.AddRange(Config.Default.DiscordBotWhitelist.Cast()); + config.DiscordBotWhitelists = Config.Default.DiscordBotWhitelist.Cast(); } - await ServerManagerBotFactory.GetServerManagerBot()?.StartAsync(Config.Default.DiscordBotLogLevel, Config.Default.DiscordBotToken, Config.Default.DiscordBotPrefix, Config.Default.DataPath, Config.Default.DiscordBotAllowAllBots, discordWhiteList, DiscordBotHelper.HandleDiscordCommand, DiscordBotHelper.HandleTranslation, _tokenSourceDiscordBot.Token); + await ServerManagerBotFactory.GetServerManagerBot().RunAsync(config, DiscordBotHelper.HandleDiscordCommand, DiscordBotHelper.HandleTranslation, _tokenSourceDiscordBot.Token); if (_tokenSourceDiscordBot != null) { diff --git a/src/ConanServerManager/VersionFeed.xml b/src/ConanServerManager/VersionFeed.xml index 64d9c4ab..4b9a2b2e 100644 --- a/src/ConanServerManager/VersionFeed.xml +++ b/src/ConanServerManager/VersionFeed.xml @@ -5,14 +5,14 @@ Conan Server Manager Version Feed This is the Conan Server Manager release version feed. - 2021-12-16T00:00:00Z + 2021-12-18T00:00:00Z urn:uuid:19B09A66-43F2-4D5F-AF33-5C77D7EA9A6B - 1.1.58 (1.1.58.8) - 1.1.58.8 + 1.1.58 (1.1.58.9) + 1.1.58.9 - 2021-12-16T00:00:00Z + 2021-12-18T00:00:00Z

diff --git a/src/ConanServerManager/VersionFeedBeta.xml b/src/ConanServerManager/VersionFeedBeta.xml index 9483dadb..1bea8309 100644 --- a/src/ConanServerManager/VersionFeedBeta.xml +++ b/src/ConanServerManager/VersionFeedBeta.xml @@ -7,6 +7,29 @@ 2021-12-17T00:00:00Z + + urn:uuid:9A427D82-9904-44F5-8C1E-7C943049869A + 1.1.58 (1.1.58.9) +

1.1.58.9 + + 2021-12-18T00:00:00Z + +
+

+ CHANGE +
+

    +
  • Discord Bot - added some additional logging and some code cleanup.
  • +
+

+
+
+ + bletch + bletch1971@hotmail.com + + + urn:uuid:9A427D82-9904-44F5-8C1E-7C943049869A 1.1.58 (1.1.58.8) diff --git a/src/ServerManager.Discord/Attributes/RequireRoleAttribute.cs b/src/ServerManager.Discord/Attributes/RequireRoleAttribute.cs new file mode 100644 index 00000000..8001fa35 --- /dev/null +++ b/src/ServerManager.Discord/Attributes/RequireRoleAttribute.cs @@ -0,0 +1,41 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Discord.Commands; +using Discord.WebSocket; + +namespace ServerManagerTool.DiscordBot.Attributes +{ + public class RequireRoleAttribute : PreconditionAttribute + { + private readonly string _name; + + public RequireRoleAttribute(string name) + { + _name = name; + } + + public override Task CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) + { + // Check if this user is a Guild User, which is the only context where roles exist + if (context.User is SocketGuildUser guildUser) + { + // If this command was executed by a user with the appropriate role, return a success + if (guildUser.Roles.Any(r => r.Name == _name)) + { + // Since no async work is done, the result has to be wrapped with `Task.FromResult` to avoid compiler errors + return Task.FromResult(PreconditionResult.FromSuccess()); + } + else + { + // Since it wasn't, fail + return Task.FromResult(PreconditionResult.FromError($"You must have a role named '{_name}' to run this command.")); + } + } + else + { + return Task.FromResult(PreconditionResult.FromError("You must be in a guild to run this command.")); + } + } + } +} diff --git a/src/ServerManager.Discord/Enums/LogLevel.cs b/src/ServerManager.Discord/Enums/LogLevel.cs index 8c18aeae..fc8421fe 100644 --- a/src/ServerManager.Discord/Enums/LogLevel.cs +++ b/src/ServerManager.Discord/Enums/LogLevel.cs @@ -21,5 +21,10 @@ namespace ServerManagerTool.DiscordBot.Enums return logSeverity; return LogSeverity.Info; } + + public static bool CheckLogLevel(LogLevel LogLevelToCheck, LogLevel configLogLevel) + { + return (int)configLogLevel >= (int)LogLevelToCheck; + } } } diff --git a/src/ServerManager.Discord/Interfaces/IServerManagerBot.cs b/src/ServerManager.Discord/Interfaces/IServerManagerBot.cs index a4ef8f1e..e3912372 100644 --- a/src/ServerManager.Discord/Interfaces/IServerManagerBot.cs +++ b/src/ServerManager.Discord/Interfaces/IServerManagerBot.cs @@ -1,6 +1,5 @@ using ServerManagerTool.DiscordBot.Delegates; -using ServerManagerTool.DiscordBot.Enums; -using System.Collections.Generic; +using ServerManagerTool.DiscordBot.Models; using System.Threading; using System.Threading.Tasks; @@ -10,6 +9,6 @@ namespace ServerManagerTool.DiscordBot.Interfaces { CancellationToken Token { get; } - Task StartAsync(LogLevel logLevel, string discordToken, string commandPrefix, string dataDirectory, bool allowAllBots, IEnumerable botWhitelist, HandleCommandDelegate handleCommandCallback, HandleTranslationDelegate handleTranslationCallback, CancellationToken token); + Task RunAsync(DiscordBotConfig discordBotConfig, HandleCommandDelegate handleCommandCallback, HandleTranslationDelegate handleTranslationCallback, CancellationToken token); } } diff --git a/src/ServerManager.Discord/Models/DiscordBotConfig.cs b/src/ServerManager.Discord/Models/DiscordBotConfig.cs index c6a0ca59..aa783c80 100644 --- a/src/ServerManager.Discord/Models/DiscordBotConfig.cs +++ b/src/ServerManager.Discord/Models/DiscordBotConfig.cs @@ -1,11 +1,20 @@ -using System.Collections.Generic; +using ServerManagerTool.DiscordBot.Enums; +using System.Collections.Generic; namespace ServerManagerTool.DiscordBot.Models { public class DiscordBotConfig { + public LogLevel LogLevel { get; set; } = LogLevel.Info; + + public string DiscordToken { get; set; } = string.Empty; + + public string CommandPrefix { get; set; } = string.Empty; + + public string DataDirectory { get; set; } = string.Empty; + public bool AllowAllBots { get; set; } = false; - public List DiscordBotWhitelists { get; set; } = new List(); + public IEnumerable DiscordBotWhitelists { get; set; } = new List(); } } diff --git a/src/ServerManager.Discord/Models/DiscordBotWhitelist.cs b/src/ServerManager.Discord/Models/DiscordBotWhitelist.cs deleted file mode 100644 index 4fb932b6..00000000 --- a/src/ServerManager.Discord/Models/DiscordBotWhitelist.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ServerManagerTool.DiscordBot.Models -{ - public class DiscordBotWhitelist - { - public string BotId { get; set; } = string.Empty; - } -} diff --git a/src/ServerManager.Discord/Modules/HelpModule.cs b/src/ServerManager.Discord/Modules/HelpModule.cs index 003da7a1..24fefc47 100644 --- a/src/ServerManager.Discord/Modules/HelpModule.cs +++ b/src/ServerManager.Discord/Modules/HelpModule.cs @@ -1,6 +1,6 @@ using Discord; using Discord.Commands; -using Microsoft.Extensions.Configuration; +using ServerManagerTool.DiscordBot.Models; using System; using System.Collections.Generic; using System.Linq; @@ -13,15 +13,15 @@ namespace ServerManagerTool.DiscordBot.Modules { private const int MAX_VALUE_LENGTH = 1024; - private readonly CommandService _service; - private readonly IConfigurationRoot _config; + private readonly CommandService _commands; + private readonly DiscordBotConfig _botConfig; private readonly IServiceProvider _services; - public HelpModule(CommandService service, IConfigurationRoot config, IServiceProvider services) + public HelpModule(CommandService commands, IServiceProvider services, DiscordBotConfig botConfig) { - _service = service; - _config = config; + _commands = commands; _services = services; + _botConfig = botConfig; } [Command("help")] @@ -29,7 +29,7 @@ namespace ServerManagerTool.DiscordBot.Modules [RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)] public async Task HelpAsync() { - var prefix = _config["DiscordSettings:Prefix"]; + var prefix = _botConfig.CommandPrefix; var builder = new EmbedBuilder() { @@ -37,7 +37,7 @@ namespace ServerManagerTool.DiscordBot.Modules Description = "These are the commands you can use" }; - foreach (var module in _service.Modules) + foreach (var module in _commands.Modules) { var moduleName = module.Name; @@ -106,7 +106,7 @@ namespace ServerManagerTool.DiscordBot.Modules [RequireBotPermission(ChannelPermission.ViewChannel | ChannelPermission.SendMessages)] public async Task HelpAsync(string command) { - var searchResults = _service.Search(Context, command); + var searchResults = _commands.Search(Context, command); if (!searchResults.IsSuccess) { @@ -114,7 +114,7 @@ namespace ServerManagerTool.DiscordBot.Modules return; } - var prefix = _config["DiscordSettings:Prefix"]; + var prefix = _botConfig.CommandPrefix; var builder = new EmbedBuilder() { diff --git a/src/ServerManager.Discord/Modules/ServerCommandModule.cs b/src/ServerManager.Discord/Modules/ServerCommandModule.cs index b2bd5461..a505c55b 100644 --- a/src/ServerManager.Discord/Modules/ServerCommandModule.cs +++ b/src/ServerManager.Discord/Modules/ServerCommandModule.cs @@ -6,7 +6,6 @@ using ServerManagerTool.DiscordBot.Delegates; using ServerManagerTool.DiscordBot.Enums; using ServerManagerTool.DiscordBot.Interfaces; using System; -using System.Threading; using System.Threading.Tasks; namespace ServerManagerTool.DiscordBot.Modules @@ -15,16 +14,14 @@ namespace ServerManagerTool.DiscordBot.Modules public sealed class ServerCommandModule : InteractiveBase { private readonly IServerManagerBot _serverManagerBot; - private readonly CommandService _service; + private readonly CommandService _commands; private readonly HandleCommandDelegate _handleCommandCallback; - private readonly IConfigurationRoot _config; - public ServerCommandModule(IServerManagerBot serverManagerBot, CommandService service, HandleCommandDelegate handleCommandCallback, IConfigurationRoot config) + public ServerCommandModule(IServerManagerBot serverManagerBot, CommandService commands, HandleCommandDelegate handleCommandCallback) { - _serverManagerBot = serverManagerBot; - _service = service; + _serverManagerBot = serverManagerBot; + _commands = commands; _handleCommandCallback = handleCommandCallback; - _config = config; } [Command("backup", RunMode = RunMode.Async)] diff --git a/src/ServerManager.Discord/Modules/ServerQueryModule.cs b/src/ServerManager.Discord/Modules/ServerQueryModule.cs index 407486c3..fa861f27 100644 --- a/src/ServerManager.Discord/Modules/ServerQueryModule.cs +++ b/src/ServerManager.Discord/Modules/ServerQueryModule.cs @@ -1,12 +1,10 @@ using Discord; using Discord.Addons.Interactive; using Discord.Commands; -using Microsoft.Extensions.Configuration; using ServerManagerTool.DiscordBot.Delegates; using ServerManagerTool.DiscordBot.Enums; using ServerManagerTool.DiscordBot.Interfaces; using System; -using System.Threading; using System.Threading.Tasks; namespace ServerManagerTool.DiscordBot.Modules @@ -15,16 +13,14 @@ namespace ServerManagerTool.DiscordBot.Modules public sealed class ServerQueryModule : InteractiveBase { private readonly IServerManagerBot _serverManagerBot; - private readonly CommandService _service; + private readonly CommandService _commands; private readonly HandleCommandDelegate _handleCommandCallback; - private readonly IConfigurationRoot _config; - public ServerQueryModule(IServerManagerBot serverManagerBot, CommandService service, HandleCommandDelegate handleCommandCallback, IConfigurationRoot config) + public ServerQueryModule(IServerManagerBot serverManagerBot, CommandService commands, HandleCommandDelegate handleCommandCallback) { _serverManagerBot = serverManagerBot; - _service = service; + _commands = commands; _handleCommandCallback = handleCommandCallback; - _config = config; } [Command("info", RunMode = RunMode.Async)] diff --git a/src/ServerManager.Discord/ServerManagerBot.cs b/src/ServerManager.Discord/ServerManagerBot.cs index c300e349..fe75e0f1 100644 --- a/src/ServerManager.Discord/ServerManagerBot.cs +++ b/src/ServerManager.Discord/ServerManagerBot.cs @@ -10,9 +10,7 @@ using ServerManagerTool.DiscordBot.Interfaces; using ServerManagerTool.DiscordBot.Models; using ServerManagerTool.DiscordBot.Services; using System; -using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -28,19 +26,24 @@ namespace ServerManagerTool.DiscordBot public CancellationToken Token { get; private set; } public bool Started { get; private set; } - public async Task StartAsync(LogLevel logLevel, string discordToken, string commandPrefix, string dataDirectory, bool allowAllBots, IEnumerable botWhitelist, HandleCommandDelegate handleCommandCallback, HandleTranslationDelegate handleTranslationCallback, CancellationToken token) + public async Task RunAsync(DiscordBotConfig discordBotConfig, HandleCommandDelegate handleCommandCallback, HandleTranslationDelegate handleTranslationCallback, CancellationToken token) { - if (string.IsNullOrWhiteSpace(discordToken)) + if (discordBotConfig is null || handleTranslationCallback is null || handleCommandCallback is null) + { + return; + } + + if (string.IsNullOrWhiteSpace(discordBotConfig.DiscordToken)) { throw new Exception("#DiscordBot_MissingTokenError"); } - if (string.IsNullOrWhiteSpace(commandPrefix)) + if (string.IsNullOrWhiteSpace(discordBotConfig.CommandPrefix)) { throw new Exception("#DiscordBot_MissingPrefixError"); } - if (Started || handleTranslationCallback is null || handleCommandCallback is null) + if (Started) { return; } @@ -48,22 +51,13 @@ namespace ServerManagerTool.DiscordBot Started = true; Token = token; - var settings = new Dictionary - { - { "DiscordSettings:Token", discordToken }, - { "DiscordSettings:Prefix", commandPrefix }, - { "DiscordSettings:LogLevel", logLevel.ToString() }, - { "ServerManager:DataDirectory", dataDirectory }, - }; - // Begin building the configuration file var config = new ConfigurationBuilder() - .AddInMemoryCollection(settings) .Build(); var socketConfig = new DiscordSocketConfig { - LogLevel = LogLevelHelper.GetLogSeverity(logLevel), + LogLevel = LogLevelHelper.GetLogSeverity(discordBotConfig.LogLevel), MessageCacheSize = 1000, }; if (Environment.OSVersion.Version < new Version(6, 2)) @@ -76,16 +70,10 @@ namespace ServerManagerTool.DiscordBot { // Force all commands to run async DefaultRunMode = RunMode.Async, - LogLevel = LogLevelHelper.GetLogSeverity(logLevel), + LogLevel = LogLevelHelper.GetLogSeverity(discordBotConfig.LogLevel), CaseSensitiveCommands = false, }; - var discordBotConfig = new DiscordBotConfig - { - AllowAllBots = allowAllBots, - DiscordBotWhitelists = new List ( botWhitelist.Select(i => new DiscordBotWhitelist { BotId = i }) ), - }; - // Build the service provider var services = new ServiceCollection() // Add the discord client to the service provider diff --git a/src/ServerManager.Discord/Services/CommandHandlerService.cs b/src/ServerManager.Discord/Services/CommandHandlerService.cs index 70fc6474..e3c022ba 100644 --- a/src/ServerManager.Discord/Services/CommandHandlerService.cs +++ b/src/ServerManager.Discord/Services/CommandHandlerService.cs @@ -1,7 +1,6 @@ using Discord; using Discord.Commands; using Discord.WebSocket; -using Microsoft.Extensions.Configuration; using ServerManagerTool.DiscordBot.Enums; using ServerManagerTool.DiscordBot.Models; using System; @@ -12,27 +11,51 @@ namespace ServerManagerTool.DiscordBot.Services { public class CommandHandlerService { - private readonly DiscordSocketClient _discord; + private readonly DiscordSocketClient _client; private readonly CommandService _commands; private readonly LoggingService _logger; - private readonly IConfigurationRoot _config; - private readonly IServiceProvider _provider; + private readonly IServiceProvider _services; private readonly DiscordBotConfig _botConfig; - public CommandHandlerService(DiscordSocketClient discord, CommandService commands, LoggingService logger, IConfigurationRoot config, IServiceProvider provider, DiscordBotConfig botConfig) + public CommandHandlerService(DiscordSocketClient client, CommandService commands, LoggingService logger, IServiceProvider services, DiscordBotConfig botConfig) { - _discord = discord; + _client = client; _commands = commands; _logger = logger; - _config = config; - _provider = provider; + _services = services; _botConfig = botConfig ?? new DiscordBotConfig(); - _discord.MessageReceived += OnMessageReceivedAsync; + + _commands.CommandExecuted += OnCommandExecutedAsync; + _client.MessageReceived += OnMessageReceivedAsync; + } + + public async Task OnCommandExecutedAsync(Optional command, ICommandContext context, IResult result) + { + var commandName = command.IsSpecified ? command.Value.Name : "A command"; + + // We can tell the user what went wrong + if (!string.IsNullOrWhiteSpace(result?.ErrorReason)) + { + switch (result?.Error) + { + case CommandError.BadArgCount: + await context.Channel.SendMessageAsync("Parameter count does not match any command."); + break; + default: + await context.Channel.SendMessageAsync(result.ErrorReason); + break; + } + } + + if (LogLevelHelper.CheckLogLevel(LogLevel.Info, _botConfig.LogLevel)) + { + await _logger?.OnLogAsync(new LogMessage(LogSeverity.Info, "CommandExecution", $"{commandName} was executed at {DateTime.Now}.")); + } } private async Task OnMessageReceivedAsync(SocketMessage s) { - if (LogLevel.Debug.ToString().Equals(_config["DiscordSettings:LogLevel"])) + if (LogLevelHelper.CheckLogLevel(LogLevel.Debug, _botConfig.LogLevel)) await _logger?.OnLogAsync(new LogMessage(LogSeverity.Debug, MessageSource.System.ToString(), $"Intercepted the following message from {s.Author.Username} ({s.Author.Id}) - {s.Content}")); // Ensure the message is a valid user socket message @@ -40,9 +63,9 @@ namespace ServerManagerTool.DiscordBot.Services return; // Ignore self - if (msg.Author.Id == _discord.CurrentUser.Id) + if (msg.Author.Id == _client.CurrentUser.Id) { - if (LogLevel.Debug.ToString().Equals(_config["DiscordSettings:LogLevel"])) + if (LogLevelHelper.CheckLogLevel(LogLevel.Debug, _botConfig.LogLevel)) await _logger?.OnLogAsync(new LogMessage(LogSeverity.Debug, MessageSource.System.ToString(), $"Message has come from this bot, message will be ignored.")); return; @@ -50,43 +73,39 @@ namespace ServerManagerTool.DiscordBot.Services // check if the author is a bot if (msg.Author.IsBot) - if (_botConfig.AllowAllBots) + { + if (_botConfig.AllowAllBots) { - if (LogLevel.Debug.ToString().Equals(_config["DiscordSettings:LogLevel"])) + if (LogLevelHelper.CheckLogLevel(LogLevel.Debug, _botConfig.LogLevel)) await _logger?.OnLogAsync(new LogMessage(LogSeverity.Debug, MessageSource.System.ToString(), $"Message has come from another bot, allow all bots enabled.")); } else { - if (LogLevel.Debug.ToString().Equals(_config["DiscordSettings:LogLevel"])) + if (LogLevelHelper.CheckLogLevel(LogLevel.Debug, _botConfig.LogLevel)) await _logger?.OnLogAsync(new LogMessage(LogSeverity.Debug, MessageSource.System.ToString(), $"Message has come from another bot, checking if bot is in the whitelist.")); - if (!_botConfig.DiscordBotWhitelists.Any(b => b.BotId.Equals(msg.Author.Id.ToString()))) + if (!_botConfig.DiscordBotWhitelists.Any(botId => botId.Equals(msg.Author.Id.ToString()))) { - if (LogLevel.Debug.ToString().Equals(_config["DiscordSettings:LogLevel"])) + if (LogLevelHelper.CheckLogLevel(LogLevel.Debug, _botConfig.LogLevel)) await _logger?.OnLogAsync(new LogMessage(LogSeverity.Debug, MessageSource.System.ToString(), $"Message has come from another bot, bot is not in the whitelist, message will be ignored.")); return; } - } + } + } // Check if the message has a valid command prefix var argPos = 0; - if (msg.HasStringPrefix(_config["DiscordSettings:Prefix"], ref argPos, StringComparison.OrdinalIgnoreCase) || msg.HasMentionPrefix(_discord.CurrentUser, ref argPos)) + if (msg.HasStringPrefix(_botConfig.CommandPrefix, ref argPos, StringComparison.OrdinalIgnoreCase) || msg.HasMentionPrefix(_client.CurrentUser, ref argPos)) { - if (LogLevel.Debug.ToString().Equals(_config["DiscordSettings:LogLevel"])) + if (LogLevelHelper.CheckLogLevel(LogLevel.Debug, _botConfig.LogLevel)) await _logger?.OnLogAsync(new LogMessage(LogSeverity.Debug, MessageSource.System.ToString(), $"Message prefix matched, message will be processed.")); // Create the command context - var context = new SocketCommandContext(_discord, msg); + var context = new SocketCommandContext(_client, msg); // Execute the command - var result = await _commands.ExecuteAsync(context, argPos, _provider); - - if (!result.IsSuccess) - { - // If not successful, reply with the error. - await context.Channel.SendMessageAsync(result.ToString()); - } + await _commands.ExecuteAsync(context, argPos, _services); } } } diff --git a/src/ServerManager.Discord/Services/LoggingService.cs b/src/ServerManager.Discord/Services/LoggingService.cs index 83a27406..a2e021e0 100644 --- a/src/ServerManager.Discord/Services/LoggingService.cs +++ b/src/ServerManager.Discord/Services/LoggingService.cs @@ -1,7 +1,7 @@ using Discord; using Discord.Commands; using Discord.WebSocket; -using Microsoft.Extensions.Configuration; +using ServerManagerTool.DiscordBot.Models; using System; using System.IO; using System.Threading.Tasks; @@ -10,24 +10,24 @@ namespace ServerManagerTool.DiscordBot.Services { public class LoggingService { - private readonly DiscordSocketClient _discord; + private readonly DiscordSocketClient _client; private readonly CommandService _commands; - private readonly IConfigurationRoot _config; + private readonly DiscordBotConfig _botConfig; private string LogDirectory { get; } private string LogFile => Path.Combine(LogDirectory, $"ServerManager_DiscordBot.{DateTime.Now:yyyyMMdd}.log"); - public LoggingService(DiscordSocketClient discord, CommandService commands, IConfigurationRoot config) + public LoggingService(DiscordSocketClient client, CommandService commands, DiscordBotConfig botConfig) { - _discord = discord; + _client = client; _commands = commands; - _config = config; + _botConfig = botConfig; // Get the data directory from the config file - var rootDirectory = _config["ServerManager:DataDirectory"] ?? AppContext.BaseDirectory; + var rootDirectory = _botConfig.DataDirectory ?? AppContext.BaseDirectory; LogDirectory = Path.Combine(rootDirectory, "logs"); - _discord.Log += OnLogAsync; + _client.Log += OnLogAsync; _commands.Log += OnLogAsync; } diff --git a/src/ServerManager.Discord/Services/ShutdownService.cs b/src/ServerManager.Discord/Services/ShutdownService.cs index d940c57d..1fa4a843 100644 --- a/src/ServerManager.Discord/Services/ShutdownService.cs +++ b/src/ServerManager.Discord/Services/ShutdownService.cs @@ -5,17 +5,17 @@ namespace ServerManagerTool.DiscordBot.Services { public class ShutdownService { - private readonly DiscordSocketClient _discord; + private readonly DiscordSocketClient _client; - public ShutdownService(DiscordSocketClient discord) + public ShutdownService(DiscordSocketClient client) { - _discord = discord; + _client = client; } public async Task StopAsync() { - await _discord.StopAsync(); - await _discord.LogoutAsync(); + await _client.StopAsync(); + await _client.LogoutAsync(); } } } diff --git a/src/ServerManager.Discord/Services/StartupService.cs b/src/ServerManager.Discord/Services/StartupService.cs index aee2f846..6ca86e86 100644 --- a/src/ServerManager.Discord/Services/StartupService.cs +++ b/src/ServerManager.Discord/Services/StartupService.cs @@ -1,7 +1,7 @@ using Discord; using Discord.Commands; using Discord.WebSocket; -using Microsoft.Extensions.Configuration; +using ServerManagerTool.DiscordBot.Models; using System; using System.Reflection; using System.Threading.Tasks; @@ -10,23 +10,23 @@ namespace ServerManagerTool.DiscordBot.Services { public class StartupService { - private readonly DiscordSocketClient _discord; + private readonly DiscordSocketClient _client; private readonly CommandService _commands; - private readonly IConfigurationRoot _config; - private readonly IServiceProvider _provider; + private readonly IServiceProvider _services; + private readonly DiscordBotConfig _botConfig; - public StartupService(DiscordSocketClient discord, CommandService commands, IConfigurationRoot config, IServiceProvider provider) + public StartupService(DiscordSocketClient client, CommandService commands, IServiceProvider services, DiscordBotConfig botConfig) { - _discord = discord; + _client = client; _commands = commands; - _config = config; - _provider = provider; + _services = services; + _botConfig = botConfig; } public async Task StartAsync() { // Get the discord token from the config file - var discordToken = _config["DiscordSettings:Token"]; + var discordToken = _botConfig?.DiscordToken; if (string.IsNullOrWhiteSpace(discordToken)) { @@ -34,12 +34,12 @@ namespace ServerManagerTool.DiscordBot.Services } // Login to discord - await _discord.LoginAsync(TokenType.Bot, discordToken); + await _client.LoginAsync(TokenType.Bot, discordToken); // Connect to the websocket - await _discord.StartAsync(); + await _client.StartAsync(); // Load commands and modules into the command service - await _commands.AddModulesAsync(Assembly.GetExecutingAssembly(), _provider); + await _commands.AddModulesAsync(Assembly.GetExecutingAssembly(), _services); } } } \ No newline at end of file