From 5a4278034b473ea14185494cb385e2090d9d9b6e Mon Sep 17 00:00:00 2001 From: Karl Essinger Date: Sun, 18 Aug 2024 23:40:14 +0200 Subject: [PATCH] Normalise indentation --- SCPDiscordBot/DiscordAPI.cs | 836 ++++++++++++++++----------------- SCPDiscordBot/SCPDiscordBot.cs | 118 ++--- 2 files changed, 477 insertions(+), 477 deletions(-) diff --git a/SCPDiscordBot/DiscordAPI.cs b/SCPDiscordBot/DiscordAPI.cs index e8dd841..7db77db 100644 --- a/SCPDiscordBot/DiscordAPI.cs +++ b/SCPDiscordBot/DiscordAPI.cs @@ -16,422 +16,422 @@ namespace SCPDiscord { - public class DiscordAPI - { - public static DiscordAPI instance { get; private set; } - public bool connected { get; private set; } - - private static readonly DiscordConfiguration config = new() - { - Token = "DUMMY_TOKEN", - TokenType = TokenType.Bot, - MinimumLogLevel = LogLevel.Debug, - AutoReconnect = true, - Intents = DiscordIntents.AllUnprivileged | DiscordIntents.MessageContents, - LogTimestampFormat = "HH:mm:ss", - LogUnknownAuditlogs = false, - LogUnknownEvents = false - }; - - public static DiscordClient client { get; private set; } = new(config); - private static DiscordRestClient restClient; - private SlashCommandsExtension commands; - - public static async Task Init() - { - try - { - Logger.Log("Setting up Discord client...", LogID.DISCORD); - - instance = new DiscordAPI(); - - // Checking log level - if (!Enum.TryParse(ConfigParser.config.bot.logLevel, true, out LogLevel logLevel)) - { - Logger.Warn("Log level '" + ConfigParser.config.bot.logLevel + "' invalid, using 'Information' instead.", LogID.CONFIG); - logLevel = LogLevel.Information; - } - - // Check if token is unset - if (ConfigParser.config.bot.token == "add-your-token-here" || ConfigParser.config.bot.token == "") - { - Logger.Fatal("You need to set your bot token in the config and start the bot again.", LogID.CONFIG); - throw new ArgumentException("Discord bot token has not been set in config"); - } - - // Setting up client configuration - config.Token = ConfigParser.config.bot.token; - config.MinimumLogLevel = logLevel; - client = new DiscordClient(config); - - ConfigParser.PrintConfig(); - - Logger.Log("Hooking events...", LogID.DISCORD); - client.SessionCreated += instance.OnReady; - client.GuildAvailable += instance.OnGuildAvailable; - client.ClientErrored += instance.OnClientError; - client.SocketErrored += instance.OnSocketError; - - if (!ConfigParser.config.bot.disableCommands) - { - client.UseInteractivity(new InteractivityConfiguration - { - PaginationBehaviour = PaginationBehaviour.Ignore, - PaginationDeletion = PaginationDeletion.DeleteMessage, - Timeout = TimeSpan.FromMinutes(15) - }); - - Logger.Log("Registering commands...", LogID.DISCORD); - instance.commands = client.UseSlashCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - //instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - instance.commands.RegisterCommands(); - - Logger.Log("Hooking command events...", LogID.DISCORD); - instance.commands.SlashCommandErrored += instance.OnCommandError; - } - - Logger.Log("Connecting to Discord...", LogID.DISCORD); - await client.ConnectAsync(); - - if (ConfigParser.config.bot.disableCommands) - { - await client.BulkOverwriteGlobalApplicationCommandsAsync(new DiscordApplicationCommand[] {}); - } - - Logger.Log("Initializing REST API...", LogID.DISCORD); - restClient = new DiscordRestClient(new DiscordConfiguration - { - Token = ConfigParser.config.bot.token, - TokenType = TokenType.Bot, - MinimumLogLevel = logLevel, - AutoReconnect = true, - Intents = DiscordIntents.AllUnprivileged | DiscordIntents.MessageContents, - LogTimestampFormat = "yyyy-MM-dd HH:mm:ss" - }); - await restClient.InitializeAsync(); - } - catch (Exception e) - { - Logger.Error(e.ToString(), LogID.DISCORD); - } - } - - public static void SetDisconnectedActivity() - { - if (!Enum.TryParse(ConfigParser.config.bot.presenceType, true, out ActivityType activityType)) - { - Logger.Warn("Activity type '" + ConfigParser.config.bot.presenceType + "' invalid, using 'Playing' instead.", LogID.DISCORD); - activityType = ActivityType.Playing; - } - - if (!Enum.TryParse(ConfigParser.config.bot.statusType, true, out UserStatus statusType)) - { - Logger.Warn("Status type '" + ConfigParser.config.bot.statusType + "' invalid, using 'DoNotDisturb' instead.", LogID.DISCORD); - statusType = UserStatus.DoNotDisturb; - } - - SetActivity(ConfigParser.config.bot.presenceText, activityType, statusType); - } - - public static void SetActivity(string activityText, ActivityType activityType, UserStatus status) - { - if (instance.connected) - { - client.UpdateStatusAsync(new DiscordActivity(activityText, activityType), status); - } - } - - public static async Task SendMessage(ulong channelID, string message) - { - if (!instance.connected) - { - return; - } - - try - { - DiscordChannel channel = await client.GetChannelAsync(channelID); - try - { - await channel.SendMessageAsync(message); - } - catch (UnauthorizedException) - { - Logger.Error("No permissions to send message in '" + channel.Name + "'", LogID.DISCORD); - } - } - catch (Exception) - { - Logger.Error("Could not send message in text channel '" + channelID + "'", LogID.DISCORD); - } - } - - public static async Task SendMessage(ulong channelID, DiscordEmbed message) - { - if (!instance.connected) - { - return; - } - - try - { - DiscordChannel channel = await client.GetChannelAsync(channelID); - try - { - await channel.SendMessageAsync(message); - } - catch (UnauthorizedException) - { - Logger.Error("No permissions to send message in '" + channel.Name + "'", LogID.DISCORD); - } - } - catch (Exception) - { - Logger.Error("Could not send embed in text channel '" + channelID + "'", LogID.DISCORD); - } - } - - public static async Task SendInteractionResponse(ulong interactionID, ulong channelID, DiscordEmbed message) - { - if (!instance.connected) - { - return; - } - - try - { - try - { - if (MessageScheduler.TryUncacheInteraction(interactionID, out InteractionContext interaction)) - { - await interaction.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(message)); - } - else - { - Logger.Error("Couldn't find interaction in the cache, sending as normal message instead."); - await SendMessage(channelID, message); - } - } - catch (UnauthorizedException) - { - Logger.Error("No permissions to send command response.", LogID.DISCORD); - } - } - catch (Exception e) - { - Logger.Error("Could not send command response.\n" + e, LogID.DISCORD); - } - } - - public static async Task SendPaginatedResponse(ulong interactionID, ulong channelID, ulong userID, List message) - { - if (!instance.connected) - { - return; - } - - try - { - try - { - if (MessageScheduler.TryUncacheInteraction(interactionID, out InteractionContext interaction)) - { - await interaction.Interaction.SendPaginatedResponseAsync(false, interaction.User, message, default, - default, default, default, true); - } - else - { - Logger.Error("Couldn't find interaction in the cache, sending as normal message instead."); - await SendPaginatedMessage(channelID, userID, message); - } - } - catch (UnauthorizedException) - { - Logger.Error("No permissions to send command response.", LogID.DISCORD); - } - } - catch (Exception e) - { - Logger.Error("Could not send command response.\n" + e, LogID.DISCORD); - } - } - - public static async Task SendPaginatedMessage(ulong channelID, ulong userID, IEnumerable pages) - { - if (!instance.connected) - { - return; - } - - try - { - try - { - DiscordChannel channel = await client.GetChannelAsync(channelID); - DiscordUser user = await client.GetUserAsync(userID); - - await channel.SendPaginatedMessageAsync(user, pages); - } - catch (UnauthorizedException) - { - Logger.Error("No permissions to send command response.", LogID.DISCORD); - } - } - catch (Exception e) - { - Logger.Error("Could not send command response.\n" + e, LogID.DISCORD); - } - } - - public static async Task GetPlayerRoles(ulong userID, string steamID) - { - if (!instance.connected) - { - return; - } - - if (ConfigParser.config.bot.serverId == 0) - { - Logger.Warn("Plugin attempted to use role sync, but no server ID was set in the config. Ignoring request...", LogID.DISCORD); - return; - } - - try - { - DiscordGuild guild = await client.GetGuildAsync(ConfigParser.config.bot.serverId); - DiscordMember member = await guild.GetMemberAsync(userID); - - Interface.MessageWrapper message = new Interface.MessageWrapper - { - UserInfo = new Interface.UserInfo - { - DiscordUserID = userID, - SteamIDOrIP = steamID, - DiscordDisplayName = member.DisplayName, - DiscordUsername = member.Username - } - }; - message.UserInfo.RoleIDs.AddRange(member.Roles.Select(role => role.Id)); - message.UserInfo.RoleIDs.Add(member.Guild.EveryoneRole.Id); - await NetworkSystem.SendMessage(message, null); - } - catch (Exception e) - { - Logger.Warn("Couldn't find discord server or server member for role syncing requested by plugin. Discord ID: " + userID + " SteamID/IP: " + steamID, LogID.DISCORD); - Logger.Debug("Exception: \n" + e, LogID.DISCORD); - } - } - - public Task OnReady(DiscordClient discordClient, SessionReadyEventArgs e) - { - instance.connected = true; - Logger.Log("Connected to Discord.", LogID.DISCORD); - SetDisconnectedActivity(); - return Task.CompletedTask; - } - - public Task OnSocketError(DiscordClient discordClient, SocketErrorEventArgs e) - { - Logger.Debug("Discord socket error: " + e.Exception, LogID.DISCORD); - return Task.CompletedTask; - } - - public async Task OnGuildAvailable(DiscordClient discordClient, GuildCreateEventArgs e) - { - Logger.Log("Found Discord server: " + e.Guild.Name + " (" + e.Guild.Id + ")", LogID.DISCORD); - - if (SCPDiscordBot.commandLineArgs.serversToLeave.Contains(e.Guild.Id)) - { - Logger.Warn("LEAVING DISCORD SERVER AS REQUESTED: " + e.Guild.Name + " (" + e.Guild.Id + ")", LogID.DISCORD); - await e.Guild.LeaveAsync(); - return; - } - - IReadOnlyDictionary roles = e.Guild.Roles; - - foreach ((ulong roleID, DiscordRole role) in roles) - { - Logger.Debug(role.Name.PadRight(40, '.') + roleID, LogID.DISCORD); - } - } - - public Task OnClientError(DiscordClient discordClient, ClientErrorEventArgs e) - { - Logger.Error($"Exception occured: {e.Exception.GetType()}: {e.Exception}", LogID.DISCORD); - - return Task.CompletedTask; - } - - public Task OnCommandError(SlashCommandsExtension commandSystem, SlashCommandErrorEventArgs e) - { - switch (e.Exception) - { - case ArgumentException: - { - DiscordEmbed error = new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Internal error occurred." - }; - e.Context.Channel.SendMessageAsync(error); - return Task.CompletedTask; - } - - case SlashExecutionChecksFailedException ex: - { - foreach (SlashCheckBaseAttribute attr in ex.FailedChecks) - { - DiscordEmbed error = new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = ParseFailedCheck(attr) - }; - e.Context.Channel.SendMessageAsync(error); - } - return Task.CompletedTask; - } - - default: - { - Logger.Error("Exception occured: " + e.Exception, LogID.DISCORD); - DiscordEmbed error = new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Internal error occured, please report this to the developer." - }; - e.Context.Channel.SendMessageAsync(error); - return Task.CompletedTask; - } - } - } - - private static string ParseFailedCheck(SlashCheckBaseAttribute attr) - { - return attr switch - { - SlashRequireDirectMessageAttribute => "This command can only be used in direct messages!", - SlashRequireOwnerAttribute => "Only the server owner can use that command!", - SlashRequirePermissionsAttribute => "You don't have permission to do that!", - SlashRequireBotPermissionsAttribute => "The bot doesn't have the required permissions to do that!", - SlashRequireUserPermissionsAttribute => "You don't have permission to do that!", - SlashRequireGuildAttribute => "This command has to be used in a Discord server!", - _ => "Unknown Discord API error occured, please try again later." - }; - } - } + public class DiscordAPI + { + public static DiscordAPI instance { get; private set; } + public bool connected { get; private set; } + + private static readonly DiscordConfiguration config = new() + { + Token = "DUMMY_TOKEN", + TokenType = TokenType.Bot, + MinimumLogLevel = LogLevel.Debug, + AutoReconnect = true, + Intents = DiscordIntents.AllUnprivileged | DiscordIntents.MessageContents, + LogTimestampFormat = "HH:mm:ss", + LogUnknownAuditlogs = false, + LogUnknownEvents = false + }; + + public static DiscordClient client { get; private set; } = new(config); + private static DiscordRestClient restClient; + private SlashCommandsExtension commands; + + public static async Task Init() + { + try + { + Logger.Log("Setting up Discord client...", LogID.DISCORD); + + instance = new DiscordAPI(); + + // Checking log level + if (!Enum.TryParse(ConfigParser.config.bot.logLevel, true, out LogLevel logLevel)) + { + Logger.Warn("Log level '" + ConfigParser.config.bot.logLevel + "' invalid, using 'Information' instead.", LogID.CONFIG); + logLevel = LogLevel.Information; + } + + // Check if token is unset + if (ConfigParser.config.bot.token == "add-your-token-here" || ConfigParser.config.bot.token == "") + { + Logger.Fatal("You need to set your bot token in the config and start the bot again.", LogID.CONFIG); + throw new ArgumentException("Discord bot token has not been set in config"); + } + + // Setting up client configuration + config.Token = ConfigParser.config.bot.token; + config.MinimumLogLevel = logLevel; + client = new DiscordClient(config); + + ConfigParser.PrintConfig(); + + Logger.Log("Hooking events...", LogID.DISCORD); + client.SessionCreated += instance.OnReady; + client.GuildAvailable += instance.OnGuildAvailable; + client.ClientErrored += instance.OnClientError; + client.SocketErrored += instance.OnSocketError; + + if (!ConfigParser.config.bot.disableCommands) + { + client.UseInteractivity(new InteractivityConfiguration + { + PaginationBehaviour = PaginationBehaviour.Ignore, + PaginationDeletion = PaginationDeletion.DeleteMessage, + Timeout = TimeSpan.FromMinutes(15) + }); + + Logger.Log("Registering commands...", LogID.DISCORD); + instance.commands = client.UseSlashCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + //instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + instance.commands.RegisterCommands(); + + Logger.Log("Hooking command events...", LogID.DISCORD); + instance.commands.SlashCommandErrored += instance.OnCommandError; + } + + Logger.Log("Connecting to Discord...", LogID.DISCORD); + await client.ConnectAsync(); + + if (ConfigParser.config.bot.disableCommands) + { + await client.BulkOverwriteGlobalApplicationCommandsAsync(new DiscordApplicationCommand[] {}); + } + + Logger.Log("Initializing REST API...", LogID.DISCORD); + restClient = new DiscordRestClient(new DiscordConfiguration + { + Token = ConfigParser.config.bot.token, + TokenType = TokenType.Bot, + MinimumLogLevel = logLevel, + AutoReconnect = true, + Intents = DiscordIntents.AllUnprivileged | DiscordIntents.MessageContents, + LogTimestampFormat = "yyyy-MM-dd HH:mm:ss" + }); + await restClient.InitializeAsync(); + } + catch (Exception e) + { + Logger.Error(e.ToString(), LogID.DISCORD); + } + } + + public static void SetDisconnectedActivity() + { + if (!Enum.TryParse(ConfigParser.config.bot.presenceType, true, out ActivityType activityType)) + { + Logger.Warn("Activity type '" + ConfigParser.config.bot.presenceType + "' invalid, using 'Playing' instead.", LogID.DISCORD); + activityType = ActivityType.Playing; + } + + if (!Enum.TryParse(ConfigParser.config.bot.statusType, true, out UserStatus statusType)) + { + Logger.Warn("Status type '" + ConfigParser.config.bot.statusType + "' invalid, using 'DoNotDisturb' instead.", LogID.DISCORD); + statusType = UserStatus.DoNotDisturb; + } + + SetActivity(ConfigParser.config.bot.presenceText, activityType, statusType); + } + + public static void SetActivity(string activityText, ActivityType activityType, UserStatus status) + { + if (instance.connected) + { + client.UpdateStatusAsync(new DiscordActivity(activityText, activityType), status); + } + } + + public static async Task SendMessage(ulong channelID, string message) + { + if (!instance.connected) + { + return; + } + + try + { + DiscordChannel channel = await client.GetChannelAsync(channelID); + try + { + await channel.SendMessageAsync(message); + } + catch (UnauthorizedException) + { + Logger.Error("No permissions to send message in '" + channel.Name + "'", LogID.DISCORD); + } + } + catch (Exception) + { + Logger.Error("Could not send message in text channel '" + channelID + "'", LogID.DISCORD); + } + } + + public static async Task SendMessage(ulong channelID, DiscordEmbed message) + { + if (!instance.connected) + { + return; + } + + try + { + DiscordChannel channel = await client.GetChannelAsync(channelID); + try + { + await channel.SendMessageAsync(message); + } + catch (UnauthorizedException) + { + Logger.Error("No permissions to send message in '" + channel.Name + "'", LogID.DISCORD); + } + } + catch (Exception) + { + Logger.Error("Could not send embed in text channel '" + channelID + "'", LogID.DISCORD); + } + } + + public static async Task SendInteractionResponse(ulong interactionID, ulong channelID, DiscordEmbed message) + { + if (!instance.connected) + { + return; + } + + try + { + try + { + if (MessageScheduler.TryUncacheInteraction(interactionID, out InteractionContext interaction)) + { + await interaction.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(message)); + } + else + { + Logger.Error("Couldn't find interaction in the cache, sending as normal message instead."); + await SendMessage(channelID, message); + } + } + catch (UnauthorizedException) + { + Logger.Error("No permissions to send command response.", LogID.DISCORD); + } + } + catch (Exception e) + { + Logger.Error("Could not send command response.\n" + e, LogID.DISCORD); + } + } + + public static async Task SendPaginatedResponse(ulong interactionID, ulong channelID, ulong userID, List message) + { + if (!instance.connected) + { + return; + } + + try + { + try + { + if (MessageScheduler.TryUncacheInteraction(interactionID, out InteractionContext interaction)) + { + await interaction.Interaction.SendPaginatedResponseAsync(false, interaction.User, message, default, + default, default, default, true); + } + else + { + Logger.Error("Couldn't find interaction in the cache, sending as normal message instead."); + await SendPaginatedMessage(channelID, userID, message); + } + } + catch (UnauthorizedException) + { + Logger.Error("No permissions to send command response.", LogID.DISCORD); + } + } + catch (Exception e) + { + Logger.Error("Could not send command response.\n" + e, LogID.DISCORD); + } + } + + public static async Task SendPaginatedMessage(ulong channelID, ulong userID, IEnumerable pages) + { + if (!instance.connected) + { + return; + } + + try + { + try + { + DiscordChannel channel = await client.GetChannelAsync(channelID); + DiscordUser user = await client.GetUserAsync(userID); + + await channel.SendPaginatedMessageAsync(user, pages); + } + catch (UnauthorizedException) + { + Logger.Error("No permissions to send command response.", LogID.DISCORD); + } + } + catch (Exception e) + { + Logger.Error("Could not send command response.\n" + e, LogID.DISCORD); + } + } + + public static async Task GetPlayerRoles(ulong userID, string steamID) + { + if (!instance.connected) + { + return; + } + + if (ConfigParser.config.bot.serverId == 0) + { + Logger.Warn("Plugin attempted to use role sync, but no server ID was set in the config. Ignoring request...", LogID.DISCORD); + return; + } + + try + { + DiscordGuild guild = await client.GetGuildAsync(ConfigParser.config.bot.serverId); + DiscordMember member = await guild.GetMemberAsync(userID); + + Interface.MessageWrapper message = new Interface.MessageWrapper + { + UserInfo = new Interface.UserInfo + { + DiscordUserID = userID, + SteamIDOrIP = steamID, + DiscordDisplayName = member.DisplayName, + DiscordUsername = member.Username + } + }; + message.UserInfo.RoleIDs.AddRange(member.Roles.Select(role => role.Id)); + message.UserInfo.RoleIDs.Add(member.Guild.EveryoneRole.Id); + await NetworkSystem.SendMessage(message, null); + } + catch (Exception e) + { + Logger.Warn("Couldn't find discord server or server member for role syncing requested by plugin. Discord ID: " + userID + " SteamID/IP: " + steamID, LogID.DISCORD); + Logger.Debug("Exception: \n" + e, LogID.DISCORD); + } + } + + public Task OnReady(DiscordClient discordClient, SessionReadyEventArgs e) + { + instance.connected = true; + Logger.Log("Connected to Discord.", LogID.DISCORD); + SetDisconnectedActivity(); + return Task.CompletedTask; + } + + public Task OnSocketError(DiscordClient discordClient, SocketErrorEventArgs e) + { + Logger.Debug("Discord socket error: " + e.Exception, LogID.DISCORD); + return Task.CompletedTask; + } + + public async Task OnGuildAvailable(DiscordClient discordClient, GuildCreateEventArgs e) + { + Logger.Log("Found Discord server: " + e.Guild.Name + " (" + e.Guild.Id + ")", LogID.DISCORD); + + if (SCPDiscordBot.commandLineArgs.serversToLeave.Contains(e.Guild.Id)) + { + Logger.Warn("LEAVING DISCORD SERVER AS REQUESTED: " + e.Guild.Name + " (" + e.Guild.Id + ")", LogID.DISCORD); + await e.Guild.LeaveAsync(); + return; + } + + IReadOnlyDictionary roles = e.Guild.Roles; + + foreach ((ulong roleID, DiscordRole role) in roles) + { + Logger.Debug(role.Name.PadRight(40, '.') + roleID, LogID.DISCORD); + } + } + + public Task OnClientError(DiscordClient discordClient, ClientErrorEventArgs e) + { + Logger.Error($"Exception occured: {e.Exception.GetType()}: {e.Exception}", LogID.DISCORD); + + return Task.CompletedTask; + } + + public Task OnCommandError(SlashCommandsExtension commandSystem, SlashCommandErrorEventArgs e) + { + switch (e.Exception) + { + case ArgumentException: + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Internal error occurred." + }; + e.Context.Channel.SendMessageAsync(error); + return Task.CompletedTask; + } + + case SlashExecutionChecksFailedException ex: + { + foreach (SlashCheckBaseAttribute attr in ex.FailedChecks) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = ParseFailedCheck(attr) + }; + e.Context.Channel.SendMessageAsync(error); + } + return Task.CompletedTask; + } + + default: + { + Logger.Error("Exception occured: " + e.Exception, LogID.DISCORD); + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Internal error occured, please report this to the developer." + }; + e.Context.Channel.SendMessageAsync(error); + return Task.CompletedTask; + } + } + } + + private static string ParseFailedCheck(SlashCheckBaseAttribute attr) + { + return attr switch + { + SlashRequireDirectMessageAttribute => "This command can only be used in direct messages!", + SlashRequireOwnerAttribute => "Only the server owner can use that command!", + SlashRequirePermissionsAttribute => "You don't have permission to do that!", + SlashRequireBotPermissionsAttribute => "The bot doesn't have the required permissions to do that!", + SlashRequireUserPermissionsAttribute => "You don't have permission to do that!", + SlashRequireGuildAttribute => "This command has to be used in a Discord server!", + _ => "Unknown Discord API error occured, please try again later." + }; + } + } } diff --git a/SCPDiscordBot/SCPDiscordBot.cs b/SCPDiscordBot/SCPDiscordBot.cs index c5f30e4..18c6b8d 100644 --- a/SCPDiscordBot/SCPDiscordBot.cs +++ b/SCPDiscordBot/SCPDiscordBot.cs @@ -8,73 +8,73 @@ namespace SCPDiscord { - public class SCPDiscordBot - { - public class CommandLineArguments - { - [Option('c', "config", Required = false, HelpText = "Select a config file to use.", Default = "config.yml", MetaValue = "PATH")] - public string configPath { get; set; } + public class SCPDiscordBot + { + public class CommandLineArguments + { + [Option('c', "config", Required = false, HelpText = "Select a config file to use.", Default = "config.yml", MetaValue = "PATH")] + public string configPath { get; set; } - [Option( - "leave", - Required = false, - HelpText = "Leaves one or more Discord servers. " + - "You can check which servers your bot is in when it starts up.", - MetaValue = "ID,ID,ID...", - Separator = ',' - )] - public IEnumerable serversToLeave { get; set; } - } + [Option( + "leave", + Required = false, + HelpText = "Leaves one or more Discord servers. " + + "You can check which servers your bot is in when it starts up.", + MetaValue = "ID,ID,ID...", + Separator = ',' + )] + public IEnumerable serversToLeave { get; set; } + } - internal static CommandLineArguments commandLineArgs; + internal static CommandLineArguments commandLineArgs; - public static void Main(string[] args) - { - commandLineArgs = Parser.Default.ParseArguments(args).Value; + public static void Main(string[] args) + { + commandLineArgs = Parser.Default.ParseArguments(args).Value; - if (args.Contains("--help") || args.Contains("--version")) - { - return; - } + if (args.Contains("--help") || args.Contains("--version")) + { + return; + } - new SCPDiscordBot().MainAsync().GetAwaiter().GetResult(); - } + new SCPDiscordBot().MainAsync().GetAwaiter().GetResult(); + } - private async Task MainAsync() - { - Logger.Log("Starting SCPDiscord version " + GetVersion() + "...", LogID.GENERAL); - try - { - try - { - ConfigParser.LoadConfig(); - } - catch (Exception e) - { - Logger.Fatal("Error loading config!\n" + e); - return; - } + private async Task MainAsync() + { + Logger.Log("Starting SCPDiscord version " + GetVersion() + "...", LogID.GENERAL); + try + { + try + { + ConfigParser.LoadConfig(); + } + catch (Exception e) + { + Logger.Fatal("Error loading config!\n" + e); + return; + } - await DiscordAPI.Init(); + await DiscordAPI.Init(); - new Thread(() => new StartNetworkSystem()).Start(); - new Thread(() => new StartMessageScheduler()).Start(); + new Thread(() => new StartNetworkSystem()).Start(); + new Thread(() => new StartMessageScheduler()).Start(); - // Block this task until the program is closed. - await Task.Delay(-1); - } - catch (Exception e) - { - Logger.Fatal("Fatal error:", LogID.GENERAL); - Logger.Fatal(e.ToString(), LogID.GENERAL); - Console.ReadLine(); - } - } + // Block this task until the program is closed. + await Task.Delay(-1); + } + catch (Exception e) + { + Logger.Fatal("Fatal error:", LogID.GENERAL); + Logger.Fatal(e.ToString(), LogID.GENERAL); + Console.ReadLine(); + } + } - public static string GetVersion() - { - Version version = Assembly.GetEntryAssembly()?.GetName().Version; - return version?.Major + "." + version?.Minor + "." + version?.Build + (version?.Revision == 0 ? "" : "-" + (char)(64 + version?.Revision ?? 0)); - } - } + public static string GetVersion() + { + Version version = Assembly.GetEntryAssembly()?.GetName().Version; + return version?.Major + "." + version?.Minor + "." + version?.Build + (version?.Revision == 0 ? "" : "-" + (char)(64 + version?.Revision ?? 0)); + } + } }