diff --git a/src/AdvancedBot.Core/BotClient.cs b/src/AdvancedBot.Core/BotClient.cs index 4612a6b..8400061 100644 --- a/src/AdvancedBot.Core/BotClient.cs +++ b/src/AdvancedBot.Core/BotClient.cs @@ -1,4 +1,8 @@ -using AdvancedBot.Core.Commands; +using System; +using System.IO; +using System.Reflection; +using System.Threading.Tasks; +using AdvancedBot.Core.Commands; using AdvancedBot.Core.Entities; using AdvancedBot.Core.Services; using AdvancedBot.Core.Services.DataStorage; @@ -7,32 +11,28 @@ using Discord.WebSocket; using GL.NET; using Microsoft.Extensions.DependencyInjection; -using System; -using System.IO; -using System.Reflection; -using System.Threading.Tasks; namespace AdvancedBot.Core { public class BotClient { - private readonly DiscordSocketClient _client; - private readonly CustomCommandService _commands; - private IServiceProvider _services; - private readonly InteractionService _interactions; - private AccountService _accounts; - private readonly GLClient _glClient; + private readonly DiscordSocketClient client; + private readonly CustomCommandService commands; + private IServiceProvider services; + private readonly InteractionService interactions; + private AccountService accounts; + private readonly GLClient glClient; public BotClient(CustomCommandService commands = null, DiscordSocketClient client = null) { - _client = client ?? new DiscordSocketClient(new DiscordSocketConfig + this.client = client ?? new DiscordSocketClient(new DiscordSocketConfig { LogLevel = LogSeverity.Info, AlwaysDownloadUsers = true, MessageCacheSize = 1000 }); - _commands = commands ?? new CustomCommandService(new CustomCommandServiceConfig + this.commands = commands ?? new CustomCommandService(new CustomCommandServiceConfig { CaseSensitiveCommands = false, LogLevel = LogSeverity.Info, @@ -45,44 +45,44 @@ public BotClient(CustomCommandService commands = null, DiscordSocketClient clien #endif }); - _interactions = new InteractionService(_client.Rest, new InteractionServiceConfig() { UseCompiledLambda = true }); + interactions = new InteractionService(this.client.Rest, new InteractionServiceConfig() { UseCompiledLambda = true }); - var envVar = Environment.GetEnvironmentVariable("PhoenixApiCred"); + string envVar = Environment.GetEnvironmentVariable("PhoenixApiCred"); if (envVar == null) { - LogAsync(new LogMessage(LogSeverity.Warning, "BotClient", "Initializing GLClient without tokens!")); - _glClient = new GLClient("", "", ""); + logAsync(new LogMessage(LogSeverity.Warning, "BotClient", "Initializing GLClient without tokens!")); + glClient = new GLClient("", "", ""); return; } - var creds = envVar.Split(';'); - _glClient = new GLClient(creds[0], creds[1], creds[2]); + string[] creds = envVar.Split(';'); + glClient = new GLClient(creds[0], creds[1], creds[2]); } public async Task InitializeAsync() { Console.Title = $"Launching Discord Bot..."; - _services = ConfigureServices(); - _accounts = _services.GetRequiredService(); + services = configureServices(); + accounts = services.GetRequiredService(); - _client.Ready += OnReadyAsync; - _interactions.SlashCommandExecuted += OnSlashCommandExecuted; + client.Ready += onReadyAsync; + interactions.SlashCommandExecuted += onSlashCommandExecuted; - _client.Log += LogAsync; - _commands.Log += LogAsync; + client.Log += logAsync; + commands.Log += logAsync; - var token = Environment.GetEnvironmentVariable("Token"); + string token = Environment.GetEnvironmentVariable("Token"); - await Task.Delay(10).ContinueWith(t => _client.LoginAsync(TokenType.Bot, token)); - await _client.StartAsync(); + await Task.Delay(10).ContinueWith(t => client.LoginAsync(TokenType.Bot, token)); + await client.StartAsync(); await Task.Delay(-1); } - private async Task OnReadyAsync() + private async Task onReadyAsync() { - Console.Title = $"Running Discord Bot: {_client.CurrentUser.Username}"; + Console.Title = $"Running Discord Bot: {client.CurrentUser.Username}"; Game activity = new( "Galaxy Life", @@ -90,37 +90,37 @@ private async Task OnReadyAsync() ActivityProperties.Instance ); - await _client.SetActivityAsync(activity); - Console.WriteLine($"Guild count: {_client.Guilds.Count}"); + await client.SetActivityAsync(activity); + Console.WriteLine($"Guild count: {client.Guilds.Count}"); - await _interactions.AddModulesAsync(Assembly.GetExecutingAssembly(), _services); - Console.WriteLine($"Modules count: {_interactions.Modules.Count}"); - Console.WriteLine($"SlashCommands count: {_interactions.SlashCommands.Count}"); + await interactions.AddModulesAsync(Assembly.GetExecutingAssembly(), services); + Console.WriteLine($"Modules count: {interactions.Modules.Count}"); + Console.WriteLine($"SlashCommands count: {interactions.SlashCommands.Count}"); #if DEBUG Console.WriteLine("Registered all commands to test server"); - await _interactions.RegisterCommandsToGuildAsync(696343127144923158, false); + await interactions.RegisterCommandsToGuildAsync(696343127144923158, false); #else - Console.WriteLine("Registered all commands globally"); - await _interactions.RegisterCommandsGloballyAsync(); + Console.WriteLine("Registered all commands globally"); + await interactions.RegisterCommandsGloballyAsync(); #endif - _client.InteractionCreated += async (x) => + client.InteractionCreated += async (x) => { - var context = new SocketInteractionContext(_client, x); - await _interactions.ExecuteCommandAsync(context, _services); + var context = new SocketInteractionContext(client, x); + await interactions.ExecuteCommandAsync(context, services); }; - _glClient.ErrorThrown += OnGLErrorThrown; + glClient.ErrorThrown += onGLErrorThrown; } - private async void OnGLErrorThrown(object sender, ErrorEventArgs e) + private async void onGLErrorThrown(object sender, ErrorEventArgs e) { var exception = e.GetException(); - await LogAsync(new LogMessage(LogSeverity.Critical, "GL.NET", exception.Message, exception)); + await logAsync(new LogMessage(LogSeverity.Critical, "GL.NET", exception.Message, exception)); } - private Task LogAsync(LogMessage msg) + private Task logAsync(LogMessage msg) { if (msg.Exception != null) { @@ -134,7 +134,7 @@ private Task LogAsync(LogMessage msg) return Task.CompletedTask; } - private async Task OnSlashCommandExecuted(SlashCommandInfo cmd, IInteractionContext context, IResult result) + private async Task onSlashCommandExecuted(SlashCommandInfo cmd, IInteractionContext context, IResult result) { if (!result.IsSuccess) { @@ -149,8 +149,8 @@ private async Task OnSlashCommandExecuted(SlashCommandInfo cmd, IInteractionCont } } - var id = context.Interaction.IsDMInteraction ? context.User.Id : context.Guild.Id; - var acc = _accounts.GetOrCreateAccount(id, !context.Interaction.IsDMInteraction); + ulong id = context.Interaction.IsDMInteraction ? context.User.Id : context.Guild.Id; + var acc = accounts.GetOrCreateAccount(id, !context.Interaction.IsDMInteraction); var cmdInfo = acc.CommandStats.Find(x => x.Name == cmd.Name); @@ -167,16 +167,16 @@ private async Task OnSlashCommandExecuted(SlashCommandInfo cmd, IInteractionCont cmdInfo.TimesFailed++; } - _accounts.SaveAccount(acc); + accounts.SaveAccount(acc); } - private ServiceProvider ConfigureServices() + private ServiceProvider configureServices() { return new ServiceCollection() - .AddSingleton(_client) - .AddSingleton(_commands) - .AddSingleton(_interactions) - .AddSingleton(_glClient) + .AddSingleton(client) + .AddSingleton(commands) + .AddSingleton(interactions) + .AddSingleton(glClient) .AddSingleton() .AddSingleton() .AddSingleton() diff --git a/src/AdvancedBot.Core/Commands/CustomCommandService.cs b/src/AdvancedBot.Core/Commands/CustomCommandService.cs index 39c0458..cbc7a6b 100644 --- a/src/AdvancedBot.Core/Commands/CustomCommandService.cs +++ b/src/AdvancedBot.Core/Commands/CustomCommandService.cs @@ -1,11 +1,11 @@ -using AdvancedBot.Core.Services; -using Discord; -using Discord.Commands; -using Humanizer; using System; using System.Linq; using System.Text; using System.Threading.Tasks; +using AdvancedBot.Core.Services; +using Discord; +using Discord.Commands; +using Humanizer; namespace AdvancedBot.Core.Commands { @@ -13,30 +13,30 @@ public class CustomCommandService : CommandService { public PaginatorService Paginator { get; set; } public ulong LogChannelId; - private readonly string _documentationUrl; - private readonly string _sourceRepo; - private readonly string _contributors; - private readonly bool _botIsPrivate; + private readonly string documentationUrl; + private readonly string sourceRepo; + private readonly string contributors; + private readonly bool botIsPrivate; public CustomCommandService() : base() { } public CustomCommandService(CustomCommandServiceConfig config) : base(config) { - _documentationUrl = config.DocumentationUrl; - _sourceRepo = config.RepositoryUrl; - _contributors = config.Contributors; - _botIsPrivate = config.BotInviteIsPrivate; + documentationUrl = config.DocumentationUrl; + sourceRepo = config.RepositoryUrl; + contributors = config.Contributors; + botIsPrivate = config.BotInviteIsPrivate; LogChannelId = config.LogChannelId; } public async Task SendBotInfoAsync(IInteractionContext context) { - var botName = context.Client.CurrentUser.Username; - var botAvatar = context.Client.CurrentUser.GetDisplayAvatarUrl(); + string botName = context.Client.CurrentUser.Username; + string botAvatar = context.Client.CurrentUser.GetDisplayAvatarUrl(); - var repoLink = string.IsNullOrEmpty(_sourceRepo) ? $"Unavailable" : $"[GitHub repository]({_sourceRepo})"; - var docsLink = string.IsNullOrEmpty(_documentationUrl) ? $"Unavailable" : $"[Read the docs]({_documentationUrl})"; - var inviteLink = $"[Invite link](https://discordapp.com/api/oauth2/authorize?client_id={context.Client.CurrentUser.Id}&permissions=8&scope=bot)"; + string repoLink = string.IsNullOrEmpty(sourceRepo) ? $"Unavailable" : $"[GitHub repository]({sourceRepo})"; + string docsLink = string.IsNullOrEmpty(documentationUrl) ? $"Unavailable" : $"[Read the docs]({documentationUrl})"; + string inviteLink = $"[Invite link](https://discordapp.com/api/oauth2/authorize?client_id={context.Client.CurrentUser.Id}&permissions=8&scope=bot)"; var embed = new EmbedBuilder() .WithTitle($"About {botName}") @@ -50,12 +50,12 @@ public async Task SendBotInfoAsync(IInteractionContext context) .WithIconUrl(context.User.GetDisplayAvatarUrl())) .WithCurrentTimestamp(); - if (!_botIsPrivate) + if (!botIsPrivate) { embed.AddField("Invitation", inviteLink, true); } - embed.AddField("Developed by", _contributors); + embed.AddField("Developed by", contributors); await context.Interaction.ModifyOriginalResponseAsync(msg => msg.Embeds = new Embed[] { embed.Build() }); } @@ -77,8 +77,8 @@ public static string GenerateCommandUsage(CommandInfo command, string prefix) for (int i = 0; i < command.Parameters.Count; i++) { - var pref = command.Parameters[i].IsOptional ? "[" : "<"; - var suff = command.Parameters[i].IsOptional ? "]" : ">"; + string pref = command.Parameters[i].IsOptional ? "[" : "<"; + string suff = command.Parameters[i].IsOptional ? "]" : ">"; parameters.Append($"{pref}{command.Parameters[i].Name.Underscore().Dasherize()}{suff} "); } diff --git a/src/AdvancedBot.Core/Commands/Modules/ChannelInfoModule.cs b/src/AdvancedBot.Core/Commands/Modules/ChannelInfoModule.cs index affba0e..b0faeae 100644 --- a/src/AdvancedBot.Core/Commands/Modules/ChannelInfoModule.cs +++ b/src/AdvancedBot.Core/Commands/Modules/ChannelInfoModule.cs @@ -1,11 +1,11 @@ +using System; +using System.Threading.Tasks; using AdvancedBot.Core.Commands.Preconditions; using AdvancedBot.Core.Entities; using AdvancedBot.Core.Entities.Enums; using AdvancedBot.Core.Services; using Discord; using Discord.Interactions; -using System; -using System.Threading.Tasks; namespace AdvancedBot.Core.Commands.Modules { @@ -13,11 +13,11 @@ namespace AdvancedBot.Core.Commands.Modules [RequireCustomPermission(GuildPermission.ManageChannels)] public class ChannelInfoModule : TopModule { - private readonly ChannelCounterService _counter; + private readonly ChannelCounterService counter; public ChannelInfoModule(ChannelCounterService counter) { - _counter = counter; + this.counter = counter; } [SlashCommand("setup", "Set up the channel counter")] @@ -34,8 +34,8 @@ public async Task SetupChannelCountersAsync() { var counter = new ChannelCounter(voiceChannel.Id, ChannelCounterType.FlashStatus); - _counter.AddNewChannelCounter(Context.Guild.Id, counter); - await _counter.UpdateChannelAsync(Accounts.GetOrCreateAccount(Context.Guild.Id), counter); + this.counter.AddNewChannelCounter(Context.Guild.Id, counter); + await this.counter.UpdateChannelAsync(Accounts.GetOrCreateAccount(Context.Guild.Id), counter); await ModifyOriginalResponseAsync(msg => msg.Content = $"Setup the Server Status Voice Channel {voiceChannel.Mention}"); } diff --git a/src/AdvancedBot.Core/Commands/Modules/ComponentResponsesModule.cs b/src/AdvancedBot.Core/Commands/Modules/ComponentResponsesModule.cs index 487cd3c..e06e877 100644 --- a/src/AdvancedBot.Core/Commands/Modules/ComponentResponsesModule.cs +++ b/src/AdvancedBot.Core/Commands/Modules/ComponentResponsesModule.cs @@ -1,6 +1,6 @@ +using System.Threading.Tasks; using AdvancedBot.Core.Services; using Discord.Interactions; -using System.Threading.Tasks; namespace AdvancedBot.Core.Commands.Modules { diff --git a/src/AdvancedBot.Core/Commands/Modules/DevModule.cs b/src/AdvancedBot.Core/Commands/Modules/DevModule.cs index c8bea3e..51fbbb8 100644 --- a/src/AdvancedBot.Core/Commands/Modules/DevModule.cs +++ b/src/AdvancedBot.Core/Commands/Modules/DevModule.cs @@ -1,10 +1,10 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; using AdvancedBot.Core.Commands.Preconditions; using AdvancedBot.Core.Entities; using Discord; using Discord.Interactions; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace AdvancedBot.Core.Commands.Modules { @@ -12,11 +12,11 @@ namespace AdvancedBot.Core.Commands.Modules [RequirePrivateList] public class DevModule : TopModule { - private readonly InteractionService _interactions; + private readonly InteractionService interactions; public DevModule(InteractionService interactions) { - _interactions = interactions; + this.interactions = interactions; } [SlashCommand("allstats", "Shows combined stats from all servers")] @@ -34,7 +34,7 @@ public async Task ShowAllStatsAsync([Choice("All", "all"), Choice("Dms", "dms"), } else accounts = Accounts.GetAllAccounts(); - var allInfos = CalculateCommandStatsOnAccounts(accounts); + var allInfos = calculateCommandStatsOnAccounts(accounts); var fields = new List(); var commands = allInfos.OrderByDescending(x => x.TimesRun).ToArray(); @@ -48,7 +48,7 @@ public async Task ShowAllStatsAsync([Choice("All", "all"), Choice("Dms", "dms"), .Build()); } - var title = Context.Interaction.IsDMInteraction ? $"Stats for {Context.User.Username}'s DMS" : $"Stats for {Context.Guild.Name}"; + string title = Context.Interaction.IsDMInteraction ? $"Stats for {Context.User.Username}'s DMS" : $"Stats for {Context.Guild.Name}"; var templateEmbed = new EmbedBuilder() .WithTitle(title); @@ -60,7 +60,7 @@ public async Task ShowAllStatsAsync([Choice("All", "all"), Choice("Dms", "dms"), [CommandContextType(InteractionContextType.Guild, InteractionContextType.PrivateChannel)] public async Task AddModerationModuleToGuildAsync(string guildId, string modulename) { - var module = _interactions.Modules.First(module => module.Name.ToLower() == modulename.ToLower()); + var module = interactions.Modules.First(module => module.Name.Equals(modulename, System.StringComparison.CurrentCultureIgnoreCase)); if (module == null) { @@ -68,7 +68,7 @@ public async Task AddModerationModuleToGuildAsync(string guildId, string modulen return; } - await _interactions.AddModulesToGuildAsync(ulong.Parse(guildId), false, module); + await interactions.AddModulesToGuildAsync(ulong.Parse(guildId), false, module); var embed = new EmbedBuilder() .WithTitle("Module successfully added") @@ -84,7 +84,7 @@ public async Task AddModerationModuleToGuildAsync(string guildId, string modulen await ModifyOriginalResponseAsync(msg => msg.Embeds = new Embed[] { embed }); } - private static List CalculateCommandStatsOnAccounts(Account[] accounts) + private static List calculateCommandStatsOnAccounts(Account[] accounts) { var allInfos = new List(); diff --git a/src/AdvancedBot.Core/Commands/Modules/GLModule.cs b/src/AdvancedBot.Core/Commands/Modules/GLModule.cs index ee308ef..deff371 100644 --- a/src/AdvancedBot.Core/Commands/Modules/GLModule.cs +++ b/src/AdvancedBot.Core/Commands/Modules/GLModule.cs @@ -1,11 +1,11 @@ -using AdvancedBot.Core.Services; -using Discord; -using Discord.Interactions; -using GL.NET.Entities; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using AdvancedBot.Core.Services; +using Discord; +using Discord.Interactions; +using GL.NET.Entities; namespace AdvancedBot.Core.Commands.Modules { @@ -18,7 +18,7 @@ public async Task DisplayServerStatusAsync() { var status = await GLClient.Api.GetServerStatus(); - var thumbnailUrl = + string thumbnailUrl = Context.Channel is IGuildChannel ? Context.Guild.IconUrl : Context.Client.CurrentUser.GetDisplayAvatarUrl(); @@ -105,9 +105,9 @@ public async Task GetLeaderboardAsync([ ] string type) { List displayTexts = new() { "Failed to get information" }; - var title = "Galaxy Life Leaderboard"; + string title = "Galaxy Life Leaderboard"; - var thumbnailUrl = + string thumbnailUrl = Context.Channel is IGuildChannel ? Context.Guild.IconUrl : Context.Client.CurrentUser.GetDisplayAvatarUrl(); @@ -197,7 +197,7 @@ public async Task CompareUsersAsync(string firstPlayer, string secondPlayer) return; } - var thumbnailUrl = + string thumbnailUrl = Context.Channel is IGuildChannel ? Context.Guild.IconUrl : Context.Client.CurrentUser.GetDisplayAvatarUrl(); @@ -205,18 +205,18 @@ Context.Channel is IGuildChannel var baseUserStats = await GLClient.Api.GetUserStats(baseUser.Id); var secondUserStats = await GLClient.Api.GetUserStats(secondUser.Id); - var expDifference = Math.Round((decimal)baseUser.Experience / secondUser.Experience, 2); + decimal expDifference = Math.Round((decimal)baseUser.Experience / secondUser.Experience, 2); var embed = new EmbedBuilder() .WithTitle($"{baseUser.Name} vs {secondUser.Name}") .WithColor(expDifference > 1 ? Color.DarkGreen : Color.DarkOrange) .WithThumbnailUrl(thumbnailUrl) .WithDescription( - $"{baseUser.Name} has **{FormatNumber(expDifference)}x** the experience of {secondUser.Name}\n" + - $"Difference of **{FormatNumber(Math.Abs((decimal)baseUser.Experience - secondUser.Experience))}** experience.\n\n") - .AddField($"{baseUser.Name}", $"Level **{baseUser.Level}**\nExperience: **{FormatNumber(baseUser.Experience)}**", true) + $"{baseUser.Name} has **{formatNumber(expDifference)}x** the experience of {secondUser.Name}\n" + + $"Difference of **{formatNumber(Math.Abs((decimal)baseUser.Experience - secondUser.Experience))}** experience.\n\n") + .AddField($"{baseUser.Name}", $"Level **{baseUser.Level}**\nExperience: **{formatNumber(baseUser.Experience)}**", true) .AddField(" vs ", $"\u200B", true) - .AddField($"{secondUser.Name}", $"Level **{secondUser.Level}**\nExperience: **{FormatNumber(secondUser.Experience)}**", true) + .AddField($"{secondUser.Name}", $"Level **{secondUser.Level}**\nExperience: **{formatNumber(secondUser.Experience)}**", true) .WithFooter(footer => footer .WithText($"Comparison requested by {Context.User.Username}#{Context.User.Discriminator}") .WithIconUrl(Context.User.GetDisplayAvatarUrl())) @@ -226,7 +226,7 @@ Context.Channel is IGuildChannel await ModifyOriginalResponseAsync(msg => msg.Embeds = new Embed[] { embed }); } - private static string FormatNumber(decimal number) + private static string formatNumber(decimal number) { return number switch { diff --git a/src/AdvancedBot.Core/Commands/Modules/InfoModule.cs b/src/AdvancedBot.Core/Commands/Modules/InfoModule.cs index f1e8e8f..3f8e70b 100644 --- a/src/AdvancedBot.Core/Commands/Modules/InfoModule.cs +++ b/src/AdvancedBot.Core/Commands/Modules/InfoModule.cs @@ -1,30 +1,30 @@ -using Discord; -using Discord.Interactions; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Discord; +using Discord.Interactions; namespace AdvancedBot.Core.Commands.Modules { public class InfoModule : TopModule { - private readonly CustomCommandService _commands; + private readonly CustomCommandService commands; public InfoModule(CustomCommandService commands) { - _commands = commands; + this.commands = commands; } [SlashCommand("help", "View basic help and information about the Galaxy Life bot.")] public async Task DisplayBotInfoAsync() { - await _commands.SendBotInfoAsync(Context); + await commands.SendBotInfoAsync(Context); } [SlashCommand("serverstats", "Shows guild stats related to the bot")] public async Task DisplayGuildOrDmStatsAsync() { - var id = Context.Interaction.IsDMInteraction ? Context.User.Id : Context.Guild.Id; + ulong id = Context.Interaction.IsDMInteraction ? Context.User.Id : Context.Guild.Id; var guild = Accounts.GetOrCreateAccount(id, !Context.Interaction.IsDMInteraction); var fields = new List(); @@ -39,8 +39,8 @@ public async Task DisplayGuildOrDmStatsAsync() .Build()); } - var title = Context.Interaction.IsDMInteraction ? $"Stats for {Context.User.Username}'s DMS" : $"Stats for {Context.Guild.Name}"; - var thumbnailUrl = Context.Interaction.IsDMInteraction ? Context.User.GetDisplayAvatarUrl() : Context.Guild.IconUrl; + string title = Context.Interaction.IsDMInteraction ? $"Stats for {Context.User.Username}'s DMS" : $"Stats for {Context.Guild.Name}"; + string thumbnailUrl = Context.Interaction.IsDMInteraction ? Context.User.GetDisplayAvatarUrl() : Context.Guild.IconUrl; var templateEmbed = new EmbedBuilder() .WithTitle(title) diff --git a/src/AdvancedBot.Core/Commands/Modules/ModerationModule.cs b/src/AdvancedBot.Core/Commands/Modules/ModerationModule.cs index f527e1b..7727984 100644 --- a/src/AdvancedBot.Core/Commands/Modules/ModerationModule.cs +++ b/src/AdvancedBot.Core/Commands/Modules/ModerationModule.cs @@ -1,3 +1,7 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; using AdvancedBot.Core.Commands.Preconditions; using AdvancedBot.Core.Entities.Enums; using AdvancedBot.Core.Services; @@ -5,10 +9,6 @@ using Discord.Interactions; using GL.NET.Entities; using Humanizer; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace AdvancedBot.Core.Commands.Modules { @@ -35,7 +35,7 @@ public async Task GetAllianceWarlogs(string allianceName) var warlogs = await GLClient.Api.GetAllianceWarlogs(alliance.Id); var texts = new List(); - var wins = warlogs.Count(war => war.WinnerId == alliance.Id); + int wins = warlogs.Count(war => war.WinnerId == alliance.Id); for (int i = 0; i < warlogs.Count; i++) { @@ -43,15 +43,15 @@ public async Task GetAllianceWarlogs(string allianceName) var endDate = new DateTime(1970, 1, 1).AddMilliseconds(log.WarEndTime); var duration = TimeSpan.FromMilliseconds(log.WarEndTime - log.WarStartTime); - var statusText = warlogs[i].WinnerId == alliance.Id ? "**Won** against" : "**Lost** against"; - var dateText = $"ended **{endDate:dd/MM/yyyy (HH:mm)}**"; - var durationText = duration.Days == 3 ? $"" : $"(KO after {(TimeSpan.FromDays(3) - duration).Humanize(3)})"; + string statusText = warlogs[i].WinnerId == alliance.Id ? "**Won** against" : "**Lost** against"; + string dateText = $"ended **{endDate:dd/MM/yyyy (HH:mm)}**"; + string durationText = duration.Days == 3 ? $"" : $"(KO after {(TimeSpan.FromDays(3) - duration).Humanize(3)})"; texts.Add($"{statusText} **{log.EnemyAllianceName}** {dateText}\n" + $"**{log.SelfAllianceWarScore}**wp versus **{log.EnemyAllianceWarScore}**wp {durationText}\n"); } - var winLossRatio = wins / (warlogs.Count - wins == 0 ? 1 : warlogs.Count - wins); + int winLossRatio = wins / (warlogs.Count - wins == 0 ? 1 : warlogs.Count - wins); await LogService.LogGameActionAsync(LogAction.GetWarlogs, Context.User.Id, 0, alliance.Id); @@ -198,10 +198,10 @@ public async Task GetFullUserAsync(string input) await LogService.LogGameActionAsync(LogAction.GetFull, Context.User.Id, user.UserId); - var steamId = user.SteamId ?? "No account linked"; - var discordTag = string.IsNullOrEmpty(user.DiscordId) ? "No account linked" : $"<@{user.DiscordId}>"; + string steamId = user.SteamId ?? "No account linked"; + string discordTag = string.IsNullOrEmpty(user.DiscordId) ? "No account linked" : $"<@{user.DiscordId}>"; - var description = + string description = user.Role == PhoenixRole.Banned ? $"**This user has been banned!!**\nBan Reason: **{user.BanReason}**\n\n" : user.Role == PhoenixRole.Donator ? "This user is a Donator\n\n" : user.Role == PhoenixRole.Staff ? "This user is a Staff Member\n\n" @@ -314,7 +314,7 @@ public async Task TryUpdateNameAsync(uint userId, string newName) return; } - var backendSuccess = await GLClient.Api.UpdateNameFromPhoenixAsync(userId.ToString()); + bool backendSuccess = await GLClient.Api.UpdateNameFromPhoenixAsync(userId.ToString()); await LogService.LogGameActionAsync(LogAction.UpdateName, Context.User.Id, userId, $"{user.UserName}:{newName}"); @@ -521,9 +521,9 @@ public async Task GetLeaderboardAsync([ Choice("Chips (advanced)", "advchips")] string type, string sku = "7000") { List displayTexts = new() { "Failed to get information" }; - var title = "Galaxy Life Leaderboard"; + string title = "Galaxy Life Leaderboard"; - var thumbnailUrl = + string thumbnailUrl = Context.Channel is IGuildChannel ? Context.Guild.IconUrl : Context.Client.CurrentUser.GetDisplayAvatarUrl(); diff --git a/src/AdvancedBot.Core/Commands/Modules/StagingComponentsModule.cs b/src/AdvancedBot.Core/Commands/Modules/StagingComponentsModule.cs index 5b1b1c8..33d23c6 100644 --- a/src/AdvancedBot.Core/Commands/Modules/StagingComponentsModule.cs +++ b/src/AdvancedBot.Core/Commands/Modules/StagingComponentsModule.cs @@ -1,6 +1,6 @@ +using System.Threading.Tasks; using AdvancedBot.Core.Services; using Discord.Interactions; -using System.Threading.Tasks; namespace AdvancedBot.Core.Commands.Modules { diff --git a/src/AdvancedBot.Core/Commands/Modules/StagingModule.cs b/src/AdvancedBot.Core/Commands/Modules/StagingModule.cs index da49d84..8589c9f 100644 --- a/src/AdvancedBot.Core/Commands/Modules/StagingModule.cs +++ b/src/AdvancedBot.Core/Commands/Modules/StagingModule.cs @@ -1,10 +1,10 @@ +using System.Threading.Tasks; using AdvancedBot.Core.Commands.Preconditions; using AdvancedBot.Core.Entities; using AdvancedBot.Core.Entities.Enums; using AdvancedBot.Core.Services; using Discord; using Discord.Interactions; -using System.Threading.Tasks; namespace AdvancedBot.Core.Commands.Modules { @@ -127,7 +127,7 @@ public async Task AddXpToUserAsync(uint userId, int amount) [SlashCommand("restart", "Restarts staging server")] public async Task RestartStagingAsync() { - var result = await GLClient.Staging.RestartServer(); + bool result = await GLClient.Staging.RestartServer(); if (!result) { diff --git a/src/AdvancedBot.Core/Commands/Modules/TelemetryModule.cs b/src/AdvancedBot.Core/Commands/Modules/TelemetryModule.cs index 7357088..3bc7484 100644 --- a/src/AdvancedBot.Core/Commands/Modules/TelemetryModule.cs +++ b/src/AdvancedBot.Core/Commands/Modules/TelemetryModule.cs @@ -1,11 +1,11 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; using AdvancedBot.Core.Commands.Preconditions; using AdvancedBot.Core.Entities; using AdvancedBot.Core.Services; using Discord; using Discord.Interactions; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace AdvancedBot.Core.Commands.Modules { @@ -75,7 +75,7 @@ public async Task GetPossibleAltsAsync(uint userId) for (int i = 0; i < result.Output.Count; i++) { - var trackerKey = result.Output.ElementAt(i).Key; + string trackerKey = result.Output.ElementAt(i).Key; var trackerResult = result.Output.ElementAt(i).Value; var a = trackerResult.First().Value; diff --git a/src/AdvancedBot.Core/Commands/Preconditions/RequireCustomPermission.cs b/src/AdvancedBot.Core/Commands/Preconditions/RequireCustomPermission.cs index 03ccb1c..4472e85 100644 --- a/src/AdvancedBot.Core/Commands/Preconditions/RequireCustomPermission.cs +++ b/src/AdvancedBot.Core/Commands/Preconditions/RequireCustomPermission.cs @@ -1,18 +1,18 @@ +using System; +using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; -using System; -using System.Threading.Tasks; namespace AdvancedBot.Core.Commands.Preconditions { public class RequireCustomPermission : PreconditionAttribute { - private readonly GuildPermission _permission; + private readonly GuildPermission permission; public RequireCustomPermission(GuildPermission permission = default) { - _permission = permission; + this.permission = permission; } public override async Task CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) @@ -24,7 +24,7 @@ public override async Task CheckPermissionsAsync(ICommandCon var guildUser = context.User as SocketGuildUser; - if (guildUser.GuildPermissions.Has(_permission) || guildUser.GuildPermissions.Has(GuildPermission.Administrator)) + if (guildUser.GuildPermissions.Has(permission) || guildUser.GuildPermissions.Has(GuildPermission.Administrator)) { return PreconditionResult.FromSuccess(); } diff --git a/src/AdvancedBot.Core/Commands/Preconditions/RequirePrivateList.cs b/src/AdvancedBot.Core/Commands/Preconditions/RequirePrivateList.cs index 0ca8dd2..916afc7 100644 --- a/src/AdvancedBot.Core/Commands/Preconditions/RequirePrivateList.cs +++ b/src/AdvancedBot.Core/Commands/Preconditions/RequirePrivateList.cs @@ -1,14 +1,14 @@ -using Discord; -using Discord.Interactions; using System; using System.Collections.Generic; using System.Threading.Tasks; +using Discord; +using Discord.Interactions; namespace AdvancedBot.Core.Commands.Preconditions { public class RequirePrivateList : PreconditionAttribute { - private readonly List _userIds = new() + private readonly List userIds = new() { 202095042372829184, // svr333 942849642931032164, // lifecoder @@ -20,7 +20,7 @@ public class RequirePrivateList : PreconditionAttribute public override async Task CheckRequirementsAsync(IInteractionContext context, ICommandInfo commandInfo, IServiceProvider services) { - if (!_userIds.Contains(context.User.Id)) + if (!userIds.Contains(context.User.Id)) { if (!context.Interaction.HasResponded) { diff --git a/src/AdvancedBot.Core/Commands/Preconditions/RequireStagingList.cs b/src/AdvancedBot.Core/Commands/Preconditions/RequireStagingList.cs index 21d855f..00c81a7 100644 --- a/src/AdvancedBot.Core/Commands/Preconditions/RequireStagingList.cs +++ b/src/AdvancedBot.Core/Commands/Preconditions/RequireStagingList.cs @@ -1,14 +1,14 @@ -using Discord; -using Discord.Interactions; using System; using System.Collections.Generic; using System.Threading.Tasks; +using Discord; +using Discord.Interactions; namespace AdvancedBot.Core.Commands.Preconditions { public class RequireStagingList : PreconditionAttribute { - private readonly List _userIds = new() + private readonly List userIds = new() { 202095042372829184, // svr333 942849642931032164, // lifecoder @@ -21,7 +21,7 @@ public class RequireStagingList : PreconditionAttribute public override async Task CheckRequirementsAsync(IInteractionContext context, ICommandInfo commandInfo, IServiceProvider services) { - if (!_userIds.Contains(context.User.Id)) + if (!userIds.Contains(context.User.Id)) { if (!context.Interaction.HasResponded) { diff --git a/src/AdvancedBot.Core/Commands/TopModule.cs b/src/AdvancedBot.Core/Commands/TopModule.cs index 187039d..e97300c 100644 --- a/src/AdvancedBot.Core/Commands/TopModule.cs +++ b/src/AdvancedBot.Core/Commands/TopModule.cs @@ -1,14 +1,14 @@ -using AdvancedBot.Core.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using AdvancedBot.Core.Entities; using AdvancedBot.Core.Services; using AdvancedBot.Core.Services.DataStorage; using Discord; using Discord.Interactions; using GL.NET; using GL.NET.Entities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace AdvancedBot.Core.Commands { @@ -44,7 +44,7 @@ public override Task AfterExecuteAsync(ICommandInfo command) protected async Task SendPaginatedMessageAsync(IEnumerable displayFields, IEnumerable displayTexts, EmbedBuilder templateEmbed) { - var displayItems = 0; + int displayItems = 0; if (displayTexts != null) { @@ -177,7 +177,7 @@ protected async Task GetPhoenixUserByInput(string input, bool full if (string.IsNullOrEmpty(input)) input = Context.User.Username; PhoenixUser user = null; - var digitString = new string(input.Where(char.IsDigit).ToArray()); + string digitString = new string(input.Where(char.IsDigit).ToArray()); // extra check to see if all characters were numbers if (digitString.Length == input.Length) diff --git a/src/AdvancedBot.Core/Entities/Log.cs b/src/AdvancedBot.Core/Entities/Log.cs index 5157358..401c86f 100644 --- a/src/AdvancedBot.Core/Entities/Log.cs +++ b/src/AdvancedBot.Core/Entities/Log.cs @@ -1,5 +1,5 @@ -using AdvancedBot.Core.Entities.Enums; using System; +using AdvancedBot.Core.Entities.Enums; namespace AdvancedBot.Core.Entities { diff --git a/src/AdvancedBot.Core/Entities/PaginatedMessage.cs b/src/AdvancedBot.Core/Entities/PaginatedMessage.cs index f767626..2a0c7a5 100644 --- a/src/AdvancedBot.Core/Entities/PaginatedMessage.cs +++ b/src/AdvancedBot.Core/Entities/PaginatedMessage.cs @@ -1,11 +1,11 @@ -using Discord; using System; +using Discord; namespace AdvancedBot.Core.Entities { public class PaginatedMessage { - private int _currentPage = 1; + private int currentPage = 1; public ulong DiscordMessageId { get; set; } public ulong DiscordChannelId { get; set; } @@ -14,21 +14,21 @@ public class PaginatedMessage public EmbedField[] DisplayFields { get; set; } public int CurrentPage { - get => _currentPage; + get => currentPage; set { - if (value > TotalPages) _currentPage = TotalPages; - else if (value < 1) _currentPage = 1; - else _currentPage = value; + if (value > TotalPages) currentPage = TotalPages; + else if (value < 1) currentPage = 1; + else currentPage = value; } } public int TotalPages { get { - var totalPages = DisplayMessages == null ? DisplayFields.Length : DisplayMessages.Length; - var decimalValue = (double)totalPages / 10; - var roundedUpValue = Math.Ceiling(decimalValue); + int totalPages = DisplayMessages == null ? DisplayFields.Length : DisplayMessages.Length; + double decimalValue = (double)totalPages / 10; + double roundedUpValue = Math.Ceiling(decimalValue); return int.Parse(roundedUpValue.ToString()); } } diff --git a/src/AdvancedBot.Core/Extensions/PrefixCheckerExt.cs b/src/AdvancedBot.Core/Extensions/PrefixCheckerExt.cs index dd42693..efc02dd 100644 --- a/src/AdvancedBot.Core/Extensions/PrefixCheckerExt.cs +++ b/src/AdvancedBot.Core/Extensions/PrefixCheckerExt.cs @@ -1,6 +1,6 @@ -using Discord.Commands; +using System.Collections.Generic; +using Discord.Commands; using Discord.WebSocket; -using System.Collections.Generic; namespace AdvancedBot.Core.Extensions { diff --git a/src/AdvancedBot.Core/Services/ChannelCounterService.cs b/src/AdvancedBot.Core/Services/ChannelCounterService.cs index 9f4ae42..20f34b6 100644 --- a/src/AdvancedBot.Core/Services/ChannelCounterService.cs +++ b/src/AdvancedBot.Core/Services/ChannelCounterService.cs @@ -1,53 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Timers; using AdvancedBot.Core.Entities; using AdvancedBot.Core.Entities.Enums; using AdvancedBot.Core.Services.DataStorage; using Discord; using Discord.WebSocket; using GL.NET; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using System.Timers; namespace AdvancedBot.Core.Services { public class ChannelCounterService { - private readonly List _activeCounters = new(); - private readonly DiscordSocketClient _client; - private readonly GLClient _gl; - private readonly AccountService _guild; - private readonly Timer _timer = new(6 * 60 * 1000); - private string _serverStatus = "Offline"; + private readonly List activeCounters = new(); + private readonly DiscordSocketClient client; + private readonly GLClient gl; + private readonly AccountService guild; + private readonly Timer timer = new(6 * 60 * 1000); + private string serverStatus = "Offline"; public ChannelCounterService(DiscordSocketClient client, GLClient gl, AccountService guild) { - _client = client; - _gl = gl; - _guild = guild; + this.client = client; + this.gl = gl; + this.guild = guild; - _timer.Start(); - _timer.Elapsed += OnTimerElapsed; + timer.Start(); + timer.Elapsed += onTimerElapsed; - OnTimerElapsed(null, null); + onTimerElapsed(null, null); InitializeCounters(); } - private async void OnTimerElapsed(object timerObj, ElapsedEventArgs e) + private async void onTimerElapsed(object timerObj, ElapsedEventArgs e) { - _timer.Stop(); + timer.Stop(); try { - await HandleActiveChannelCounters(); + await handleActiveChannelCounters(); } catch (Exception err) { Console.WriteLine(err); } - _timer.Start(); + timer.Start(); } public void InitializeCounters() @@ -56,16 +56,16 @@ public void InitializeCounters() for (int i = 0; i < enumValues.Length; i++) { - _activeCounters.Add(new ChannelCounterInfo(enumValues[i])); + activeCounters.Add(new ChannelCounterInfo(enumValues[i])); } } public ChannelCounterInfo[] GetAllChannelCounters() - => _activeCounters.ToArray(); + => activeCounters.ToArray(); public void AddNewChannelCounter(ulong guildId, ChannelCounter counter) { - var guild = _guild.GetOrCreateAccount(guildId, true); + var guild = this.guild.GetOrCreateAccount(guildId, true); var fCounter = guild.ChannelCounters.Find(x => x.Type == counter.Type); var cCounter = guild.ChannelCounters.Find(x => x.ChannelId == counter.ChannelId); @@ -75,53 +75,43 @@ public void AddNewChannelCounter(ulong guildId, ChannelCounter counter) throw new Exception($"This channel already has the '{cCounter.Type}' active."); guild.ChannelCounters.Add(counter); - _guild.SaveAccount(guild); + this.guild.SaveAccount(guild); } public void RemoveChannelCounterByType(ulong guildId, ChannelCounterType counterType) { - var guild = _guild.GetOrCreateAccount(guildId); - - var counter = guild.ChannelCounters.Find(x => x.Type == counterType); - - if (counter is null) - throw new Exception($"There is no counter active of type '{counterType}'."); + var guild = this.guild.GetOrCreateAccount(guildId); + var counter = guild.ChannelCounters.Find(x => x.Type == counterType) ?? throw new Exception($"There is no counter active of type '{counterType}'."); guild.ChannelCounters.Remove(counter); - _guild.SaveAccount(guild); + this.guild.SaveAccount(guild); } public void RemoveChannelCounterByChannel(ulong guildId, ulong channelId) { - var guild = _guild.GetOrCreateAccount(guildId); - - var counter = guild.ChannelCounters.Find(x => x.ChannelId == channelId); - - if (counter is null) - throw new Exception($"This channel has no active counter."); + var guild = this.guild.GetOrCreateAccount(guildId); + var counter = guild.ChannelCounters.Find(x => x.ChannelId == channelId) ?? throw new Exception($"This channel has no active counter."); guild.ChannelCounters.Remove(counter); - _guild.SaveAccount(guild); + this.guild.SaveAccount(guild); } public async Task UpdateChannelAsync(Account account, ChannelCounter counter) { - var channel = await _client.GetChannelAsync(counter.ChannelId) as IVoiceChannel; - /* Channel got removed */ - if (channel == null) + if (await client.GetChannelAsync(counter.ChannelId) is not IVoiceChannel channel) { account.ChannelCounters.Remove(counter); - _guild.SaveAccount(account); + guild.SaveAccount(account); return; } switch (counter.Type) { case ChannelCounterType.FlashStatus: - string newName = $"Server Status: {_serverStatus}"; + string newName = $"Server Status: {serverStatus}"; if (channel.Name != newName) await channel.ModifyAsync(x => x.Name = newName); break; @@ -130,17 +120,17 @@ public async Task UpdateChannelAsync(Account account, ChannelCounter counter) } } - private async Task HandleActiveChannelCounters() + private async Task handleActiveChannelCounters() { Console.WriteLine($"Started handling all counters"); var start = DateTime.UtcNow; - var guilds = _guild.GetManyAccounts(x => x.IsGuild); - await UpdateServerInfo(); + var guilds = guild.GetManyAccounts(x => x.IsGuild); + await updateServerInfo(); for (int i = 0; i < guilds.Length; i++) { - if (!guilds[i].ChannelCounters.Any()) + if (guilds[i].ChannelCounters.Count == 0) continue; for (int j = 0; j < guilds[i].ChannelCounters.Count; j++) @@ -152,32 +142,32 @@ private async Task HandleActiveChannelCounters() Console.WriteLine($"Finished updating all counters ({(DateTime.UtcNow - start).TotalSeconds}s)"); } - private async Task UpdateServerInfo() + private async Task updateServerInfo() { try { - var status = await _gl.Api.GetServerStatus(); + var status = await gl.Api.GetServerStatus(); var authStatus = status.Find(x => x.Name == "Auth Server"); if (authStatus == null || !authStatus.IsOnline) { - _serverStatus = "Auth server down"; + serverStatus = "Auth server down"; return; } - var onlineBackends = status.Count(x => x.Name.Contains("Backend") && x.IsOnline); + int onlineBackends = status.Count(x => x.Name.Contains("Backend") && x.IsOnline); if (onlineBackends >= 3) { - _serverStatus = "Online"; + serverStatus = "Online"; return; } - _serverStatus = "Offline"; + serverStatus = "Offline"; } catch (Exception) { - _serverStatus = "Offline"; + serverStatus = "Offline"; } } } diff --git a/src/AdvancedBot.Core/Services/DataStorage/AccountService.cs b/src/AdvancedBot.Core/Services/DataStorage/AccountService.cs index 3263e42..06d3325 100644 --- a/src/AdvancedBot.Core/Services/DataStorage/AccountService.cs +++ b/src/AdvancedBot.Core/Services/DataStorage/AccountService.cs @@ -1,22 +1,22 @@ -using AdvancedBot.Core.Entities; using System; using System.Linq; using System.Linq.Expressions; +using AdvancedBot.Core.Entities; namespace AdvancedBot.Core.Services.DataStorage { public class AccountService { - private readonly LiteDBHandler _storage; + private readonly LiteDBHandler storage; public AccountService(LiteDBHandler storage) { - _storage = storage; + this.storage = storage; } public Account GetOrCreateAccount(ulong id, bool isGuild = false) { - if (!_storage.Exists(x => x.Id == id)) + if (!storage.Exists(x => x.Id == id)) { var account = new Account(id, isGuild); @@ -24,28 +24,28 @@ public Account GetOrCreateAccount(ulong id, bool isGuild = false) return account; } - return _storage.RestoreSingle(x => x.Id == id); + return storage.RestoreSingle(x => x.Id == id); } public Account[] GetAllAccounts() { - return _storage.RestoreAll().ToArray(); + return storage.RestoreAll().ToArray(); } public Account[] GetManyAccounts(Expression> predicate) { - return _storage.RestoreMany(predicate).ToArray(); + return storage.RestoreMany(predicate).ToArray(); } public void SaveAccount(Account account) { - if (!_storage.Exists(x => x.Id == account.Id)) + if (!storage.Exists(x => x.Id == account.Id)) { - _storage.Store(account); + storage.Store(account); } else { - _storage.Update(account); + storage.Update(account); } } } diff --git a/src/AdvancedBot.Core/Services/DataStorage/BotStorage.cs b/src/AdvancedBot.Core/Services/DataStorage/BotStorage.cs index 314ae86..9cdbeae 100644 --- a/src/AdvancedBot.Core/Services/DataStorage/BotStorage.cs +++ b/src/AdvancedBot.Core/Services/DataStorage/BotStorage.cs @@ -1,31 +1,31 @@ -using AdvancedBot.Core.Entities; using System.Collections.Generic; using System.Linq; +using AdvancedBot.Core.Entities; namespace AdvancedBot.Core.Services.DataStorage { public class BotStorage { - private readonly LiteDBHandler _storage; + private readonly LiteDBHandler storage; public BotStorage(LiteDBHandler storage) { - _storage = storage; + this.storage = storage; } public void AddTempBan(Tempban ban) { - _storage.Store(ban); + storage.Store(ban); } public List GetTempbans() { - return _storage.RestoreAll().ToList(); + return storage.RestoreAll().ToList(); } public void RemoveTempban(Tempban tempban) { - _storage.Remove(ban => ban.ModeratorId == tempban.ModeratorId && ban.UserId == tempban.UserId); + storage.Remove(ban => ban.ModeratorId == tempban.ModeratorId && ban.UserId == tempban.UserId); } } } diff --git a/src/AdvancedBot.Core/Services/DataStorage/LiteDBHandler.cs b/src/AdvancedBot.Core/Services/DataStorage/LiteDBHandler.cs index c0a5d3b..12f4397 100644 --- a/src/AdvancedBot.Core/Services/DataStorage/LiteDBHandler.cs +++ b/src/AdvancedBot.Core/Services/DataStorage/LiteDBHandler.cs @@ -1,61 +1,61 @@ -using LiteDB; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; +using LiteDB; namespace AdvancedBot.Core.Services.DataStorage { public class LiteDBHandler { - private const string _dbFileName = "Data.db"; - private readonly LiteDatabase _db = new(_dbFileName); + private const string db_file_name = "Data.db"; + private readonly LiteDatabase db = new(db_file_name); public void Store(T item) { - var collection = _db.GetCollection(); + var collection = db.GetCollection(); collection.Insert(item); } public void Update(T item) { - var collection = _db.GetCollection(); + var collection = db.GetCollection(); collection.Update(item); } public IEnumerable RestoreMany(Expression> predicate) { - var collection = _db.GetCollection(); + var collection = db.GetCollection(); return collection.Find(predicate); } public IEnumerable RestoreAll() { - var collection = _db.GetCollection(); + var collection = db.GetCollection(); return collection.FindAll(); } public int RestoreCount() { - var collection = _db.GetCollection(); + var collection = db.GetCollection(); return collection.Count(); } public T RestoreSingle(Expression> predicate) { - var collection = _db.GetCollection(); + var collection = db.GetCollection(); return collection.Find(predicate).FirstOrDefault(); } public bool Exists(Expression> predicate) { - var collection = _db.GetCollection(); + var collection = db.GetCollection(); return collection.Exists(predicate); } public void Remove(Expression> predicate) { - var collection = _db.GetCollection(); + var collection = db.GetCollection(); collection.DeleteMany(predicate); } } diff --git a/src/AdvancedBot.Core/Services/GLService.cs b/src/AdvancedBot.Core/Services/GLService.cs index f437820..2211ba6 100644 --- a/src/AdvancedBot.Core/Services/GLService.cs +++ b/src/AdvancedBot.Core/Services/GLService.cs @@ -1,3 +1,6 @@ +using System; +using System.Linq; +using System.Threading.Tasks; using AdvancedBot.Core.Entities; using AdvancedBot.Core.Entities.Enums; using Discord; @@ -5,31 +8,28 @@ using GL.NET.Entities; using Humanizer; using Humanizer.Localisation; -using System; -using System.Linq; -using System.Threading.Tasks; namespace AdvancedBot.Core.Services { public class GLService { - private readonly GLClient _client; + private readonly GLClient client; public GLService(GLClient client) { - _client = client; + this.client = client; } public async Task GetUserProfileAsync(string input) { - var phoenixUser = await GetPhoenixUserByInput(input); + var phoenixUser = await getPhoenixUserByInput(input); if (phoenixUser == null) { return new ModResult(ModResultType.NotFound, message: new ResponseMessage($"<:shrugR:945740284308893696> Could not find any user for **{input}**.")); } - var user = await GetUserByInput(input); + var user = await getUserByInput(input); if (user == null) { @@ -43,10 +43,10 @@ public async Task GetUserProfileAsync(string input) } } - var stats = await _client.Api.GetUserStats(user.Id); + var stats = await client.Api.GetUserStats(user.Id); - var steamId = phoenixUser.SteamId ?? "No steam linked"; - var roleText = phoenixUser.Role == PhoenixRole.Banned ? "[BANNED]" + string steamId = phoenixUser.SteamId ?? "No steam linked"; + string roleText = phoenixUser.Role == PhoenixRole.Banned ? "[BANNED]" : phoenixUser.Role == PhoenixRole.Donator ? "[Donator]" : phoenixUser.Role == PhoenixRole.Staff ? "[Staff]" : phoenixUser.Role == PhoenixRole.Administrator ? "[Admin]" @@ -58,11 +58,11 @@ public async Task GetUserProfileAsync(string input) : phoenixUser.Role == PhoenixRole.Administrator ? Color.DarkRed : Color.LightGrey; - var displayAlliance = "This user is not a member of any alliance."; + string displayAlliance = "This user is not a member of any alliance."; if (!string.IsNullOrEmpty(user.AllianceId)) { - var alliance = await _client.Api.GetAlliance(user.AllianceId); + var alliance = await client.Api.GetAlliance(user.AllianceId); // can happen due to 24hour player delay if (alliance == null) @@ -79,7 +79,7 @@ public async Task GetUserProfileAsync(string input) .WithTitle($"Profile | {roleText} {phoenixUser.UserName}") .WithThumbnailUrl(user.Avatar) .WithDescription($"{displayAlliance}\n\u200b") - .AddField("Level", FormatNumber(user.Level), true) + .AddField("Level", formatNumber(user.Level), true) .AddField("Starbase", user.Planets[0].HQLevel, true) .AddField("Colonies", user.Planets.Count(x => x != null) - 1, true) .WithColor(color) @@ -98,15 +98,15 @@ public async Task GetUserProfileAsync(string input) public async Task GetUserStatsAsync(string input) { - var user = await GetUserByInput(input); + var user = await getUserByInput(input); if (user == null) { return new ModResult(ModResultType.NotFound, message: new ResponseMessage($"<:shrugR:945740284308893696> Could not find any user for **{input}**.")); } - var stats = await _client.Api.GetUserStats(user.Id); - var displayAlliance = string.IsNullOrEmpty(user.AllianceId) ? "This user is not a member of any alliance." : $"This user is a member of **{user.AllianceId}**."; + var stats = await client.Api.GetUserStats(user.Id); + string displayAlliance = string.IsNullOrEmpty(user.AllianceId) ? "This user is not a member of any alliance." : $"This user is a member of **{user.AllianceId}**."; var embed = new EmbedBuilder() .WithTitle($"Statistics | {user.Name}") @@ -116,11 +116,11 @@ public async Task GetUserStatsAsync(string input) .AddField("Level", user.Level, true) .AddField("Players attacked", stats.PlayersAttacked, true) .AddField("NPCs attacked", stats.NpcsAttacked, true) - .AddField("Coins spent", FormatNumber(stats.CoinsSpent), true) - .AddField("Minerals spent", FormatNumber(stats.MineralsSpent), true) - .AddField("Friends helped", FormatNumber(stats.FriendsHelped), true) - .AddField("Gifts received", FormatNumber(stats.GiftsReceived), true) - .AddField("Gifts sent", FormatNumber(stats.GiftsSent), true) + .AddField("Coins spent", formatNumber(stats.CoinsSpent), true) + .AddField("Minerals spent", formatNumber(stats.MineralsSpent), true) + .AddField("Friends helped", formatNumber(stats.FriendsHelped), true) + .AddField("Gifts received", formatNumber(stats.GiftsReceived), true) + .AddField("Gifts sent", formatNumber(stats.GiftsSent), true) .AddField("Obstacles recycled", stats.ObstaclesRecycled, true) .AddField("Troops trained", stats.TroopsTrained, true) .AddField("Troopsize donated", stats.TroopSizesDonated, true) @@ -137,19 +137,19 @@ public async Task GetUserStatsAsync(string input) public async Task GetAllianceAsync(string input) { - var alliance = await _client.Api.GetAlliance(input); + var alliance = await client.Api.GetAlliance(input); if (alliance == null) { return new ModResult(ModResultType.NotFound, message: new ResponseMessage($"<:shrugR:945740284308893696> Could not find any alliance for **{input}**.")); } - var emblemUrl = $"https://cdn.galaxylifegame.net/content/img/alliance_flag/AllianceLogos/flag_{(int)alliance.Emblem.Shape}_{(int)alliance.Emblem.Pattern}_{(int)alliance.Emblem.Icon}.png"; + string emblemUrl = $"https://cdn.galaxylifegame.net/content/img/alliance_flag/AllianceLogos/flag_{(int)alliance.Emblem.Shape}_{(int)alliance.Emblem.Pattern}_{(int)alliance.Emblem.Icon}.png"; var owner = alliance.Members.FirstOrDefault(x => x.AllianceRole == AllianceRole.LEADER); - var warsWon = alliance.WarsWon; - var warsLost = alliance.WarsLost; + int warsWon = alliance.WarsWon; + int warsLost = alliance.WarsLost; int warsTotal = warsWon + warsLost; double winRatio = (warsTotal > 0) ? (double)warsWon / warsTotal * 100 : 0; @@ -178,7 +178,7 @@ public async Task GetAllianceAsync(string input) public async Task GetAllianceMembersAsync(string input) { - var alliance = await _client.Api.GetAlliance(input); + var alliance = await client.Api.GetAlliance(input); if (alliance == null) { @@ -189,10 +189,10 @@ public async Task GetAllianceMembersAsync(string input) var captains = alliance.Members.Where(x => x.AllianceRole == AllianceRole.ADMIN); var regulars = alliance.Members.Where(x => x.AllianceRole == AllianceRole.REGULAR); - var formattedCaptains = $"{string.Join(" | ", captains.Select(x => $"**{x.Name}** ({x.Id})"))}\n\u200b"; - var formattedMembers = $"{string.Join(", ", regulars.Select(x => x.Name))}"; + string formattedCaptains = $"{string.Join(" | ", captains.Select(x => $"**{x.Name}** ({x.Id})"))}\n\u200b"; + string formattedMembers = $"{string.Join(", ", regulars.Select(x => x.Name))}"; - var emblemUrl = $"https://cdn.galaxylifegame.net/content/img/alliance_flag/AllianceLogos/flag_{(int)alliance.Emblem.Shape}_{(int)alliance.Emblem.Pattern}_{(int)alliance.Emblem.Icon}.png"; + string emblemUrl = $"https://cdn.galaxylifegame.net/content/img/alliance_flag/AllianceLogos/flag_{(int)alliance.Emblem.Shape}_{(int)alliance.Emblem.Pattern}_{(int)alliance.Emblem.Icon}.png"; var embed = new EmbedBuilder() .WithTitle($"{alliance.Name} | Members") @@ -211,53 +211,53 @@ public async Task GetAllianceMembersAsync(string input) return new ModResult(ModResultType.Success, message, null, null) { Alliance = alliance }; } - private async Task GetUserByInput(string input) + private async Task getUserByInput(string input) { User profile = null; - var digitString = new string(input.Where(char.IsDigit).ToArray()); + string digitString = new string(input.Where(char.IsDigit).ToArray()); if (digitString.Length == input.Length) { - profile = await _client.Api.GetUserById(input); + profile = await client.Api.GetUserById(input); } - profile ??= await _client.Api.GetUserByName(input); + profile ??= await client.Api.GetUserByName(input); return profile; } - private async Task GetPhoenixUserByInput(string input, bool full = false) + private async Task getPhoenixUserByInput(string input, bool full = false) { PhoenixUser user = null; - var digitString = new string(input.Where(char.IsDigit).ToArray()); + string digitString = new string(input.Where(char.IsDigit).ToArray()); // extra check to see if all characters were numbers if (digitString.Length == input.Length) { if (full) { - user = await _client.Phoenix.GetFullPhoenixUserAsync(input); + user = await client.Phoenix.GetFullPhoenixUserAsync(input); } else { - user = await _client.Phoenix.GetPhoenixUserAsync(input); + user = await client.Phoenix.GetPhoenixUserAsync(input); } } // try to get user by name - user ??= await _client.Phoenix.GetPhoenixUserByNameAsync(input); + user ??= await client.Phoenix.GetPhoenixUserByNameAsync(input); // get user by id after getting it by name if (user != null && full) { - user = await _client.Phoenix.GetFullPhoenixUserAsync(user.UserId); + user = await client.Phoenix.GetFullPhoenixUserAsync(user.UserId); } return user; } - private static string FormatNumber(decimal number) + private static string formatNumber(decimal number) { return number switch { diff --git a/src/AdvancedBot.Core/Services/LogService.cs b/src/AdvancedBot.Core/Services/LogService.cs index fe7a91c..8dccf21 100644 --- a/src/AdvancedBot.Core/Services/LogService.cs +++ b/src/AdvancedBot.Core/Services/LogService.cs @@ -1,3 +1,5 @@ +using System; +using System.Threading.Tasks; using AdvancedBot.Core.Commands; using AdvancedBot.Core.Entities; using AdvancedBot.Core.Entities.Enums; @@ -7,38 +9,36 @@ using GL.NET; using GL.NET.Entities; using Humanizer; -using System; -using System.Threading.Tasks; namespace AdvancedBot.Core.Services { public class LogService { - private int _id = 0; - private readonly LiteDBHandler _storage; - private readonly CustomCommandService _commands; - private readonly DiscordSocketClient _client; - private readonly GLClient _gl; + private int id = 0; + private readonly LiteDBHandler storage; + private readonly CustomCommandService commands; + private readonly DiscordSocketClient client; + private readonly GLClient gl; public LogService(LiteDBHandler storage, CustomCommandService commands, DiscordSocketClient client, GLClient gl) { - _storage = storage; - _commands = commands; - _client = client; - _gl = gl; + this.storage = storage; + this.commands = commands; + this.client = client; + this.gl = gl; - _id = _storage.RestoreCount(); + id = this.storage.RestoreCount(); } public async Task LogGameActionAsync(LogAction action, ulong discordModId, uint victimGameId, string reason = "", DateTime? until = null) { - _id++; - var log = new Log(_id, action, discordModId, victimGameId, reason, until); + id++; + var log = new Log(id, action, discordModId, victimGameId, reason, until); - _storage.Store(log); + storage.Store(log); - var channel = await _client.GetChannelAsync(_commands.LogChannelId) as ISocketMessageChannel; - var user = await _gl.Api.GetUserById(victimGameId.ToString()); + var channel = await client.GetChannelAsync(commands.LogChannelId) as ISocketMessageChannel; + var user = await gl.Api.GetUserById(victimGameId.ToString()); await channel.SendMessageAsync(embed: GetEmbedForLog(log, user)); } @@ -47,7 +47,7 @@ public static Embed GetEmbedForLog(Log log, User target) { var embed = new EmbedBuilder() .WithTitle($"Overview | {log.Type.Humanize()}") - .WithColor(GetColorBasedOnAction(log.Type)) + .WithColor(getColorBasedOnAction(log.Type)) .AddField("Moderator", $"<@{log.DiscordModId}>", true) .WithFooter(footer => footer .WithText($"Case #{log.Id} • Requested by moderator with id {log.DiscordModId}")) @@ -79,7 +79,7 @@ public static Embed GetEmbedForLog(Log log, User target) case LogAction.UpdateEmail: case LogAction.UpdateName: case LogAction.RenameAlliance: - var splits = log.Reason.Split(':'); + string[] splits = log.Reason.Split(':'); embed.AddField("Previous", splits[0]); embed.AddField("Updated", splits[1], true); break; @@ -89,7 +89,7 @@ public static Embed GetEmbedForLog(Log log, User target) break; case LogAction.AddItem: - var itemSplit = log.Reason.Split(':'); + string[] itemSplit = log.Reason.Split(':'); embed.AddField("Item SKU", itemSplit[0]); embed.AddField("Quantity", itemSplit[1]); break; @@ -117,14 +117,14 @@ public static Embed GetEmbedForLog(Log log, User target) case LogAction.ForceWar: case LogAction.ForceStopWar: - var warSplit = log.Reason.Split(':'); + string[] warSplit = log.Reason.Split(':'); embed.AddField("Server", warSplit[0], true); embed.AddField("Alliance A", warSplit[1]); embed.AddField("Alliance B", warSplit[2]); break; case LogAction.Compensate: - var compensateSplit = log.Reason.Split(':'); + string[] compensateSplit = log.Reason.Split(':'); embed.AddField("Type", compensateSplit[0]); if (compensateSplit.Length > 2) @@ -155,7 +155,7 @@ public static Embed GetEmbedForLog(Log log, User target) return embed.Build(); } - private static Color GetColorBasedOnAction(LogAction action) + private static Color getColorBasedOnAction(LogAction action) { return action switch { diff --git a/src/AdvancedBot.Core/Services/ModerationService.cs b/src/AdvancedBot.Core/Services/ModerationService.cs index 9cddf68..2cd87ba 100644 --- a/src/AdvancedBot.Core/Services/ModerationService.cs +++ b/src/AdvancedBot.Core/Services/ModerationService.cs @@ -1,38 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Timers; using AdvancedBot.Core.Entities; using AdvancedBot.Core.Entities.Enums; using AdvancedBot.Core.Services.DataStorage; using Discord; using GL.NET; using GL.NET.Entities; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Timers; namespace AdvancedBot.Core.Services { public class ModerationService { - private readonly GLClient _gl; - private readonly LogService _logs; - private readonly BotStorage _storage; + private readonly GLClient gl; + private readonly LogService logs; + private readonly BotStorage storage; - private readonly Timer _banTimer = new(1000 * 60 * 30); + private readonly Timer banTimer = new(1000 * 60 * 30); public ModerationService(GLClient gl, LogService logs, BotStorage storage) { - _gl = gl; - _logs = logs; - _storage = storage; + this.gl = gl; + this.logs = logs; + this.storage = storage; - _banTimer.Elapsed += OnBanTimer; - _banTimer.Start(); - OnBanTimer(null, null); + banTimer.Elapsed += onBanTimer; + banTimer.Start(); + onBanTimer(null, null); } public async Task BanUserAsync(ulong discordId, uint userId, string reason, uint days = 0) { - var user = await _gl.Phoenix.GetPhoenixUserAsync(userId); + var user = await gl.Phoenix.GetPhoenixUserAsync(userId); if (user == null) { @@ -44,7 +44,7 @@ public async Task BanUserAsync(ulong discordId, uint userId, string r return new ModResult(ModResultType.AlreadyDone, new ResponseMessage($"{user.UserName} ({user.UserId}) is already banned."), user); } - if (!await _gl.Phoenix.TryBanUser(userId, reason)) + if (!await gl.Phoenix.TryBanUser(userId, reason)) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to ban {user.UserName} ({user.UserId})"), user); } @@ -65,11 +65,11 @@ public async Task BanUserAsync(ulong discordId, uint userId, string r if (days > 0) { banDuration = DateTime.UtcNow.AddDays(days); - _storage.AddTempBan(new Tempban(discordId, userId, banDuration.Value)); + storage.AddTempBan(new Tempban(discordId, userId, banDuration.Value)); } - await _gl.Production.TryKickUserOfflineAsync(userId.ToString()); - await _logs.LogGameActionAsync(LogAction.Ban, discordId, userId, reason, banDuration); + await gl.Production.TryKickUserOfflineAsync(userId.ToString()); + await logs.LogGameActionAsync(LogAction.Ban, discordId, userId, reason, banDuration); var message = new ResponseMessage(embeds: new Embed[] { embed }); return new ModResult(ModResultType.Success, message, user); @@ -77,7 +77,7 @@ public async Task BanUserAsync(ulong discordId, uint userId, string r public async Task UnbanUserAsync(ulong discordId, uint userId, bool auto = false) { - var user = await _gl.Phoenix.GetPhoenixUserAsync(userId); + var user = await gl.Phoenix.GetPhoenixUserAsync(userId); if (user == null) { @@ -89,13 +89,13 @@ public async Task UnbanUserAsync(ulong discordId, uint userId, bool a return new ModResult(ModResultType.AlreadyDone, new ResponseMessage($"{user.UserName} ({user.UserId}) is not banned."), user); } - if (!await _gl.Phoenix.TryUnbanUser(userId)) + if (!await gl.Phoenix.TryUnbanUser(userId)) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to unban {user.UserName} ({user.UserId})"), user); } - var extra = auto ? "Auto Unban" : ""; - await _logs.LogGameActionAsync(LogAction.Unban, discordId, userId, extra); + string extra = auto ? "Auto Unban" : ""; + await logs.LogGameActionAsync(LogAction.Unban, discordId, userId, extra); var embed = new EmbedBuilder() .WithTitle($"{user.UserName} ({user.UserId}) is no longer banned in-game!") @@ -111,19 +111,19 @@ public async Task UnbanUserAsync(ulong discordId, uint userId, bool a public async Task AddBetaToUserAsync(ulong discordId, uint userId) { - var user = await _gl.Phoenix.GetPhoenixUserAsync(userId); + var user = await gl.Phoenix.GetPhoenixUserAsync(userId); if (user == null) { return new ModResult(ModResultType.NotFound, new ResponseMessage($"Could not find any user with id **{userId}**.")); } - if (!await _gl.Phoenix.AddGlBeta(userId)) + if (!await gl.Phoenix.AddGlBeta(userId)) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to add beta access to {user.UserName} ({user.UserId})")); } - await _logs.LogGameActionAsync(LogAction.AddBeta, discordId, userId); + await logs.LogGameActionAsync(LogAction.AddBeta, discordId, userId); var embed = new EmbedBuilder() .WithTitle($"Entitlement successfully added") @@ -140,19 +140,19 @@ public async Task AddBetaToUserAsync(ulong discordId, uint userId) public async Task RemoveBetaFromUserAsync(ulong discordId, uint userId) { - var user = await _gl.Phoenix.GetPhoenixUserAsync(userId); + var user = await gl.Phoenix.GetPhoenixUserAsync(userId); if (user == null) { return new ModResult(ModResultType.NotFound, new ResponseMessage($"Could not find any user with id **{userId}**.")); } - if (!await _gl.Phoenix.RemoveGlBeta(userId)) + if (!await gl.Phoenix.RemoveGlBeta(userId)) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to remove beta access from {user.UserName} ({user.UserId})")); } - await _logs.LogGameActionAsync(LogAction.RemoveBeta, discordId, userId); + await logs.LogGameActionAsync(LogAction.RemoveBeta, discordId, userId); var embed = new EmbedBuilder() .WithTitle($"Entitlement successfully removed") @@ -169,19 +169,19 @@ public async Task RemoveBetaFromUserAsync(ulong discordId, uint userI public async Task AddEmulateToUserAsync(ulong discordId, uint userId) { - var user = await _gl.Phoenix.GetPhoenixUserAsync(userId); + var user = await gl.Phoenix.GetPhoenixUserAsync(userId); if (user == null) { return new ModResult(ModResultType.NotFound, new ResponseMessage($"Could not find any user with id **{userId}**.")); } - if (!await _gl.Phoenix.AddEmulate(userId)) + if (!await gl.Phoenix.AddEmulate(userId)) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to add emulate access to {user.UserName} ({user.UserId})")); } - await _logs.LogGameActionAsync(LogAction.AddEmulate, discordId, userId); + await logs.LogGameActionAsync(LogAction.AddEmulate, discordId, userId); var embed = new EmbedBuilder() .WithTitle($"Entitlement successfully added") @@ -198,19 +198,19 @@ public async Task AddEmulateToUserAsync(ulong discordId, uint userId) public async Task RemoveEmulateFromUserAsync(ulong discordId, uint userId) { - var user = await _gl.Phoenix.GetPhoenixUserAsync(userId); + var user = await gl.Phoenix.GetPhoenixUserAsync(userId); if (user == null) { return new ModResult(ModResultType.NotFound, new ResponseMessage($"Could not find any user with id **{userId}**.")); } - if (!await _gl.Phoenix.RemoveGlBeta(userId)) + if (!await gl.Phoenix.RemoveGlBeta(userId)) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to remove emulate access from {user.UserName} ({user.UserId})")); } - await _logs.LogGameActionAsync(LogAction.RemoveEmulate, discordId, userId); + await logs.LogGameActionAsync(LogAction.RemoveEmulate, discordId, userId); var embed = new EmbedBuilder() .WithTitle($"Entitlement successfully removed") @@ -227,14 +227,14 @@ public async Task RemoveEmulateFromUserAsync(ulong discordId, uint us public async Task GiveRoleAsync(ulong discordId, uint userId, PhoenixRole newRole) { - var user = await _gl.Phoenix.GetPhoenixUserAsync(userId); + var user = await gl.Phoenix.GetPhoenixUserAsync(userId); if (user == null) { return new ModResult(ModResultType.NotFound, new ResponseMessage($"Could not find any user with id **{userId}**.")); } - var roleText = newRole == PhoenixRole.Donator ? "a Donator" + string roleText = newRole == PhoenixRole.Donator ? "a Donator" : newRole == PhoenixRole.Staff ? "a Staff Member" : newRole == PhoenixRole.Administrator ? "an Admin" : newRole.ToString(); @@ -244,12 +244,12 @@ public async Task GiveRoleAsync(ulong discordId, uint userId, Phoenix return new ModResult(ModResultType.AlreadyDone, new ResponseMessage($"User is already {roleText}!")); } - if (!await _gl.Phoenix.GiveRoleAsync(userId, newRole)) + if (!await gl.Phoenix.GiveRoleAsync(userId, newRole)) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to give {newRole} to {user.UserName} ({user.UserId})"), user); } - await _logs.LogGameActionAsync(LogAction.GiveRole, discordId, userId, newRole.ToString()); + await logs.LogGameActionAsync(LogAction.GiveRole, discordId, userId, newRole.ToString()); var embed = new EmbedBuilder() .WithTitle($"User role successfully updated") @@ -268,17 +268,17 @@ public async Task GiveRoleAsync(ulong discordId, uint userId, Phoenix public async Task GetChipsBoughtAsync(ulong discordId, uint userId) { - var user = await _gl.Api.GetUserById(userId.ToString()); + var user = await gl.Api.GetUserById(userId.ToString()); if (user == null) { return new ModResult(ModResultType.NotFound, new ResponseMessage($"Could not find any user with id **{userId}**.")); } - var chipsBought = await _gl.Api.GetChipsBoughtAsync(userId.ToString()); - await _logs.LogGameActionAsync(LogAction.GetChipsBought, discordId, userId); + int chipsBought = await gl.Api.GetChipsBoughtAsync(userId.ToString()); + await logs.LogGameActionAsync(LogAction.GetChipsBought, discordId, userId); - var description = chipsBought == 0 ? + string description = chipsBought == 0 ? $"This player hasn't bought any chips." : $"This player has bought **{chipsBought}** chips."; @@ -297,17 +297,17 @@ public async Task GetChipsBoughtAsync(ulong discordId, uint userId) public async Task GetChipsSpentAsync(ulong discordId, uint userId) { - var user = await _gl.Api.GetUserById(userId.ToString()); + var user = await gl.Api.GetUserById(userId.ToString()); if (user == null) { return new ModResult(ModResultType.NotFound, new ResponseMessage($"Could not find any user with id **{userId}**.")); } - var chipsSpent = await _gl.Api.GetChipsSpentAsync(userId.ToString()); - await _logs.LogGameActionAsync(LogAction.GetChipsSpent, discordId, userId); + int chipsSpent = await gl.Api.GetChipsSpentAsync(userId.ToString()); + await logs.LogGameActionAsync(LogAction.GetChipsSpent, discordId, userId); - var description = chipsSpent == 0 ? + string description = chipsSpent == 0 ? $"This player hasn't spent any chips." : $"This player has spent **{chipsSpent}** chips."; @@ -326,23 +326,23 @@ public async Task GetChipsSpentAsync(ulong discordId, uint userId) public async Task AddChipsAsync(ulong discordId, uint userId, int amount, bool staging = false) { - var user = await _gl.Api.GetUserById(userId.ToString()); + var user = await gl.Api.GetUserById(userId.ToString()); if (user == null) { return new ModResult(ModResultType.NotFound, new ResponseMessage($"Could not find any user with id **{userId}**.")); } - var success = staging ? await _gl.Staging.TryAddChipsToUserAsync(userId.ToString(), amount) : await _gl.Production.TryAddChipsToUserAsync(userId.ToString(), amount); + bool success = staging ? await gl.Staging.TryAddChipsToUserAsync(userId.ToString(), amount) : await gl.Production.TryAddChipsToUserAsync(userId.ToString(), amount); if (!success) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to add chips to {user.Name} ({user.Id})"), null, user); } - await _logs.LogGameActionAsync(LogAction.AddChips, discordId, userId, amount.ToString()); + await logs.LogGameActionAsync(LogAction.AddChips, discordId, userId, amount.ToString()); - var action = Math.Sign(amount) < 0 ? "removed" : "added"; + string action = Math.Sign(amount) < 0 ? "removed" : "added"; var embed = new EmbedBuilder() .WithTitle($"Chips {action} successfully") @@ -361,23 +361,23 @@ public async Task AddChipsAsync(ulong discordId, uint userId, int amo public async Task AddItemsAsync(ulong discordId, uint userId, string sku, int amount, bool staging = false) { - var user = await _gl.Api.GetUserById(userId.ToString()); + var user = await gl.Api.GetUserById(userId.ToString()); if (user == null) { return new ModResult(ModResultType.NotFound, new ResponseMessage($"Could not find any user with id **{userId}**.")); } - var success = staging ? await _gl.Staging.TryAddItemToUserAsync(userId.ToString(), sku, amount) : await _gl.Production.TryAddItemToUserAsync(userId.ToString(), sku, amount); + bool success = staging ? await gl.Staging.TryAddItemToUserAsync(userId.ToString(), sku, amount) : await gl.Production.TryAddItemToUserAsync(userId.ToString(), sku, amount); if (!success) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to add item with sku {sku} to {user.Name} ({user.Id})"), null, user); } - await _logs.LogGameActionAsync(LogAction.AddItem, discordId, userId, $"{sku}:{amount}"); + await logs.LogGameActionAsync(LogAction.AddItem, discordId, userId, $"{sku}:{amount}"); - var action = Math.Sign(amount) < 0 ? "removed" : "added"; + string action = Math.Sign(amount) < 0 ? "removed" : "added"; var embed = new EmbedBuilder() .WithTitle($"Item {action} successfully") @@ -397,22 +397,22 @@ public async Task AddItemsAsync(ulong discordId, uint userId, string public async Task AddXpAsync(ulong discordId, uint userId, int amount, bool staging = false) { - var user = await _gl.Api.GetUserById(userId.ToString()); + var user = await gl.Api.GetUserById(userId.ToString()); if (user == null) { return new ModResult(ModResultType.NotFound, new ResponseMessage($"Could not find any user with id **{userId}**.")); } - var success = staging ? await _gl.Staging.TryAddXpToUserAsync(userId.ToString(), amount) : await _gl.Production.TryAddXpToUserAsync(userId.ToString(), amount); + bool success = staging ? await gl.Staging.TryAddXpToUserAsync(userId.ToString(), amount) : await gl.Production.TryAddXpToUserAsync(userId.ToString(), amount); if (!success) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to add xp to {user.Name} ({user.Id})"), null, user); } - await _logs.LogGameActionAsync(LogAction.AddXp, discordId, userId, $"{amount}"); + await logs.LogGameActionAsync(LogAction.AddXp, discordId, userId, $"{amount}"); - var action = Math.Sign(amount) < 0 ? "removed" : "added"; + string action = Math.Sign(amount) < 0 ? "removed" : "added"; var embed = new EmbedBuilder() .WithTitle($"Experience {action} successfully") @@ -431,14 +431,14 @@ public async Task AddXpAsync(ulong discordId, uint userId, int amount public async Task EnableMaintenance(ulong discordId, uint minutes) { - var success = await _gl.Production.EnableMaintenance(minutes); + bool success = await gl.Production.EnableMaintenance(minutes); if (!success) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to enable maintenance for {minutes} minutes")); } - await _logs.LogGameActionAsync(LogAction.EnableMaintenance, discordId, 0, minutes.ToString()); + await logs.LogGameActionAsync(LogAction.EnableMaintenance, discordId, 0, minutes.ToString()); var embed = new EmbedBuilder() .WithTitle($"Maintenance enabled successfully") @@ -455,15 +455,15 @@ public async Task EnableMaintenance(ulong discordId, uint minutes) public async Task ReloadRules(ulong discordId, bool staging = false) { - var success = staging ? await _gl.Staging.ReloadRules() : await _gl.Production.ReloadRules(); - var serverText = staging ? "Staging" : "Production"; + bool success = staging ? await gl.Staging.ReloadRules() : await gl.Production.ReloadRules(); + string serverText = staging ? "Staging" : "Production"; if (!success) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Could not reload rules on the {serverText.ToLower()} backend!")); } - await _logs.LogGameActionAsync(LogAction.ReloadRules, discordId, 0, serverText); + await logs.LogGameActionAsync(LogAction.ReloadRules, discordId, 0, serverText); var embed = new EmbedBuilder() .WithTitle($"Rules reloaded successfully") @@ -480,14 +480,14 @@ public async Task ReloadRules(ulong discordId, bool staging = false) public async Task RunStagingKickerAsync(ulong discordId) { - var success = await _gl.Staging.RunKicker(); + bool success = await gl.Staging.RunKicker(); if (!success) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to run kicker on staging!")); } - await _logs.LogGameActionAsync(LogAction.RunKicker, discordId, 0, "Staging"); + await logs.LogGameActionAsync(LogAction.RunKicker, discordId, 0, "Staging"); var embed = new EmbedBuilder() .WithTitle($"Kicker ran successfully") @@ -504,14 +504,14 @@ public async Task RunStagingKickerAsync(ulong discordId) public async Task ResetHelpsStagingAsync(ulong discordId, uint userId) { - var success = await _gl.Staging.ResetPlanetHelps(userId.ToString()); + bool success = await gl.Staging.ResetPlanetHelps(userId.ToString()); if (!success) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to reset helps for {userId}!")); } - await _logs.LogGameActionAsync(LogAction.ResetHelps, discordId, 0, "Staging"); + await logs.LogGameActionAsync(LogAction.ResetHelps, discordId, 0, "Staging"); var embed = new EmbedBuilder() .WithTitle($"Helps reset successfully") @@ -529,14 +529,14 @@ public async Task ResetHelpsStagingAsync(ulong discordId, uint userId public async Task ForceWarStagingAsync(ulong discordId, string allianceA, string allianceB) { - var success = await _gl.Staging.ForceWar(allianceA, allianceB); + bool success = await gl.Staging.ForceWar(allianceA, allianceB); if (!success) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to force war between **{allianceA}** and **{allianceB}**!")); } - await _logs.LogGameActionAsync(LogAction.ForceWar, discordId, 0, $"Staging:{allianceA}:{allianceB}"); + await logs.LogGameActionAsync(LogAction.ForceWar, discordId, 0, $"Staging:{allianceA}:{allianceB}"); var embed = new EmbedBuilder() .WithTitle($"War declared successfully") @@ -556,14 +556,14 @@ public async Task ForceWarStagingAsync(ulong discordId, string allian public async Task ForceEndWarStagingAsync(ulong discordId, string allianceA, string allianceB) { - var success = await _gl.Staging.ForceStopWar(allianceA, allianceB); + bool success = await gl.Staging.ForceStopWar(allianceA, allianceB); if (!success) { return new ModResult(ModResultType.BackendError, new ResponseMessage($"Failed to end war between **{allianceA}** and **{allianceB}**!")); } - await _logs.LogGameActionAsync(LogAction.ForceStopWar, discordId, 0, $"Staging:{allianceA}:{allianceB}"); + await logs.LogGameActionAsync(LogAction.ForceStopWar, discordId, 0, $"Staging:{allianceA}:{allianceB}"); var embed = new EmbedBuilder() .WithTitle($"War ended successfully") @@ -583,44 +583,44 @@ public async Task ForceEndWarStagingAsync(ulong discordId, string all public async Task>> GetBattleLogTelemetry(ulong discordId, uint userId) { - var result = await _gl.Api.GetBattlelogTelemetry(userId.ToString()); - await _logs.LogGameActionAsync(LogAction.GetTelemetry, discordId, userId, "BattleLogs"); + var result = await gl.Api.GetBattlelogTelemetry(userId.ToString()); + await logs.LogGameActionAsync(LogAction.GetTelemetry, discordId, userId, "BattleLogs"); return new ModResult>(result, ModResultType.Success); } public async Task>> GetGiftsTelemetry(ulong discordId, uint userId) { - var result = await _gl.Api.GetGiftsTelemetry(userId.ToString()); - await _logs.LogGameActionAsync(LogAction.GetTelemetry, discordId, userId, "Gifts"); + var result = await gl.Api.GetGiftsTelemetry(userId.ToString()); + await logs.LogGameActionAsync(LogAction.GetTelemetry, discordId, userId, "Gifts"); return new ModResult>(result, ModResultType.Success); } public async Task>> GetLoginsTelemetry(ulong discordId, uint userId) { - var result = await _gl.Api.GetLoginsTelemetry(userId.ToString()); - await _logs.LogGameActionAsync(LogAction.GetTelemetry, discordId, userId, "Gifts"); + var result = await gl.Api.GetLoginsTelemetry(userId.ToString()); + await logs.LogGameActionAsync(LogAction.GetTelemetry, discordId, userId, "Gifts"); return new ModResult>(result, ModResultType.Success); } public async Task>>> GetPossibleAlts(ulong discordId, uint userId) { - var result = await _gl.Api.GetFingerprint(userId.ToString()); - await _logs.LogGameActionAsync(LogAction.GetAccounts, discordId, userId); + var result = await gl.Api.GetFingerprint(userId.ToString()); + await logs.LogGameActionAsync(LogAction.GetAccounts, discordId, userId); return new ModResult>>(result, ModResultType.Success); } - private void OnBanTimer(object sender, ElapsedEventArgs e) + private void onBanTimer(object sender, ElapsedEventArgs e) { - var bans = _storage.GetTempbans(); + var bans = storage.GetTempbans(); var bansToRemove = new List(); for (int i = 0; i < bans.Count; i++) { - var time = (bans[i].BanEnd - DateTime.UtcNow).TotalMinutes; + double time = (bans[i].BanEnd - DateTime.UtcNow).TotalMinutes; if (time <= 0) { @@ -633,7 +633,7 @@ private void OnBanTimer(object sender, ElapsedEventArgs e) // remove bans that were handled for (int i = 0; i < bansToRemove.Count; i++) { - _storage.RemoveTempban(bansToRemove[i]); + storage.RemoveTempban(bansToRemove[i]); } } } diff --git a/src/AdvancedBot.Core/Services/PaginatorService.cs b/src/AdvancedBot.Core/Services/PaginatorService.cs index 529486a..02f1f52 100644 --- a/src/AdvancedBot.Core/Services/PaginatorService.cs +++ b/src/AdvancedBot.Core/Services/PaginatorService.cs @@ -1,28 +1,28 @@ -using AdvancedBot.Core.Entities; -using Discord; -using Discord.Interactions; -using Discord.WebSocket; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Timers; +using AdvancedBot.Core.Entities; +using Discord; +using Discord.Interactions; +using Discord.WebSocket; namespace AdvancedBot.Core.Services { public class PaginatorService { - private readonly List _activeMessages; - private readonly ConcurrentDictionary _activeTimers; - private readonly DiscordSocketClient _client; + private readonly List activeMessages; + private readonly ConcurrentDictionary activeTimers; + private readonly DiscordSocketClient client; public PaginatorService(DiscordSocketClient client) { - _activeMessages = new List(); - _activeTimers = new ConcurrentDictionary(); + activeMessages = new List(); + activeTimers = new ConcurrentDictionary(); - _client = client; - _client.InteractionCreated += OnInteraction; + this.client = client; + this.client.InteractionCreated += onInteraction; } public async Task HandleNewPaginatedMessageAsync(SocketInteractionContext context, IEnumerable displayFields, IEnumerable displayTexts, Embed embed) { @@ -39,15 +39,15 @@ public async Task HandleNewPaginatedMessageAsync(SocketInteractionContext contex if (displayFields == null) paginatedMessage.DisplayMessages = displayTexts.ToArray(); else paginatedMessage.DisplayFields = displayFields.ToArray(); - _activeMessages.Add(paginatedMessage); + activeMessages.Add(paginatedMessage); if (paginatedMessage.TotalPages > 1) { - await context.Interaction.ModifyOriginalResponseAsync(msg => msg.Components = CreateMessageComponents()); + await context.Interaction.ModifyOriginalResponseAsync(msg => msg.Components = createMessageComponents()); AddNewTimer(message.Id); } - await GoToFirstPageAsync(context.Interaction, message.Id); + await goToFirstPageAsync(context.Interaction, message.Id); } public void AddNewTimer(ulong messageId) @@ -55,61 +55,61 @@ public void AddNewTimer(ulong messageId) var timer = new Timer(30 * 60 * 1000); timer.Start(); - timer.Elapsed += DisposeActivePaginatorMessage; - _activeTimers.TryAdd(messageId, timer); + timer.Elapsed += disposeActivePaginatorMessage; + activeTimers.TryAdd(messageId, timer); } - private async void DisposeActivePaginatorMessage(object timerObj, ElapsedEventArgs e) + private async void disposeActivePaginatorMessage(object timerObj, ElapsedEventArgs e) { var timer = timerObj as Timer; - var messageId = _activeTimers.First(x => x.Value == timer).Key; + ulong messageId = activeTimers.First(x => x.Value == timer).Key; timer.Enabled = false; - var paginatorMessage = _activeMessages.First(x => x.DiscordMessageId == messageId); + var paginatorMessage = activeMessages.First(x => x.DiscordMessageId == messageId); - var channel = await _client.GetChannelAsync(paginatorMessage.DiscordChannelId) as SocketTextChannel; + var channel = await client.GetChannelAsync(paginatorMessage.DiscordChannelId) as SocketTextChannel; if (await channel.GetMessageAsync(paginatorMessage.DiscordMessageId) is not SocketUserMessage message) return; - await message.ModifyAsync(x => x.Components = CreateMessageComponents(true)); + await message.ModifyAsync(x => x.Components = createMessageComponents(true)); - _activeMessages.Remove(paginatorMessage); - _activeTimers.TryRemove(messageId, out Timer oldTimer); + activeMessages.Remove(paginatorMessage); + activeTimers.TryRemove(messageId, out Timer oldTimer); timer.Dispose(); } public void ResetTimer(ulong messageId) { - _activeTimers.TryRemove(messageId, out Timer currentTimer); + activeTimers.TryRemove(messageId, out Timer currentTimer); currentTimer.Stop(); currentTimer.Start(); - _activeTimers.TryAdd(messageId, currentTimer); + activeTimers.TryAdd(messageId, currentTimer); } - private async Task OnInteraction(SocketInteraction interaction) + private async Task onInteraction(SocketInteraction interaction) { if (interaction is SocketMessageComponent component) { // Not our message to handle - if (_activeMessages.FirstOrDefault(x => x.DiscordMessageId == component.Message.Id) == null) return; + if (activeMessages.FirstOrDefault(x => x.DiscordMessageId == component.Message.Id) == null) return; await component.DeferAsync(); switch (component.Data.CustomId) { case "first": - await GoToFirstPageAsync(interaction, component.Message.Id); + await goToFirstPageAsync(interaction, component.Message.Id); break; case "previous": - await GoToPreviousPageAsync(interaction, component.Message.Id); + await goToPreviousPageAsync(interaction, component.Message.Id); break; case "next": - await GoToNextPageAsync(interaction, component.Message.Id); + await goToNextPageAsync(interaction, component.Message.Id); break; case "last": - await GoToLastPageAsync(interaction, component.Message.Id); + await goToLastPageAsync(interaction, component.Message.Id); break; } @@ -117,7 +117,7 @@ private async Task OnInteraction(SocketInteraction interaction) } } - private static MessageComponent CreateMessageComponents(bool disabled = false) + private static MessageComponent createMessageComponents(bool disabled = false) { var builder = new ComponentBuilder() .WithButton("First", "first", ButtonStyle.Secondary, new Emoji("⏮️"), disabled: disabled) @@ -128,7 +128,7 @@ private static MessageComponent CreateMessageComponents(bool disabled = false) return builder.Build(); } - private static async Task HandleUpdateMessagePagesAsync(SocketInteraction interaction, PaginatedMessage msg) + private static async Task handleUpdateMessagePagesAsync(SocketInteraction interaction, PaginatedMessage msg) { var channel = interaction.Channel; var message = await channel.GetMessageAsync(msg.DiscordMessageId); @@ -164,32 +164,32 @@ private static async Task HandleUpdateMessagePagesAsync(SocketInteraction intera await channel.ModifyMessageAsync(msg.DiscordMessageId, msg => msg.Embeds = new Embed[] { updatedEmbed.Build() }); } - private async Task GoToLastPageAsync(SocketInteraction interaction, ulong id) + private async Task goToLastPageAsync(SocketInteraction interaction, ulong id) { - var paginatorMessage = _activeMessages.Find(x => x.DiscordMessageId == id); + var paginatorMessage = activeMessages.Find(x => x.DiscordMessageId == id); paginatorMessage.CurrentPage = paginatorMessage.TotalPages; - await HandleUpdateMessagePagesAsync(interaction, paginatorMessage); + await handleUpdateMessagePagesAsync(interaction, paginatorMessage); } - private async Task GoToFirstPageAsync(SocketInteraction interaction, ulong id) + private async Task goToFirstPageAsync(SocketInteraction interaction, ulong id) { - var paginatorMessage = _activeMessages.Find(x => x.DiscordMessageId == id); + var paginatorMessage = activeMessages.Find(x => x.DiscordMessageId == id); paginatorMessage.CurrentPage = 1; - await HandleUpdateMessagePagesAsync(interaction, paginatorMessage); + await handleUpdateMessagePagesAsync(interaction, paginatorMessage); } - private async Task GoToNextPageAsync(SocketInteraction interaction, ulong id) + private async Task goToNextPageAsync(SocketInteraction interaction, ulong id) { - var paginatorMessage = _activeMessages.First(x => x.DiscordMessageId == id); + var paginatorMessage = activeMessages.First(x => x.DiscordMessageId == id); paginatorMessage.CurrentPage++; - await HandleUpdateMessagePagesAsync(interaction, paginatorMessage); + await handleUpdateMessagePagesAsync(interaction, paginatorMessage); } - private async Task GoToPreviousPageAsync(SocketInteraction interaction, ulong id) + private async Task goToPreviousPageAsync(SocketInteraction interaction, ulong id) { - var paginatorMessage = _activeMessages.Find(x => x.DiscordMessageId == id); + var paginatorMessage = activeMessages.Find(x => x.DiscordMessageId == id); paginatorMessage.CurrentPage--; - await HandleUpdateMessagePagesAsync(interaction, paginatorMessage); + await handleUpdateMessagePagesAsync(interaction, paginatorMessage); } } }