Bot cleanup

Language file updates
This commit is contained in:
Brett Hewitson 2021-12-18 10:10:43 +10:00
parent e72f5fb28f
commit 40b85340ae
21 changed files with 258 additions and 129 deletions

View file

@ -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<CommandInfo> 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);
}
}
}

View file

@ -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;
}

View file

@ -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();
}
}
}

View file

@ -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);
}
}
}