From ffa2c3f11970f903dafd405fdaf2b619654ccc91 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Wed, 2 Feb 2022 01:44:45 +0100 Subject: [PATCH] Updated editorconfig to (mostly?) require braces around if/else statements, and applied the new formatting rules --- src/NadekoBot/.editorconfig | 61 +++--- src/NadekoBot/Bot.cs | 31 ++- .../Attributes/CommandNameLoadHelper.cs | 2 +- .../Common/Collections/ConcurrentHashSet.cs | 104 +++++++--- .../Common/Collections/IndexedCollection.cs | 14 +- src/NadekoBot/Common/Creds.cs | 8 +- src/NadekoBot/Common/Kwum.cs | 2 + src/NadekoBot/Common/NadekoModule.cs | 9 +- src/NadekoBot/Common/PubSub/EventPubSub.cs | 7 +- src/NadekoBot/Common/PubSub/IPubSub.cs | 5 +- src/NadekoBot/Common/PubSub/JsonSeria.cs | 6 +- src/NadekoBot/Common/PubSub/RedisPubSub.cs | 2 +- .../Common/Replacements/ReplacementBuilder.cs | 2 - src/NadekoBot/Common/Replacements/Replacer.cs | 15 +- .../Common/SmartText/SmartEmbedText.cs | 27 ++- src/NadekoBot/Common/SmartText/SmartText.cs | 12 +- .../TypeReaders/Models/PermissionAction.cs | 3 +- .../Common/TypeReaders/Models/StoopidTime.cs | 18 +- .../Common/TypeReaders/ModuleTypeReader.cs | 5 +- .../TypeReaders/ShmartNumberTypeReader.cs | 3 +- .../Yml/MultilineScalarFlowStyleEmitter.cs | 5 +- src/NadekoBot/Common/Yml/YamlHelper.cs | 12 +- .../Db/Extensions/DiscordUserExtensions.cs | 15 +- .../Db/Extensions/GuildConfigExtensions.cs | 29 ++- .../MusicPlayerSettingsExtensions.cs | 6 +- .../Extensions/NadekoExpressionExtensions.cs | 5 +- .../Db/Extensions/UserXpExtensions.cs | 5 +- src/NadekoBot/Db/Models/Permission.cs | 5 +- src/NadekoBot/Db/Models/ShopEntry.cs | 3 +- .../Db/Models/SlowmodeIgnoredRole.cs | 3 +- .../Db/Models/SlowmodeIgnoredUser.cs | 3 +- src/NadekoBot/Db/Models/Waifu.cs | 6 +- src/NadekoBot/Db/NadekoContext.cs | 87 ++++++-- .../Modules/Administration/Administration.cs | 2 + .../Administration/AdministrationService.cs | 9 +- .../AutoAssignRoleService.cs | 9 +- .../DangerousCommands/DangerousCommands.cs | 3 +- .../DangerousCommandsService.cs | 19 +- .../GameVoiceChannelService.cs | 28 ++- .../Administration/GreetBye/GreetCommands.cs | 6 +- .../Administration/GreetBye/GreetService.cs | 39 ++-- .../Administration/ImageOnlyChannelService.cs | 10 +- .../Administration/Mute/MuteService.cs | 72 ++++--- .../DiscordPermOverrideCommands.cs | 2 +- .../DiscordPermOverrideService.cs | 11 +- .../PlayingRotate/PlayingRotateService.cs | 10 +- .../Protection/ProtectionCommands.cs | 11 +- .../Protection/ProtectionService.cs | 41 +++- .../Protection/UserSpamStats.cs | 2 +- .../Administration/Role/RoleCommands.cs | 28 ++- .../Role/RoleCommandsService.cs | 5 +- .../Administration/Self/SelfCommands.cs | 5 +- .../Administration/Self/SelfService.cs | 58 ++++-- .../SelfAssignedRolesCommands.cs | 2 + .../SelfAssignedRolesService.cs | 25 ++- .../ServerLog/ServerLogCommandService.cs | 58 ++++-- .../UserPunish/UserPunishCommands.cs | 39 +++- .../UserPunish/UserPunishService.cs | 16 +- .../Administration/VcRole/VcRoleService.cs | 22 +- .../CustomReactions/NadekoExpressions.cs | 20 +- .../NadekoExpressionsService.cs | 61 +++--- .../Gambling/AnimalRacing/AnimalRace.cs | 2 + .../AnimalRacing/AnimalRacingCommands.cs | 2 +- .../Gambling/BlackJack/BlackJackCommands.cs | 7 +- .../Modules/Gambling/BlackJack/Blackjack.cs | 25 ++- .../Modules/Gambling/BlackJack/Player.cs | 3 +- .../Modules/Gambling/Connect4/Connect4.cs | 26 ++- .../Gambling/Connect4/Connect4Commands.cs | 14 +- .../Gambling/DiceRoll/DiceRollCommands.cs | 11 +- .../Modules/Gambling/Draw/DrawCommands.cs | 3 +- .../Gambling/Events/GameStatusEvent.cs | 24 ++- .../Modules/Gambling/Events/ReactionEvent.cs | 21 +- .../Gambling/FlipCoin/FlipCoinCommands.cs | 3 +- src/NadekoBot/Modules/Gambling/Gambling.cs | 38 ++-- .../Modules/Gambling/GamblingConfig.cs | 17 +- .../Modules/Gambling/GamblingConfigService.cs | 1 + .../Modules/Gambling/GamblingService.cs | 11 +- .../Gambling/GamblingTopLevelModule.cs | 9 +- .../PlantPick/PlantAndPickCommands.cs | 11 +- .../Gambling/PlantPick/PlantPickService.cs | 12 +- .../Gambling/Raffle/CurrencyRaffleGame.cs | 6 +- .../Gambling/Raffle/CurrencyRaffleService.cs | 2 - .../Modules/Gambling/Shop/ShopCommands.cs | 19 +- .../Modules/Gambling/Slot/SlotCommands.cs | 5 +- .../Modules/Gambling/VoteRewardService.cs | 3 +- .../Gambling/Waifus/WaifuClaimCommands.cs | 3 +- .../Modules/Gambling/Waifus/WaifuService.cs | 63 ++++-- .../Modules/Gambling/Wheel/WheelOfFortune.cs | 6 +- .../Modules/Gambling/~Shared/BetRoll.cs | 13 +- .../Modules/Gambling/~Shared/Decks/Deck.cs | 19 +- .../Modules/Games/Acrophobia/Acrophobia.cs | 2 +- .../Games/Acrophobia/AcropobiaCommands.cs | 2 +- .../Games/ChatterBot/ChatterbotService.cs | 2 +- src/NadekoBot/Modules/Games/GamesConfig.cs | 59 +++++- .../Modules/Games/GamesConfigService.cs | 5 +- src/NadekoBot/Modules/Games/GamesService.cs | 5 +- .../Games/Hangman/DefaultHangmanSource.cs | 2 + .../Modules/Games/Hangman/HangmanCommands.cs | 3 +- .../Modules/Games/Hangman/HangmanService.cs | 8 +- src/NadekoBot/Modules/Games/Nunchi/Nunchi.cs | 4 +- .../Modules/Games/Nunchi/NunchiCommands.cs | 2 +- .../Modules/Games/Polls/PollRunner.cs | 8 +- .../Modules/Games/Polls/PollService.cs | 6 +- .../Games/SpeedTyping/SpeedTypingCommands.cs | 3 +- .../Modules/Games/SpeedTyping/TypingGame.cs | 16 +- .../Modules/Games/TicTacToe/TicTacToe.cs | 8 +- .../Games/TicTacToe/TicTacToeCommands.cs | 2 +- .../Modules/Games/Trivia/TriviaCommands.cs | 3 +- .../Modules/Games/Trivia/TriviaGame.cs | 5 +- .../Modules/Games/Trivia/TriviaQuestion.cs | 13 +- .../Games/Trivia/TriviaQuestionPool.cs | 2 +- src/NadekoBot/Modules/Help/Help.cs | 18 +- src/NadekoBot/Modules/Help/HelpService.cs | 2 +- src/NadekoBot/Modules/Music/Music.cs | 6 +- .../Modules/Music/PlaylistCommands.cs | 8 +- .../Music/Services/AyuVoiceStateService.cs | 7 +- .../Modules/Music/Services/MusicService.cs | 12 +- .../Modules/Music/_Common/Impl/MusicPlayer.cs | 11 +- .../Modules/Music/_Common/Impl/MusicQueue.cs | 9 +- .../Modules/Music/_Common/Impl/VoiceProxy.cs | 6 +- .../_Common/Resolvers/LocalTrackResolver.cs | 3 +- .../_Common/Resolvers/SoundcloudResolver.cs | 6 +- src/NadekoBot/Modules/Nsfw/Nsfw.cs | 9 +- .../Modules/Nsfw/SearchImageCacher.cs | 7 + .../Modules/Nsfw/SearchImagesService.cs | 71 +++++-- .../Downloaders/DanbooruImageDownloader.cs | 3 +- .../Downloaders/DapiImageDownloader.cs | 2 + .../Blacklist/BlacklistCommands.cs | 4 +- .../Permissions/Blacklist/BlacklistService.cs | 15 +- .../CommandCooldown/CmdCdService.cs | 8 +- .../CommandCooldown/CmdCdsCommands.cs | 6 +- .../Permissions/Filter/FilterCommands.cs | 20 +- .../Permissions/Filter/FilterService.cs | 4 +- .../Permissions/PermissionExtensions.cs | 3 +- .../Modules/Permissions/Permissions.cs | 3 +- .../Modules/Permissions/PermissionsService.cs | 9 +- .../Searches/Anime/AnimeSearchCommands.cs | 4 +- .../Modules/Searches/Crypto/CryptoCommands.cs | 5 +- .../Modules/Searches/Crypto/CryptoService.cs | 2 +- .../Modules/Searches/Feeds/FeedCommands.cs | 3 +- .../Modules/Searches/Feeds/FeedsService.cs | 21 +- .../Modules/Searches/MemegenCommands.cs | 2 + src/NadekoBot/Modules/Searches/OsuCommands.cs | 9 +- .../Modules/Searches/PathOfExileCommands.cs | 14 +- .../Modules/Searches/PokemonSearchCommands.cs | 4 + src/NadekoBot/Modules/Searches/Searches.cs | 18 +- .../Modules/Searches/SearchesService.cs | 25 ++- .../StreamNotificationCommands.cs | 3 +- .../StreamNotificationService.cs | 47 ++++- .../Searches/Translate/TranslateService.cs | 14 +- .../StreamNotifications/NotifChecker.cs | 16 +- .../Providers/PicartoProvider.cs | 7 +- .../Providers/TrovoProvider.cs | 13 +- .../Providers/TwitchProvider.cs | 2 + .../Utility/CommandMap/CommandMapCommands.cs | 12 +- .../Utility/CommandMap/CommandMapService.cs | 7 +- .../Modules/Utility/ConfigCommands.cs | 16 +- .../Modules/Utility/Info/InfoCommands.cs | 13 +- .../Utility/Patreon/PatreonRewardsService.cs | 13 +- .../Modules/Utility/Quote/QuoteCommands.cs | 11 +- .../Modules/Utility/Remind/RemindCommands.cs | 6 +- .../Modules/Utility/Remind/RemindService.cs | 18 +- .../Utility/Repeater/RepeatCommands.cs | 3 +- .../Utility/Repeater/RepeaterService.cs | 16 +- .../Utility/Repeater/RunningRepeater.cs | 3 +- .../Utility/StreamRole/StreamRoleService.cs | 32 ++- .../UnitConversion/ConverterService.cs | 8 +- .../UnitConversion/UnitConversionCommands.cs | 4 +- src/NadekoBot/Modules/Utility/Utility.cs | 2 +- .../VerboseErrors/VerboseErrorsService.cs | 3 +- src/NadekoBot/Modules/Xp/Club/Club.cs | 3 +- src/NadekoBot/Modules/Xp/Club/ClubService.cs | 19 +- src/NadekoBot/Modules/Xp/Xp.cs | 9 +- src/NadekoBot/Modules/Xp/XpConfigService.cs | 1 + src/NadekoBot/Modules/Xp/XpService.cs | 106 +++++++--- .../Modules/Xp/_Common/XpTemplate.cs | 181 +++++++++++++++-- src/NadekoBot/NadekoBot.csproj | 192 +++++++++--------- .../Services/Currency/CurrencyService.cs | 7 +- .../Services/Currency/CurrencyType.cs | 2 +- .../Services/Currency/DefaultWallet.cs | 8 +- src/NadekoBot/Services/Currency/IWallet.cs | 4 +- src/NadekoBot/Services/Currency/TxData.cs | 6 +- .../Services/Impl/BehaviorExecutor.cs | 6 + .../Services/Impl/BotCredsProvider.cs | 15 +- src/NadekoBot/Services/Impl/FontProvider.cs | 5 +- .../Services/Impl/GoogleApiService.cs | 18 +- src/NadekoBot/Services/Impl/Localization.cs | 7 +- src/NadekoBot/Services/Impl/RedisCache.cs | 3 +- .../Services/Impl/RedisImagesCache.cs | 16 +- .../Services/Impl/RemoteGrpcCoordinator.cs | 10 +- src/NadekoBot/Services/Impl/StatsService.cs | 16 +- .../Services/Settings/BotConfigService.cs | 5 +- .../Services/strings/impl/BotStrings.cs | 6 +- .../strings/impl/LocalFileStringsSource.cs | 4 + .../strings/impl/RedisBotStringsProvider.cs | 6 +- src/NadekoBot/_Extensions/Extensions.cs | 19 +- .../_Extensions/IMessageChannelExtensions.cs | 7 +- .../_Extensions/ImagesharpExtensions.cs | 13 +- .../_Extensions/ProcessExtensions.cs | 11 +- .../ServiceCollectionExtensions.cs | 5 +- src/NadekoBot/_Extensions/StringExtensions.cs | 6 +- .../data/strings/commands/commands.en-US.yml | 12 +- 202 files changed, 2108 insertions(+), 920 deletions(-) diff --git a/src/NadekoBot/.editorconfig b/src/NadekoBot/.editorconfig index 5787b55e0..3a05399e4 100644 --- a/src/NadekoBot/.editorconfig +++ b/src/NadekoBot/.editorconfig @@ -97,10 +97,10 @@ csharp_style_conditional_delegate_call = true:error # Modifier preferences csharp_prefer_static_local_function = true -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async +csharp_preferred_modifier_order = public, private, protected, internal, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, volatile, async # Code-block preferences -csharp_prefer_braces = when_multiline:suggestion +csharp_prefer_braces = when_multiline:error csharp_prefer_simple_using_statement = true # Expression-level preferences @@ -124,7 +124,7 @@ csharp_style_namespace_declarations = file_scoped:error # New line preferences csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false -csharp_style_allow_embedded_statements_on_same_line_experimental = true +csharp_style_allow_embedded_statements_on_same_line_experimental = false #### C# Formatting Rules #### @@ -171,7 +171,7 @@ csharp_space_between_square_brackets = false # Wrapping preferences csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true +csharp_preserve_single_line_statements = false #### Naming styles #### @@ -236,35 +236,35 @@ dotnet_naming_symbols.const_fields.applicable_kinds = field dotnet_naming_symbols.class.applicable_kinds = class dotnet_naming_symbols.class.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.class.required_modifiers = +dotnet_naming_symbols.class.required_modifiers = dotnet_naming_symbols.interface.applicable_kinds = interface dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = +dotnet_naming_symbols.interface.required_modifiers = dotnet_naming_symbols.struct.applicable_kinds = struct dotnet_naming_symbols.struct.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.struct.required_modifiers = +dotnet_naming_symbols.struct.required_modifiers = dotnet_naming_symbols.enum.applicable_kinds = enum dotnet_naming_symbols.enum.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.enum.required_modifiers = +dotnet_naming_symbols.enum.required_modifiers = dotnet_naming_symbols.method.applicable_kinds = method dotnet_naming_symbols.method.applicable_accessibilities = public -dotnet_naming_symbols.method.required_modifiers = +dotnet_naming_symbols.method.required_modifiers = dotnet_naming_symbols.property.applicable_kinds = property dotnet_naming_symbols.property.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.property.required_modifiers = +dotnet_naming_symbols.property.required_modifiers = dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = +dotnet_naming_symbols.types.required_modifiers = dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = +dotnet_naming_symbols.non_field_members.required_modifiers = dotnet_naming_symbols.private_readonly_field.applicable_kinds = field dotnet_naming_symbols.private_readonly_field.applicable_accessibilities = private, protected @@ -272,7 +272,7 @@ dotnet_naming_symbols.private_readonly_field.required_modifiers = readonly dotnet_naming_symbols.private_field.applicable_kinds = field dotnet_naming_symbols.private_field.applicable_accessibilities = private, protected -dotnet_naming_symbols.private_field.required_modifiers = +dotnet_naming_symbols.private_field.required_modifiers = dotnet_naming_symbols.async_method.applicable_kinds = method, local_function dotnet_naming_symbols.async_method.applicable_accessibilities = * @@ -280,36 +280,36 @@ dotnet_naming_symbols.async_method.required_modifiers = async dotnet_naming_symbols.local_variable.applicable_kinds = parameter, local dotnet_naming_symbols.local_variable.applicable_accessibilities = local -dotnet_naming_symbols.local_variable.required_modifiers = +dotnet_naming_symbols.local_variable.required_modifiers = # Naming styles dotnet_naming_style.all_upper.capitalization = all_upper -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = dotnet_naming_style.pascal_case.capitalization = pascal_case dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = dotnet_naming_style.begins_with_i.capitalization = pascal_case dotnet_naming_style.begins_with_underscore.required_prefix = _ -dotnet_naming_style.begins_with_underscore.required_suffix = -dotnet_naming_style.begins_with_underscore.word_separator = +dotnet_naming_style.begins_with_underscore.required_suffix = +dotnet_naming_style.begins_with_underscore.word_separator = dotnet_naming_style.begins_with_underscore.capitalization = camel_case -dotnet_naming_style.ends_with_async.required_prefix = +dotnet_naming_style.ends_with_async.required_prefix = # dotnet_naming_style.ends_with_async.required_suffix = Async -dotnet_naming_style.ends_with_async.word_separator = +dotnet_naming_style.ends_with_async.word_separator = dotnet_naming_style.ends_with_async.capitalization = pascal_case -dotnet_naming_style.camel_case.required_prefix = -dotnet_naming_style.camel_case.required_suffix = -dotnet_naming_style.camel_case.word_separator = +dotnet_naming_style.camel_case.required_prefix = +dotnet_naming_style.camel_case.required_suffix = +dotnet_naming_style.camel_case.word_separator = dotnet_naming_style.camel_case.capitalization = camel_case # CA1822: Mark members as static @@ -321,8 +321,8 @@ dotnet_diagnostic.ide0004.severity = warning # IDE0058: Expression value is never used dotnet_diagnostic.ide0058.severity = none -# IDE0011: Add braces to 'if'/'else' statement -dotnet_diagnostic.ide0011.severity = none +# # IDE0011: Add braces to 'if'/'else' statement +# dotnet_diagnostic.ide0011.severity = none resharper_wrap_after_invocation_lpar = false resharper_wrap_before_invocation_rpar = false @@ -349,5 +349,8 @@ resharper_csharp_place_type_constraints_on_same_line = false resharper_csharp_wrap_before_extends_colon = true resharper_csharp_place_constructor_initializer_on_same_line = false resharper_force_attribute_style = separate -resharper_braces_for_ifelse = required_for_multiline +resharper_csharp_braces_for_ifelse = required_for_complex +resharper_csharp_braces_for_foreach = required_for_multiline +resharper_csharp_braces_for_while = required_for_multiline +resharper_csharp_braces_for_for = required_for_multiline resharper_arrange_redundant_parentheses_highlighting = hint diff --git a/src/NadekoBot/Bot.cs b/src/NadekoBot/Bot.cs index 86340f879..83581cc9d 100644 --- a/src/NadekoBot/Bot.cs +++ b/src/NadekoBot/Bot.cs @@ -24,10 +24,11 @@ public sealed class Bot public string Mention { get; private set; } public bool IsReady { get; private set; } public int ShardId { get; set; } - + private readonly IBotCredentials _creds; private readonly CommandService _commandService; private readonly DbService _db; + private readonly IBotCredsProvider _credsProvider; // private readonly InteractionService _interactionService; @@ -42,7 +43,8 @@ public sealed class Bot _db = new(_creds); - if (shardId == 0) _db.Setup(); + if (shardId == 0) + _db.Setup(); Client = new(new() { @@ -55,10 +57,14 @@ public sealed class Bot AlwaysResolveStickers = false, AlwaysDownloadDefaultStickers = false, GatewayIntents = GatewayIntents.All, - LogGatewayIntentWarnings = false, + LogGatewayIntentWarnings = false }); - _commandService = new(new() { CaseSensitiveCommands = false, DefaultRunMode = RunMode.Sync }); + _commandService = new(new() + { + CaseSensitiveCommands = false, + DefaultRunMode = RunMode.Sync + }); // _interactionService = new(Client.Rest); @@ -100,7 +106,7 @@ public sealed class Bot .AddMemoryCache() // music .AddMusic(); - // admin + // admin #if GLOBAL_NADEKO svcs.AddSingleton(); #else @@ -109,7 +115,10 @@ public sealed class Bot svcs.AddHttpClient(); svcs.AddHttpClient("memelist") - .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); + .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler + { + AllowAutoRedirect = false + }); if (Environment.GetEnvironmentVariable("NADEKOBOT_IS_COORDINATED") != "1") svcs.AddSingleton(); @@ -147,7 +156,8 @@ public sealed class Bot var exec = Services.GetRequiredService(); exec.Initialize(); - if (Client.ShardId == 0) ApplyConfigMigrations(); + if (Client.ShardId == 0) + ApplyConfigMigrations(); _ = LoadTypeReaders(typeof(Bot).Assembly); @@ -201,12 +211,13 @@ public sealed class Bot Task SetClientReady() { - _= Task.Run(async () => + _ = Task.Run(async () => { clientReady.TrySetResult(true); try { - foreach (var chan in await Client.GetDMChannelsAsync()) await chan.CloseAsync(); + foreach (var chan in await Client.GetDMChannelsAsync()) + await chan.CloseAsync(); } catch { @@ -253,7 +264,7 @@ public sealed class Bot private Task Client_JoinedGuild(SocketGuild arg) { Log.Information("Joined server: {GuildName} [{GuildId}]", arg.Name, arg.Id); - _= Task.Run(async () => + _ = Task.Run(async () => { GuildConfig gc; await using (var uow = _db.GetDbContext()) diff --git a/src/NadekoBot/Common/Attributes/CommandNameLoadHelper.cs b/src/NadekoBot/Common/Attributes/CommandNameLoadHelper.cs index 28b156f8d..d5f023cf8 100644 --- a/src/NadekoBot/Common/Attributes/CommandNameLoadHelper.cs +++ b/src/NadekoBot/Common/Attributes/CommandNameLoadHelper.cs @@ -6,7 +6,7 @@ public static class CommandNameLoadHelper { private static readonly IDeserializer _deserializer = new Deserializer(); - private static readonly Lazy> _lazyCommandAliases + private static readonly Lazy> _lazyCommandAliases = new(() => LoadAliases()); public static Dictionary LoadAliases(string aliasesFilePath = "data/aliases.yml") diff --git a/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs b/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs index 1d8294e0e..b4ef76c59 100644 --- a/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs +++ b/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs @@ -41,8 +41,10 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection collection, IEqualityComparer comparer) : this(comparer) { - if (collection is null) throw new ArgumentNullException(nameof(collection)); + if (collection is null) + throw new ArgumentNullException(nameof(collection)); InitializeFromCollection(collection); } @@ -244,8 +248,10 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection collection, IEqualityComparer comparer) : this(concurrencyLevel, DEFAULT_CAPACITY, false, comparer) { - if (collection is null) throw new ArgumentNullException(nameof(collection)); - if (comparer is null) throw new ArgumentNullException(nameof(comparer)); + if (collection is null) + throw new ArgumentNullException(nameof(collection)); + if (comparer is null) + throw new ArgumentNullException(nameof(comparer)); InitializeFromCollection(collection); } @@ -285,15 +291,19 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection comparer) { - if (concurrencyLevel < 1) throw new ArgumentOutOfRangeException(nameof(concurrencyLevel)); - if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); + if (concurrencyLevel < 1) + throw new ArgumentOutOfRangeException(nameof(concurrencyLevel)); + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity)); // The capacity should be at least as large as the concurrency level. Otherwise, we would have locks that don't guard // any buckets. - if (capacity < concurrencyLevel) capacity = concurrencyLevel; + if (capacity < concurrencyLevel) + capacity = concurrencyLevel; var locks = new object[concurrencyLevel]; - for (var i = 0; i < locks.Length; i++) locks[i] = new(); + for (var i = 0; i < locks.Length; i++) + locks[i] = new(); var countPerLock = new int[locks.Length]; var buckets = new Node[capacity]; @@ -335,7 +345,7 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection.CopyTo(T[] array, int arrayIndex) { - if (array is null) throw new ArgumentNullException(nameof(array)); - if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); + if (array is null) + throw new ArgumentNullException(nameof(array)); + if (arrayIndex < 0) + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); var locksAcquired = 0; try @@ -369,7 +381,8 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection= 0; i++) count += tables.CountPerLock[i]; + for (var i = 0; i < tables.Locks.Length && count >= 0; i++) + count += tables.CountPerLock[i]; if (array.Length - count < arrayIndex || count < 0) //"count" itself or "count + arrayIndex" can overflow throw new ArgumentException( @@ -444,20 +457,26 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection collection) { - foreach (var item in collection) AddInternal(item, _comparer.GetHashCode(item), false); + foreach (var item in collection) + AddInternal(item, _comparer.GetHashCode(item), false); - if (budget == 0) budget = tables.Buckets.Length / tables.Locks.Length; + if (budget == 0) + budget = tables.Buckets.Length / tables.Locks.Length; } private bool AddInternal(T item, int hashcode, bool acquireLock) { while (true) { - var localTables = this.tables; - GetBucketAndLockNo(hashcode, out var bucketNo, out var lockNo, localTables.Buckets.Length, localTables.Locks.Length); + var localTables = tables; + GetBucketAndLockNo(hashcode, + out var bucketNo, + out var lockNo, + localTables.Buckets.Length, + localTables.Locks.Length); var resizeDesired = false; var lockTaken = false; @@ -501,13 +526,15 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection budget) resizeDesired = true; + if (localTables.CountPerLock[lockNo] > budget) + resizeDesired = true; } finally { @@ -542,7 +570,8 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection maxArrayLength) maximizeTableSize = true; + if (newLength > maxArrayLength) + maximizeTableSize = true; } } catch (OverflowException) @@ -647,7 +680,8 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IList - where T : class, IIndexed + where T : class, IIndexed { public List Source { get; } @@ -54,7 +54,7 @@ public class IndexedCollection : IList public void Add(T item) { ArgumentNullException.ThrowIfNull(item); - + lock (_locker) { item.Index = Source.Count; @@ -93,8 +93,10 @@ public class IndexedCollection : IList if (Source.Remove(item)) { for (var i = 0; i < Source.Count; i++) + { if (Source[i].Index != i) Source[i].Index = i; + } return true; } @@ -108,7 +110,8 @@ public class IndexedCollection : IList lock (_locker) { Source.Insert(index, item); - for (var i = index; i < Source.Count; i++) Source[i].Index = i; + for (var i = index; i < Source.Count; i++) + Source[i].Index = i; } } @@ -117,7 +120,8 @@ public class IndexedCollection : IList lock (_locker) { Source.RemoveAt(index); - for (var i = index; i < Source.Count; i++) Source[i].Index = i; + for (var i = index; i < Source.Count; i++) + Source[i].Index = i; } } @@ -126,8 +130,10 @@ public class IndexedCollection : IList lock (_locker) { for (var i = 0; i < Source.Count; i++) + { if (Source[i].Index != i) Source[i].Index = i; + } } } diff --git a/src/NadekoBot/Common/Creds.cs b/src/NadekoBot/Common/Creds.cs index a475646ad..6792ebcf6 100644 --- a/src/NadekoBot/Common/Creds.cs +++ b/src/NadekoBot/Common/Creds.cs @@ -66,7 +66,7 @@ Used for cryptocurrency related commands.")] [Comment(@"Api key used for Osu related commands. Obtain this key at https://osu.ppy.sh/p/api")] public string OsuApiKey { get; set; } - + [Comment(@"Optional Trovo client id. You should only use this if Trovo notifications stopped working or you're getting ratelimit errors.")] public string TrovoClientId { get; set; } @@ -96,7 +96,11 @@ Windows default BotListToken = string.Empty; CleverbotApiKey = string.Empty; RedisOptions = "localhost:6379,syncTimeout=30000,responseTimeout=30000,allowAdmin=true,password="; - Db = new() { Type = "sqlite", ConnectionString = "Data Source=data/NadekoBot.db" }; + Db = new() + { + Type = "sqlite", + ConnectionString = "Data Source=data/NadekoBot.db" + }; CoordinatorUrl = "http://localhost:3442"; diff --git a/src/NadekoBot/Common/Kwum.cs b/src/NadekoBot/Common/Kwum.cs index 5ae773126..347792c50 100644 --- a/src/NadekoBot/Common/Kwum.cs +++ b/src/NadekoBot/Common/Kwum.cs @@ -45,8 +45,10 @@ public readonly struct kwum : IEquatable { value = default; foreach (var c in input) + { if (!IsValidChar(c)) return false; + } value = new(input); return true; diff --git a/src/NadekoBot/Common/NadekoModule.cs b/src/NadekoBot/Common/NadekoModule.cs index f097af53b..b8f2aee17 100644 --- a/src/NadekoBot/Common/NadekoModule.cs +++ b/src/NadekoBot/Common/NadekoModule.cs @@ -11,7 +11,7 @@ namespace NadekoBot.Modules; public abstract class NadekoModule : ModuleBase { protected CultureInfo Culture { get; set; } - + // Injected by Discord.net public IBotStrings Strings { get; set; } public CommandHandler _cmdHandler { get; set; } @@ -88,7 +88,7 @@ public abstract class NadekoModule : ModuleBase } finally { - _= Task.Run(() => msg.DeleteAsync()); + _ = Task.Run(() => msg.DeleteAsync()); } } @@ -113,7 +113,7 @@ public abstract class NadekoModule : ModuleBase Task MessageReceived(SocketMessage arg) { - _= Task.Run(() => + _ = Task.Run(() => { if (arg is not SocketUserMessage userMsg || userMsg.Channel is not ITextChannel @@ -121,7 +121,8 @@ public abstract class NadekoModule : ModuleBase || userMsg.Channel.Id != channelId) return Task.CompletedTask; - if (userInputTask.TrySetResult(arg.Content)) userMsg.DeleteAfter(1); + if (userInputTask.TrySetResult(arg.Content)) + userMsg.DeleteAfter(1); return Task.CompletedTask; }); diff --git a/src/NadekoBot/Common/PubSub/EventPubSub.cs b/src/NadekoBot/Common/PubSub/EventPubSub.cs index 1c4eabe21..02021b3fb 100644 --- a/src/NadekoBot/Common/PubSub/EventPubSub.cs +++ b/src/NadekoBot/Common/PubSub/EventPubSub.cs @@ -6,7 +6,7 @@ public class EventPubSub : IPubSub private readonly object _locker = new(); public Task Sub(in TypedKey key, Func action) - where TData: notnull + where TData : notnull { Func localAction = obj => action((TData)obj); lock (_locker) @@ -30,7 +30,7 @@ public class EventPubSub : IPubSub } public Task Pub(in TypedKey key, TData data) - where TData: notnull + where TData : notnull { lock (_locker) { @@ -67,7 +67,8 @@ public class EventPubSub : IPubSub // if our dictionary has no more elements after // removing the entry // it's safe to remove it from the key's subscriptions - if (actions.Count == 0) _actions.Remove(key.Key); + if (actions.Count == 0) + _actions.Remove(key.Key); } } diff --git a/src/NadekoBot/Common/PubSub/IPubSub.cs b/src/NadekoBot/Common/PubSub/IPubSub.cs index f0ee0940f..2d66bf6d7 100644 --- a/src/NadekoBot/Common/PubSub/IPubSub.cs +++ b/src/NadekoBot/Common/PubSub/IPubSub.cs @@ -3,7 +3,8 @@ namespace NadekoBot.Common; public interface IPubSub { public Task Pub(in TypedKey key, TData data) - where TData: notnull; + where TData : notnull; + public Task Sub(in TypedKey key, Func action) - where TData: notnull; + where TData : notnull; } \ No newline at end of file diff --git a/src/NadekoBot/Common/PubSub/JsonSeria.cs b/src/NadekoBot/Common/PubSub/JsonSeria.cs index 63d14c210..416c1b9c4 100644 --- a/src/NadekoBot/Common/PubSub/JsonSeria.cs +++ b/src/NadekoBot/Common/PubSub/JsonSeria.cs @@ -7,7 +7,11 @@ public class JsonSeria : ISeria { private readonly JsonSerializerOptions _serializerOptions = new() { - Converters = { new Rgba32Converter(), new CultureInfoConverter() } + Converters = + { + new Rgba32Converter(), + new CultureInfoConverter() + } }; public byte[] Serialize(T data) diff --git a/src/NadekoBot/Common/PubSub/RedisPubSub.cs b/src/NadekoBot/Common/PubSub/RedisPubSub.cs index 533d0f443..7f250fee5 100644 --- a/src/NadekoBot/Common/PubSub/RedisPubSub.cs +++ b/src/NadekoBot/Common/PubSub/RedisPubSub.cs @@ -33,7 +33,7 @@ public sealed class RedisPubSub : IPubSub try { var dataObj = _serializer.Deserialize(data); - if(dataObj is not null) + if (dataObj is not null) await action(dataObj); else Log.Warning("Publishing event {EventName} with a null value. This is not allowed", diff --git a/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs b/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs index d9c211456..2a40a90b0 100644 --- a/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs +++ b/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs @@ -63,10 +63,8 @@ public class ReplacementBuilder { var to = TimeZoneInfo.Local; if (g is not null) - { if (GuildTimezoneService.AllServices.TryGetValue(client.CurrentUser.Id, out var tz)) to = tz.GetTimeZoneOrDefault(g.Id) ?? TimeZoneInfo.Local; - } return TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Utc, to).ToString("HH:mm ") + to.StandardName.GetInitials(); diff --git a/src/NadekoBot/Common/Replacements/Replacer.cs b/src/NadekoBot/Common/Replacements/Replacer.cs index acfa4a45b..3a772b818 100644 --- a/src/NadekoBot/Common/Replacements/Replacer.cs +++ b/src/NadekoBot/Common/Replacements/Replacer.cs @@ -20,10 +20,13 @@ public class Replacer return input; foreach (var (key, text) in _replacements) + { if (input.Contains(key)) input = input.Replace(key, text(), StringComparison.InvariantCulture); + } - foreach (var item in _regex) input = item.Regex.Replace(input, m => item.Replacement(m)); + foreach (var item in _regex) + input = item.Regex.Replace(input, m => item.Replacement(m)); return input; } @@ -53,7 +56,8 @@ public class Replacer if (embedData.Author is not null) newEmbedData.Author = new() { - Name = Replace(embedData.Author.Name), IconUrl = Replace(embedData.Author.IconUrl) + Name = Replace(embedData.Author.Name), + IconUrl = Replace(embedData.Author.IconUrl) }; if (embedData.Fields is not null) @@ -63,7 +67,9 @@ public class Replacer { var newF = new SmartTextEmbedField { - Name = Replace(f.Name), Value = Replace(f.Value), Inline = f.Inline + Name = Replace(f.Name), + Value = Replace(f.Value), + Inline = f.Inline }; fields.Add(newF); } @@ -74,7 +80,8 @@ public class Replacer if (embedData.Footer is not null) newEmbedData.Footer = new() { - Text = Replace(embedData.Footer.Text), IconUrl = Replace(embedData.Footer.IconUrl) + Text = Replace(embedData.Footer.Text), + IconUrl = Replace(embedData.Footer.IconUrl) }; newEmbedData.Color = embedData.Color; diff --git a/src/NadekoBot/Common/SmartText/SmartEmbedText.cs b/src/NadekoBot/Common/SmartText/SmartEmbedText.cs index 1a0bb5653..5a3e40eb1 100644 --- a/src/NadekoBot/Common/SmartText/SmartEmbedText.cs +++ b/src/NadekoBot/Common/SmartText/SmartEmbedText.cs @@ -36,16 +36,31 @@ public sealed record SmartEmbedText : SmartText Url = eb.Url, Thumbnail = eb.Thumbnail?.Url, Image = eb.Image?.Url, - Author = eb.Author is { } ea ? new() { Name = ea.Name, Url = ea.Url, IconUrl = ea.IconUrl } : null, - Footer = eb.Footer is { } ef ? new() { Text = ef.Text, IconUrl = ef.IconUrl } : null + Author = eb.Author is { } ea + ? new() + { + Name = ea.Name, + Url = ea.Url, + IconUrl = ea.IconUrl + } + : null, + Footer = eb.Footer is { } ef + ? new() + { + Text = ef.Text, + IconUrl = ef.IconUrl + } + : null }; if (eb.Fields.Length > 0) set.Fields = eb.Fields.Select(field => new SmartTextEmbedField - { - Inline = field.Inline, Name = field.Name, Value = field.Value - }) + { + Inline = field.Inline, + Name = field.Name, + Value = field.Value + }) .ToArray(); set.Color = eb.Color?.RawValue ?? 0; @@ -91,8 +106,10 @@ public sealed record SmartEmbedText : SmartText if (Fields is not null) foreach (var f in Fields) + { if (!string.IsNullOrWhiteSpace(f.Name) && !string.IsNullOrWhiteSpace(f.Value)) embed.AddField(f.Name, f.Value, f.Inline); + } return embed; } diff --git a/src/NadekoBot/Common/SmartText/SmartText.cs b/src/NadekoBot/Common/SmartText/SmartText.cs index a5c768eb2..23fb5b8af 100644 --- a/src/NadekoBot/Common/SmartText/SmartText.cs +++ b/src/NadekoBot/Common/SmartText/SmartText.cs @@ -14,7 +14,10 @@ public abstract record SmartText public static SmartText operator +(SmartText text, string input) => text switch { - SmartEmbedText set => set with { PlainText = set.PlainText + input }, + SmartEmbedText set => set with + { + PlainText = set.PlainText + input + }, SmartPlainText spt => new SmartPlainText(spt.Text + input), _ => throw new ArgumentOutOfRangeException(nameof(text)) }; @@ -22,7 +25,10 @@ public abstract record SmartText public static SmartText operator +(string input, SmartText text) => text switch { - SmartEmbedText set => set with { PlainText = input + set.PlainText }, + SmartEmbedText set => set with + { + PlainText = input + set.PlainText + }, SmartPlainText spt => new SmartPlainText(input + spt.Text), _ => throw new ArgumentOutOfRangeException(nameof(text)) }; @@ -41,7 +47,7 @@ public abstract record SmartText smartEmbedText.NormalizeFields(); - if (!smartEmbedText.IsValid) + if (!smartEmbedText.IsValid) return new SmartPlainText(input); return smartEmbedText; diff --git a/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs b/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs index 476be8b7d..5a05a1616 100644 --- a/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs +++ b/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs @@ -16,7 +16,8 @@ public class PermissionAction public override bool Equals(object obj) { - if (obj is null || GetType() != obj.GetType()) return false; + if (obj is null || GetType() != obj.GetType()) + return false; return Value == ((PermissionAction)obj).Value; } diff --git a/src/NadekoBot/Common/TypeReaders/Models/StoopidTime.cs b/src/NadekoBot/Common/TypeReaders/Models/StoopidTime.cs index 312fc8e0a..ac025caeb 100644 --- a/src/NadekoBot/Common/TypeReaders/Models/StoopidTime.cs +++ b/src/NadekoBot/Common/TypeReaders/Models/StoopidTime.cs @@ -18,20 +18,23 @@ public class StoopidTime { var m = _regex.Match(input); - if (m.Length == 0) throw new ArgumentException("Invalid string input format."); + if (m.Length == 0) + throw new ArgumentException("Invalid string input format."); var namesAndValues = new Dictionary(); foreach (var groupName in _regex.GetGroupNames()) { - if (groupName == "0") continue; + if (groupName == "0") + continue; if (!int.TryParse(m.Groups[groupName].Value, out var value)) { namesAndValues[groupName] = 0; continue; } - if (value < 1) throw new ArgumentException($"Invalid {groupName} value."); + if (value < 1) + throw new ArgumentException($"Invalid {groupName} value."); namesAndValues[groupName] = value; } @@ -40,8 +43,13 @@ public class StoopidTime namesAndValues["hours"], namesAndValues["minutes"], namesAndValues["seconds"]); - if (ts > TimeSpan.FromDays(90)) throw new ArgumentException("Time is too long."); + if (ts > TimeSpan.FromDays(90)) + throw new ArgumentException("Time is too long."); - return new() { Input = input, Time = ts }; + return new() + { + Input = input, + Time = ts + }; } } \ No newline at end of file diff --git a/src/NadekoBot/Common/TypeReaders/ModuleTypeReader.cs b/src/NadekoBot/Common/TypeReaders/ModuleTypeReader.cs index 0d1c598bb..e1620772d 100644 --- a/src/NadekoBot/Common/TypeReaders/ModuleTypeReader.cs +++ b/src/NadekoBot/Common/TypeReaders/ModuleTypeReader.cs @@ -37,7 +37,10 @@ public sealed class ModuleOrCrTypeReader : NadekoTypeReader if (module is null && input != "ACTUALEXPRESSIONS") return new(TypeReaderResult.FromError(CommandError.ParseFailed, "No such module found.")); - return new(TypeReaderResult.FromSuccess(new ModuleOrCrInfo { Name = input })); + return new(TypeReaderResult.FromSuccess(new ModuleOrCrInfo + { + Name = input + })); } } diff --git a/src/NadekoBot/Common/TypeReaders/ShmartNumberTypeReader.cs b/src/NadekoBot/Common/TypeReaders/ShmartNumberTypeReader.cs index 62b9448af..7b04e06a9 100644 --- a/src/NadekoBot/Common/TypeReaders/ShmartNumberTypeReader.cs +++ b/src/NadekoBot/Common/TypeReaders/ShmartNumberTypeReader.cs @@ -40,7 +40,8 @@ public sealed class ShmartNumberTypeReader : NadekoTypeReader } catch (Exception) { - return ValueTask.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, $"Invalid input: {input}")); + return ValueTask.FromResult( + TypeReaderResult.FromError(CommandError.ParseFailed, $"Invalid input: {input}")); } } diff --git a/src/NadekoBot/Common/Yml/MultilineScalarFlowStyleEmitter.cs b/src/NadekoBot/Common/Yml/MultilineScalarFlowStyleEmitter.cs index a3d830845..754d485a7 100644 --- a/src/NadekoBot/Common/Yml/MultilineScalarFlowStyleEmitter.cs +++ b/src/NadekoBot/Common/Yml/MultilineScalarFlowStyleEmitter.cs @@ -21,7 +21,10 @@ public class MultilineScalarFlowStyleEmitter : ChainedEventEmitter { var isMultiLine = value.IndexOfAny(new[] { '\r', '\n', '\x85', '\x2028', '\x2029' }) >= 0; if (isMultiLine) - eventInfo = new(eventInfo.Source) { Style = ScalarStyle.Literal }; + eventInfo = new(eventInfo.Source) + { + Style = ScalarStyle.Literal + }; } } diff --git a/src/NadekoBot/Common/Yml/YamlHelper.cs b/src/NadekoBot/Common/Yml/YamlHelper.cs index f5841e5fb..d1159d801 100644 --- a/src/NadekoBot/Common/Yml/YamlHelper.cs +++ b/src/NadekoBot/Common/Yml/YamlHelper.cs @@ -18,14 +18,16 @@ public class YamlHelper foreach (var c in point) { - if (!IsHex(c)) return point; + if (!IsHex(c)) + return point; character = (character << 4) + AsHex(c); } // Check the value and write the character. - if (character is (>= 0xD800 and <= 0xDFFF) or > 0x10FFFF) return point; + if (character is (>= 0xD800 and <= 0xDFFF) or > 0x10FFFF) + return point; return char.ConvertFromUtf32(character); } @@ -35,9 +37,11 @@ public class YamlHelper public static int AsHex(char c) { - if (c <= '9') return c - '0'; + if (c <= '9') + return c - '0'; - if (c <= 'F') return c - 'A' + 10; + if (c <= 'F') + return c - 'A' + 10; return c - 'a' + 10; } diff --git a/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs b/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs index a15d84529..45b861ae2 100644 --- a/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs +++ b/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs @@ -26,8 +26,16 @@ public static class DiscordUserExtensions TotalXp = 0, CurrencyAmount = 0 }, - old => new() { Username = username, Discriminator = discrim, AvatarId = avatarId }, - () => new() { UserId = userId }); + old => new() + { + Username = username, + Discriminator = discrim, + AvatarId = avatarId + }, + () => new() + { + UserId = userId + }); //temp is only used in updatecurrencystate, so that i don't overwrite real usernames/discrims with Unknown public static DiscordUser GetOrCreateUser( @@ -72,7 +80,8 @@ public static class DiscordUserExtensions public static void RemoveFromMany(this DbSet users, IEnumerable ids) { var items = users.AsQueryable().Where(x => ids.Contains(x.UserId)); - foreach (var item in items) item.CurrencyAmount = 0; + foreach (var item in items) + item.CurrencyAmount = 0; } public static bool TryUpdateCurrencyState( diff --git a/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs b/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs index f77dd469d..de91b381c 100644 --- a/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs +++ b/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs @@ -11,8 +11,16 @@ public static class GuildConfigExtensions private static List DefaultWarnPunishments => new() { - new() { Count = 3, Punishment = PunishmentAction.Kick }, - new() { Count = 5, Punishment = PunishmentAction.Ban } + new() + { + Count = 3, + Punishment = PunishmentAction.Kick + }, + new() + { + Count = 5, + Punishment = PunishmentAction.Ban + } }; /// @@ -105,7 +113,10 @@ public static class GuildConfigExtensions if (logSetting is null) { - ctx.LogSettings.Add(logSetting = new() { GuildId = guildId }); + ctx.LogSettings.Add(logSetting = new() + { + GuildId = guildId + }); ctx.SaveChanges(); } @@ -128,7 +139,11 @@ public static class GuildConfigExtensions if (config is null) // if there is no guildconfig, create new one { - ctx.GuildConfigs.Add(config = new() { GuildId = guildId, Permissions = Permissionv2.GetDefaultPermlist }); + ctx.GuildConfigs.Add(config = new() + { + GuildId = guildId, + Permissions = Permissionv2.GetDefaultPermlist + }); ctx.SaveChanges(); } else if (config.Permissions is null || !config.Permissions.Any()) // if no perms, add default ones @@ -181,7 +196,11 @@ public static class GuildConfigExtensions .Include(x => x.GenerateCurrencyChannelIds) .Where(x => x.GenerateCurrencyChannelIds.Any()) .SelectMany(x => x.GenerateCurrencyChannelIds) - .Select(x => new GeneratingChannel { ChannelId = x.ChannelId, GuildId = x.GuildConfig.GuildId }) + .Select(x => new GeneratingChannel + { + ChannelId = x.ChannelId, + GuildId = x.GuildConfig.GuildId + }) .ToArray(); public class GeneratingChannel diff --git a/src/NadekoBot/Db/Extensions/MusicPlayerSettingsExtensions.cs b/src/NadekoBot/Db/Extensions/MusicPlayerSettingsExtensions.cs index 3a026024a..68047b7e1 100644 --- a/src/NadekoBot/Db/Extensions/MusicPlayerSettingsExtensions.cs +++ b/src/NadekoBot/Db/Extensions/MusicPlayerSettingsExtensions.cs @@ -12,7 +12,11 @@ public static class MusicPlayerSettingsExtensions if (toReturn is null) { - var newSettings = new MusicPlayerSettings { GuildId = guildId, PlayerRepeat = PlayerRepeatType.Queue }; + var newSettings = new MusicPlayerSettings + { + GuildId = guildId, + PlayerRepeat = PlayerRepeatType.Queue + }; await settings.AddAsync(newSettings); return newSettings; diff --git a/src/NadekoBot/Db/Extensions/NadekoExpressionExtensions.cs b/src/NadekoBot/Db/Extensions/NadekoExpressionExtensions.cs index c661dd369..2ff117385 100644 --- a/src/NadekoBot/Db/Extensions/NadekoExpressionExtensions.cs +++ b/src/NadekoBot/Db/Extensions/NadekoExpressionExtensions.cs @@ -13,6 +13,9 @@ public static class NadekoExpressionExtensions public static IEnumerable ForId(this DbSet exprs, ulong id) => exprs.AsNoTracking().AsQueryable().Where(x => x.GuildId == id).ToList(); - public static NadekoExpression GetByGuildIdAndInput(this DbSet exprs, ulong? guildId, string input) + public static NadekoExpression GetByGuildIdAndInput( + this DbSet exprs, + ulong? guildId, + string input) => exprs.FirstOrDefault(x => x.GuildId == guildId && x.Trigger.ToUpper() == input); } \ No newline at end of file diff --git a/src/NadekoBot/Db/Extensions/UserXpExtensions.cs b/src/NadekoBot/Db/Extensions/UserXpExtensions.cs index 5d2dcbf85..3562df3a6 100644 --- a/src/NadekoBot/Db/Extensions/UserXpExtensions.cs +++ b/src/NadekoBot/Db/Extensions/UserXpExtensions.cs @@ -15,7 +15,10 @@ public static class UserXpExtensions if (usr is null) ctx.Add(usr = new() { - Xp = 0, UserId = userId, NotifyOnLevelUp = XpNotificationLocation.None, GuildId = guildId + Xp = 0, + UserId = userId, + NotifyOnLevelUp = XpNotificationLocation.None, + GuildId = guildId }); return usr; diff --git a/src/NadekoBot/Db/Models/Permission.cs b/src/NadekoBot/Db/Models/Permission.cs index 11082fa42..5ad1b021e 100644 --- a/src/NadekoBot/Db/Models/Permission.cs +++ b/src/NadekoBot/Db/Models/Permission.cs @@ -38,7 +38,10 @@ public class Permissionv2 : DbEntity, IIndexed }; public static List GetDefaultPermlist - => new() { AllowAllPerm }; + => new() + { + AllowAllPerm + }; } public enum PrimaryPermissionType diff --git a/src/NadekoBot/Db/Models/ShopEntry.cs b/src/NadekoBot/Db/Models/ShopEntry.cs index 3c644146f..862fb0030 100644 --- a/src/NadekoBot/Db/Models/ShopEntry.cs +++ b/src/NadekoBot/Db/Models/ShopEntry.cs @@ -32,7 +32,8 @@ public class ShopEntryItem : DbEntity public override bool Equals(object obj) { - if (obj is null || GetType() != obj.GetType()) return false; + if (obj is null || GetType() != obj.GetType()) + return false; return ((ShopEntryItem)obj).Text == Text; } diff --git a/src/NadekoBot/Db/Models/SlowmodeIgnoredRole.cs b/src/NadekoBot/Db/Models/SlowmodeIgnoredRole.cs index 2398045d6..13dee800c 100644 --- a/src/NadekoBot/Db/Models/SlowmodeIgnoredRole.cs +++ b/src/NadekoBot/Db/Models/SlowmodeIgnoredRole.cs @@ -8,7 +8,8 @@ public class SlowmodeIgnoredRole : DbEntity // override object.Equals public override bool Equals(object obj) { - if (obj is null || GetType() != obj.GetType()) return false; + if (obj is null || GetType() != obj.GetType()) + return false; return ((SlowmodeIgnoredRole)obj).RoleId == RoleId; } diff --git a/src/NadekoBot/Db/Models/SlowmodeIgnoredUser.cs b/src/NadekoBot/Db/Models/SlowmodeIgnoredUser.cs index 8e0b68e9c..2972749b7 100644 --- a/src/NadekoBot/Db/Models/SlowmodeIgnoredUser.cs +++ b/src/NadekoBot/Db/Models/SlowmodeIgnoredUser.cs @@ -8,7 +8,8 @@ public class SlowmodeIgnoredUser : DbEntity // override object.Equals public override bool Equals(object obj) { - if (obj is null || GetType() != obj.GetType()) return false; + if (obj is null || GetType() != obj.GetType()) + return false; return ((SlowmodeIgnoredUser)obj).UserId == UserId; } diff --git a/src/NadekoBot/Db/Models/Waifu.cs b/src/NadekoBot/Db/Models/Waifu.cs index b6e2b5e87..0a71d0e95 100644 --- a/src/NadekoBot/Db/Models/Waifu.cs +++ b/src/NadekoBot/Db/Models/Waifu.cs @@ -25,7 +25,8 @@ public class WaifuInfo : DbEntity var waifuUsername = Waifu.Username.TrimTo(20); var claimerUsername = Claimer?.Username.TrimTo(20); - if (ClaimerId is not null) claimer = $"{claimerUsername}#{Claimer.Discriminator}"; + if (ClaimerId is not null) + claimer = $"{claimerUsername}#{Claimer.Discriminator}"; if (AffinityId is null) status = $"... but {waifuUsername}'s heart is empty"; else if (AffinityId == ClaimerId) @@ -58,7 +59,8 @@ public class WaifuLbResult var waifuUsername = Username.TrimTo(20); var claimerUsername = Claimer?.TrimTo(20); - if (Claimer is not null) claimer = $"{claimerUsername}#{ClaimerDiscrim}"; + if (Claimer is not null) + claimer = $"{claimerUsername}#{ClaimerDiscrim}"; if (Affinity is null) status = $"... but {waifuUsername}'s heart is empty"; else if (Affinity + AffinityDiscrim == Claimer + ClaimerDiscrim) diff --git a/src/NadekoBot/Db/NadekoContext.cs b/src/NadekoBot/Db/NadekoContext.cs index 1cef37327..65d0127db 100644 --- a/src/NadekoBot/Db/NadekoContext.cs +++ b/src/NadekoBot/Db/NadekoContext.cs @@ -62,7 +62,7 @@ public class NadekoContext : DbContext public DbSet NsfwBlacklistedTags { get; set; } public DbSet AutoTranslateChannels { get; set; } public DbSet AutoTranslateUsers { get; set; } - + public DbSet Permissions { get; set; } public NadekoContext(DbContextOptions options) @@ -95,7 +95,12 @@ public class NadekoContext : DbContext .HasForeignKey(x => x.GuildConfigId) .OnDelete(DeleteBehavior.Cascade); - modelBuilder.Entity().HasAlternateKey(x => new { x.GuildConfigId, x.Url }); + modelBuilder.Entity() + .HasAlternateKey(x => new + { + x.GuildConfigId, + x.Url + }); modelBuilder.Entity().HasIndex(x => x.MessageId).IsUnique(); @@ -115,7 +120,12 @@ public class NadekoContext : DbContext var selfassignableRolesEntity = modelBuilder.Entity(); - selfassignableRolesEntity.HasIndex(s => new { s.GuildId, s.RoleId }).IsUnique(); + selfassignableRolesEntity.HasIndex(s => new + { + s.GuildId, + s.RoleId + }) + .IsUnique(); selfassignableRolesEntity.Property(x => x.Group).HasDefaultValue(0); @@ -160,7 +170,7 @@ public class NadekoContext : DbContext du.Property(x => x.TotalXp) .HasDefaultValue(0); - + du.Property(x => x.CurrencyAmount) .HasDefaultValue(0); @@ -196,7 +206,12 @@ public class NadekoContext : DbContext #region XpStats var xps = modelBuilder.Entity(); - xps.HasIndex(x => new { x.UserId, x.GuildId }).IsUnique(); + xps.HasIndex(x => new + { + x.UserId, + x.GuildId + }) + .IsUnique(); xps.Property(x => x.LastLevelUp) .HasDefaultValue(new DateTime(2017, 9, 21, 20, 53, 13, 307, DateTimeKind.Local)); @@ -216,7 +231,13 @@ public class NadekoContext : DbContext #region XpRoleReward - modelBuilder.Entity().HasIndex(x => new { x.XpSettingsId, x.Level }).IsUnique(); + modelBuilder.Entity() + .HasIndex(x => new + { + x.XpSettingsId, + x.Level + }) + .IsUnique(); #endregion @@ -226,19 +247,33 @@ public class NadekoContext : DbContext ci.HasOne(x => x.Owner).WithOne().HasForeignKey(x => x.OwnerId); - ci.HasAlternateKey(x => new { x.Name, x.Discrim }); + ci.HasAlternateKey(x => new + { + x.Name, + x.Discrim + }); #endregion #region ClubManytoMany - modelBuilder.Entity().HasKey(t => new { t.ClubId, t.UserId }); + modelBuilder.Entity() + .HasKey(t => new + { + t.ClubId, + t.UserId + }); modelBuilder.Entity().HasOne(pt => pt.User).WithMany(); modelBuilder.Entity().HasOne(pt => pt.Club).WithMany(x => x.Applicants); - modelBuilder.Entity().HasKey(t => new { t.ClubId, t.UserId }); + modelBuilder.Entity() + .HasKey(t => new + { + t.ClubId, + t.UserId + }); modelBuilder.Entity().HasOne(pt => pt.User).WithMany(); @@ -264,12 +299,10 @@ public class NadekoContext : DbContext e.Property(x => x.Type) .IsRequired(); - + e.Property(x => x.Extra) .IsRequired(); - }); - #endregion @@ -281,7 +314,13 @@ public class NadekoContext : DbContext #region GroupName - modelBuilder.Entity().HasIndex(x => new { x.GuildConfigId, x.Number }).IsUnique(); + modelBuilder.Entity() + .HasIndex(x => new + { + x.GuildConfigId, + x.Number + }) + .IsUnique(); modelBuilder.Entity() .HasOne(x => x.GuildConfig) @@ -298,7 +337,13 @@ public class NadekoContext : DbContext #region Perm Override - modelBuilder.Entity().HasIndex(x => new { x.GuildId, x.Command }).IsUnique(); + modelBuilder.Entity() + .HasIndex(x => new + { + x.GuildId, + x.Command + }) + .IsUnique(); #endregion @@ -329,7 +374,12 @@ public class NadekoContext : DbContext .OnDelete(DeleteBehavior.Cascade)); modelBuilder.Entity(ili => ili - .HasIndex(x => new { x.LogSettingId, x.LogItemId, x.ItemType }) + .HasIndex(x => new + { + x.LogSettingId, + x.LogItemId, + x.ItemType + }) .IsUnique()); #endregion @@ -345,8 +395,11 @@ public class NadekoContext : DbContext atch.HasMany(x => x.Users).WithOne(x => x.Channel).OnDelete(DeleteBehavior.Cascade); - modelBuilder.Entity(atu => atu.HasAlternateKey(x => new { x.ChannelId, x.UserId })); - + modelBuilder.Entity(atu => atu.HasAlternateKey(x => new + { + x.ChannelId, + x.UserId + })); } #if DEBUG diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index 359c4685a..b9ed023ed 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -314,7 +314,9 @@ public partial class Administration : NadekoModule } if (time is null) + { await msg.DeleteAsync(); + } else if (time.Time <= TimeSpan.FromDays(7)) { _ = Task.Run(async () => diff --git a/src/NadekoBot/Modules/Administration/AdministrationService.cs b/src/NadekoBot/Modules/Administration/AdministrationService.cs index 944790b8c..f56994f02 100644 --- a/src/NadekoBot/Modules/Administration/AdministrationService.cs +++ b/src/NadekoBot/Modules/Administration/AdministrationService.cs @@ -41,7 +41,7 @@ public class AdministrationService : INService private Task DelMsgOnCmd_Handler(IUserMessage msg, CommandInfo cmd) { - _= Task.Run(async () => + _ = Task.Run(async () => { if (msg.Channel is not SocketTextChannel channel) return; @@ -97,7 +97,10 @@ public class AdministrationService : INService { if (old is null) { - old = new() { ChannelId = chId }; + old = new() + { + ChannelId = chId + }; conf.DelMsgOnCmdChannels.Add(old); } @@ -126,6 +129,7 @@ public class AdministrationService : INService if (!users.Any()) return; foreach (var u in users) + { try { await u.ModifyAsync(usr => usr.Deaf = value); @@ -134,6 +138,7 @@ public class AdministrationService : INService { // ignored } + } } public async Task EditMessage( diff --git a/src/NadekoBot/Modules/Administration/AutoAssignableRoles/AutoAssignRoleService.cs b/src/NadekoBot/Modules/Administration/AutoAssignableRoles/AutoAssignRoleService.cs index 87d9cbcaf..d0d20def8 100644 --- a/src/NadekoBot/Modules/Administration/AutoAssignableRoles/AutoAssignRoleService.cs +++ b/src/NadekoBot/Modules/Administration/AutoAssignableRoles/AutoAssignRoleService.cs @@ -19,7 +19,9 @@ public sealed class AutoAssignRoleService : INService private readonly Channel _assignQueue = Channel.CreateBounded( new BoundedChannelOptions(100) { - FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true, SingleWriter = false + FullMode = BoundedChannelFullMode.DropOldest, + SingleReader = true, + SingleWriter = false }); public AutoAssignRoleService(DiscordSocketClient client, Bot bot, DbService db) @@ -118,7 +120,10 @@ public sealed class AutoAssignRoleService : INService await uow.GuildConfigs.AsNoTracking() .Where(x => x.GuildId == guildId) - .UpdateAsync(_ => new() { AutoAssignRoleIds = null }); + .UpdateAsync(_ => new() + { + AutoAssignRoleIds = null + }); _autoAssignableRoles.TryRemove(guildId, out _); diff --git a/src/NadekoBot/Modules/Administration/DangerousCommands/DangerousCommands.cs b/src/NadekoBot/Modules/Administration/DangerousCommands/DangerousCommands.cs index 3b60c7e2e..1af7d57e4 100644 --- a/src/NadekoBot/Modules/Administration/DangerousCommands/DangerousCommands.cs +++ b/src/NadekoBot/Modules/Administration/DangerousCommands/DangerousCommands.cs @@ -97,7 +97,8 @@ namespace NadekoBot.Modules.Administration var embed = _eb.Create() .WithDescription(GetText(strs.purge_user_confirm(Format.Bold(userId.ToString())))); - if (!await PromptUserConfirmAsync(embed)) return; + if (!await PromptUserConfirmAsync(embed)) + return; await _service.PurgeUserAsync(userId); await ctx.OkAsync(); diff --git a/src/NadekoBot/Modules/Administration/DangerousCommands/DangerousCommandsService.cs b/src/NadekoBot/Modules/Administration/DangerousCommands/DangerousCommandsService.cs index 61f9ba255..1baf91d1c 100644 --- a/src/NadekoBot/Modules/Administration/DangerousCommands/DangerousCommandsService.cs +++ b/src/NadekoBot/Modules/Administration/DangerousCommands/DangerousCommandsService.cs @@ -52,7 +52,11 @@ DELETE FROM Clubs;"; public SelectResult SelectSql(string sql) { - var result = new SelectResult { ColumnNames = new(), Results = new() }; + var result = new SelectResult + { + ColumnNames = new(), + Results = new() + }; using var uow = _db.GetDbContext(); var conn = uow.Database.GetDbConnection(); @@ -61,7 +65,8 @@ DELETE FROM Clubs;"; using var reader = cmd.ExecuteReader(); if (reader.HasRows) { - for (var i = 0; i < reader.FieldCount; i++) result.ColumnNames.Add(reader.GetName(i)); + for (var i = 0; i < reader.FieldCount; i++) + result.ColumnNames.Add(reader.GetName(i)); while (reader.Read()) { var obj = new object[reader.FieldCount]; @@ -93,13 +98,19 @@ DELETE FROM Clubs;"; await uow.Set() .AsQueryable() .Where(x => x.Claimer.UserId == userId) - .UpdateAsync(x => new() { ClaimerId = null }); + .UpdateAsync(x => new() + { + ClaimerId = null + }); // all affinities set to this waifu are reset await uow.Set() .AsQueryable() .Where(x => x.Affinity.UserId == userId) - .UpdateAsync(x => new() { AffinityId = null }); + .UpdateAsync(x => new() + { + AffinityId = null + }); } // delete guild xp diff --git a/src/NadekoBot/Modules/Administration/GameVoiceChannel/GameVoiceChannelService.cs b/src/NadekoBot/Modules/Administration/GameVoiceChannel/GameVoiceChannelService.cs index 198948b63..87ac222a8 100644 --- a/src/NadekoBot/Modules/Administration/GameVoiceChannel/GameVoiceChannelService.cs +++ b/src/NadekoBot/Modules/Administration/GameVoiceChannel/GameVoiceChannelService.cs @@ -26,7 +26,7 @@ public class GameVoiceChannelService : INService private Task OnPresenceUpdate(SocketUser socketUser, SocketPresence before, SocketPresence after) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -34,20 +34,18 @@ public class GameVoiceChannelService : INService return; // if the user is in the voice channel and that voice channel is gvc - if (newUser.VoiceChannel is not { } vc + if (newUser.VoiceChannel is not { } vc || !GameVoiceChannels.Contains(vc.Id)) return; - - //if the activity has changed, and is a playi1ng activity - foreach (var activity in after.Activities) - { - if (activity is { Type: ActivityType.Playing }) - { - //trigger gvc - if (await TriggerGvc(newUser, activity.Name)) - return; - } - } + + //if the activity has changed, and is a playi1ng activity + foreach (var activity in after.Activities) + { + if (activity is { Type: ActivityType.Playing }) + //trigger gvc + if (await TriggerGvc(newUser, activity.Name)) + return; + } } catch (Exception ex) { @@ -82,7 +80,7 @@ public class GameVoiceChannelService : INService private Task OnUserVoiceStateUpdated(SocketUser usr, SocketVoiceState oldState, SocketVoiceState newState) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -94,7 +92,7 @@ public class GameVoiceChannelService : INService if (!GameVoiceChannels.Contains(newState.VoiceChannel.Id)) return; - + foreach (var game in gUser.Activities.Select(x => x.Name)) { if (await TriggerGvc(gUser, game)) diff --git a/src/NadekoBot/Modules/Administration/GreetBye/GreetCommands.cs b/src/NadekoBot/Modules/Administration/GreetBye/GreetCommands.cs index cdeb3e6aa..db7ffaf4f 100644 --- a/src/NadekoBot/Modules/Administration/GreetBye/GreetCommands.cs +++ b/src/NadekoBot/Modules/Administration/GreetBye/GreetCommands.cs @@ -190,7 +190,8 @@ public partial class Administration await _service.ByeTest((ITextChannel)ctx.Channel, user); var enabled = _service.GetByeEnabled(ctx.Guild.Id); - if (!enabled) await ReplyPendingLocalizedAsync(strs.byemsg_enable($"`{prefix}bye`")); + if (!enabled) + await ReplyPendingLocalizedAsync(strs.byemsg_enable($"`{prefix}bye`")); } [Cmd] @@ -203,7 +204,8 @@ public partial class Administration await _service.GreetTest((ITextChannel)ctx.Channel, user); var enabled = _service.GetGreetEnabled(ctx.Guild.Id); - if (!enabled) await ReplyPendingLocalizedAsync(strs.greetmsg_enable($"`{prefix}greet`")); + if (!enabled) + await ReplyPendingLocalizedAsync(strs.greetmsg_enable($"`{prefix}greet`")); } [Cmd] diff --git a/src/NadekoBot/Modules/Administration/GreetBye/GreetService.cs b/src/NadekoBot/Modules/Administration/GreetBye/GreetService.cs index 6d672d334..84d7cd83c 100644 --- a/src/NadekoBot/Modules/Administration/GreetBye/GreetService.cs +++ b/src/NadekoBot/Modules/Administration/GreetBye/GreetService.cs @@ -50,7 +50,7 @@ public class GreetService : INService, IReadyExecutor await Task.Delay(2000); } } - + private Task ClientOnGuildMemberUpdated(Cacheable optOldUser, SocketGuildUser newUser) { // if user is a new booster @@ -61,7 +61,8 @@ public class GreetService : INService, IReadyExecutor && newDate > oldDate)) { var conf = GetOrAddSettingsForGuild(newUser.Guild.Id); - if (!conf.SendBoostMessage) return Task.CompletedTask; + if (!conf.SendBoostMessage) + return Task.CompletedTask; _ = Task.Run(TriggerBoostMessage(conf, newUser)); } @@ -85,7 +86,8 @@ public class GreetService : INService, IReadyExecutor try { var toDelete = await channel.SendAsync(rep.Replace(toSend)); - if (conf.BoostMessageDeleteAfter > 0) toDelete.DeleteAfter(conf.BoostMessageDeleteAfter); + if (conf.BoostMessageDeleteAfter > 0) + toDelete.DeleteAfter(conf.BoostMessageDeleteAfter); } catch (Exception ex) { @@ -107,13 +109,14 @@ public class GreetService : INService, IReadyExecutor private Task OnUserLeft(SocketGuild guild, SocketUser user) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { var conf = GetOrAddSettingsForGuild(guild.Id); - if (!conf.SendChannelByeMessage) return; + if (!conf.SendChannelByeMessage) + return; var channel = guild.TextChannels.FirstOrDefault(c => c.Id == conf.ByeMessageChannelId); if (channel is null) //maybe warn the server owner that the channel is missing @@ -187,7 +190,8 @@ public class GreetService : INService, IReadyExecutor try { var toDelete = await channel.SendAsync(text); - if (conf.AutoDeleteByeMessagesTimer > 0) toDelete.DeleteAfter(conf.AutoDeleteByeMessagesTimer); + if (conf.AutoDeleteByeMessagesTimer > 0) + toDelete.DeleteAfter(conf.AutoDeleteByeMessagesTimer); } catch (Exception ex) { @@ -214,7 +218,8 @@ public class GreetService : INService, IReadyExecutor try { var toDelete = await channel.SendAsync(text); - if (conf.AutoDeleteGreetMessagesTimer > 0) toDelete.DeleteAfter(conf.AutoDeleteGreetMessagesTimer); + if (conf.AutoDeleteGreetMessagesTimer > 0) + toDelete.DeleteAfter(conf.AutoDeleteGreetMessagesTimer); } catch (Exception ex) { @@ -229,14 +234,14 @@ public class GreetService : INService, IReadyExecutor // probably the best thing to do is to drop newest (raiding) users FullMode = BoundedChannelFullMode.DropNewest }); - + private async Task GreetDmUser(GreetSettings conf, IGuildUser user) { var completionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await _greetDmQueue.Writer.WriteAsync((conf, user, completionSource)); return await completionSource.Task; } - + private async Task GreetDmUserInternal(GreetSettings conf, IGuildUser user) { try @@ -248,15 +253,17 @@ public class GreetService : INService, IReadyExecutor var text = SmartText.CreateFrom(conf.DmGreetMessageText); text = rep.Replace(text); - + if (text is SmartPlainText pt) - { - text = new SmartEmbedText() { PlainText = pt.Text }; - } + text = new SmartEmbedText() + { + PlainText = pt.Text + }; ((SmartEmbedText)text).Footer = new() { - Text = $"This message was sent from {user.Guild} server.", IconUrl = user.Guild.IconUrl + Text = $"This message was sent from {user.Guild} server.", + IconUrl = user.Guild.IconUrl }; await user.SendAsync(text); @@ -271,7 +278,7 @@ public class GreetService : INService, IReadyExecutor private Task OnUserJoined(IGuildUser user) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -308,9 +315,7 @@ public class GreetService : INService, IReadyExecutor } if (conf.SendDmGreetMessage) - { await GreetDmUser(conf, user); - } } catch { diff --git a/src/NadekoBot/Modules/Administration/ImageOnlyChannelService.cs b/src/NadekoBot/Modules/Administration/ImageOnlyChannelService.cs index 919570a3d..6d2a2ef2c 100644 --- a/src/NadekoBot/Modules/Administration/ImageOnlyChannelService.cs +++ b/src/NadekoBot/Modules/Administration/ImageOnlyChannelService.cs @@ -18,7 +18,9 @@ public sealed class ImageOnlyChannelService : IEarlyBehavior private readonly Channel _deleteQueue = Channel.CreateBounded( new BoundedChannelOptions(100) { - FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true, SingleWriter = false + FullMode = BoundedChannelFullMode.DropOldest, + SingleReader = true, + SingleWriter = false }); @@ -78,7 +80,11 @@ public sealed class ImageOnlyChannelService : IEarlyBehavior } else { - uow.ImageOnlyChannels.Add(new() { GuildId = guildId, ChannelId = channelId }); + uow.ImageOnlyChannels.Add(new() + { + GuildId = guildId, + ChannelId = channelId + }); channels = _enabledOn.GetOrAdd(guildId, new ConcurrentHashSet()); channels.Add(channelId); diff --git a/src/NadekoBot/Modules/Administration/Mute/MuteService.cs b/src/NadekoBot/Modules/Administration/Mute/MuteService.cs index 73bfb3623..22bf52940 100644 --- a/src/NadekoBot/Modules/Administration/Mute/MuteService.cs +++ b/src/NadekoBot/Modules/Administration/Mute/MuteService.cs @@ -127,13 +127,13 @@ public class MuteService : INService if (string.IsNullOrWhiteSpace(reason)) return; - _= Task.Run(() => user.SendMessageAsync(embed: _eb.Create() - .WithDescription( - $"You've been muted in {user.Guild} server") - .AddField("Mute Type", type.ToString()) - .AddField("Moderator", mod.ToString()) - .AddField("Reason", reason) - .Build())); + _ = Task.Run(() => user.SendMessageAsync(embed: _eb.Create() + .WithDescription( + $"You've been muted in {user.Guild} server") + .AddField("Mute Type", type.ToString()) + .AddField("Moderator", mod.ToString()) + .AddField("Reason", reason) + .Build())); } private void OnUserUnmuted( @@ -145,13 +145,13 @@ public class MuteService : INService if (string.IsNullOrWhiteSpace(reason)) return; - _= Task.Run(() => user.SendMessageAsync(embed: _eb.Create() - .WithDescription( - $"You've been unmuted in {user.Guild} server") - .AddField("Unmute Type", type.ToString()) - .AddField("Moderator", mod.ToString()) - .AddField("Reason", reason) - .Build())); + _ = Task.Run(() => user.SendMessageAsync(embed: _eb.Create() + .WithDescription( + $"You've been unmuted in {user.Guild} server") + .AddField("Unmute Type", type.ToString()) + .AddField("Moderator", mod.ToString()) + .AddField("Reason", reason) + .Build())); } private Task Client_UserJoined(IGuildUser usr) @@ -162,7 +162,7 @@ public class MuteService : INService if (muted is null || !muted.Contains(usr.Id)) return Task.CompletedTask; - _= Task.Run(() => MuteUser(usr, _client.CurrentUser, reason: "Sticky mute")); + _ = Task.Run(() => MuteUser(usr, _client.CurrentUser, reason: "Sticky mute")); } catch (Exception ex) { @@ -200,7 +200,10 @@ public class MuteService : INService { var config = uow.GuildConfigsForId(usr.Guild.Id, set => set.Include(gc => gc.MutedUsers).Include(gc => gc.UnmuteTimers)); - config.MutedUsers.Add(new() { UserId = usr.Id }); + config.MutedUsers.Add(new() + { + UserId = usr.Id + }); if (MutedUsers.TryGetValue(usr.Guild.Id, out var muted)) muted.Add(usr.Id); @@ -242,9 +245,13 @@ public class MuteService : INService { var config = uow.GuildConfigsForId(guildId, set => set.Include(gc => gc.MutedUsers).Include(gc => gc.UnmuteTimers)); - var match = new MutedUserId { UserId = usrId }; + var match = new MutedUserId + { + UserId = usrId + }; var toRemove = config.MutedUsers.FirstOrDefault(x => x.Equals(match)); - if (toRemove is not null) uow.Remove(toRemove); + if (toRemove is not null) + uow.Remove(toRemove); if (MutedUsers.TryGetValue(guildId, out var muted)) muted.TryRemove(usrId); @@ -308,6 +315,7 @@ public class MuteService : INService } foreach (var toOverwrite in await guild.GetTextChannelsAsync()) + { try { if (!toOverwrite.PermissionOverwrites.Any(x => x.TargetId == muteRole.Id @@ -322,6 +330,7 @@ public class MuteService : INService { // ignored } + } return muteRole; } @@ -339,7 +348,8 @@ public class MuteService : INService var config = uow.GuildConfigsForId(user.GuildId, set => set.Include(x => x.UnmuteTimers)); config.UnmuteTimers.Add(new() { - UserId = user.Id, UnmuteAt = DateTime.UtcNow + after + UserId = user.Id, + UnmuteAt = DateTime.UtcNow + after }); // add teh unmute timer to the database uow.SaveChanges(); } @@ -359,7 +369,8 @@ public class MuteService : INService var config = uow.GuildConfigsForId(guild.Id, set => set.Include(x => x.UnbanTimer)); config.UnbanTimer.Add(new() { - UserId = user.Id, UnbanAt = DateTime.UtcNow + after + UserId = user.Id, + UnbanAt = DateTime.UtcNow + after }); // add teh unmute timer to the database uow.SaveChanges(); } @@ -379,7 +390,9 @@ public class MuteService : INService var config = uow.GuildConfigsForId(user.GuildId, set => set.Include(x => x.UnroleTimer)); config.UnroleTimer.Add(new() { - UserId = user.Id, UnbanAt = DateTime.UtcNow + after, RoleId = role.Id + UserId = user.Id, + UnbanAt = DateTime.UtcNow + after, + RoleId = role.Id }); // add teh unmute timer to the database uow.SaveChanges(); } @@ -401,26 +414,24 @@ public class MuteService : INService var toAdd = new Timer(async _ => { if (type == TimerType.Ban) - { try { RemoveTimerFromDb(guildId, userId, type); StopTimer(guildId, userId, type); var guild = _client.GetGuild(guildId); // load the guild - if (guild is not null) await guild.RemoveBanAsync(userId); + if (guild is not null) + await guild.RemoveBanAsync(userId); } catch (Exception ex) { Log.Warning(ex, "Couldn't unban user {UserId} in guild {GuildId}", userId, guildId); } - } else if (type == TimerType.AddRole) - { try { if (roleId is null) return; - + RemoveTimerFromDb(guildId, userId, type); StopTimer(guildId, userId, type); var guild = _client.GetGuild(guildId); @@ -433,9 +444,7 @@ public class MuteService : INService { Log.Warning(ex, "Couldn't remove role from user {UserId} in guild {GuildId}", userId, guildId); } - } else - { try { // unmute the user, this will also remove the timer from the db @@ -446,7 +455,6 @@ public class MuteService : INService RemoveTimerFromDb(guildId, userId, type); // if unmute errored, just remove unmute from db Log.Warning(ex, "Couldn't unmute user {UserId} in guild {GuildId}", userId, guildId); } - } }, null, after, @@ -467,7 +475,8 @@ public class MuteService : INService if (!UnTimers.TryGetValue(guildId, out var userTimer)) return; - if (userTimer.TryRemove((userId, type), out var removed)) removed.Change(Timeout.Infinite, Timeout.Infinite); + if (userTimer.TryRemove((userId, type), out var removed)) + removed.Change(Timeout.Infinite, Timeout.Infinite); } private void RemoveTimerFromDb(ulong guildId, ulong userId, TimerType type) @@ -485,7 +494,8 @@ public class MuteService : INService toDelete = config.UnbanTimer.FirstOrDefault(x => x.UserId == userId); } - if (toDelete is not null) uow.Remove(toDelete); + if (toDelete is not null) + uow.Remove(toDelete); uow.SaveChanges(); } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Administration/PermOverrides/DiscordPermOverrideCommands.cs b/src/NadekoBot/Modules/Administration/PermOverrides/DiscordPermOverrideCommands.cs index 7e1b7ecfa..0460d4eb5 100644 --- a/src/NadekoBot/Modules/Administration/PermOverrides/DiscordPermOverrideCommands.cs +++ b/src/NadekoBot/Modules/Administration/PermOverrides/DiscordPermOverrideCommands.cs @@ -41,7 +41,7 @@ public partial class Administration if (!result) return; - + await _service.ClearAllOverrides(ctx.Guild.Id); await ReplyConfirmLocalizedAsync(strs.perm_override_all); diff --git a/src/NadekoBot/Modules/Administration/PermOverrides/DiscordPermOverrideService.cs b/src/NadekoBot/Modules/Administration/PermOverrides/DiscordPermOverrideService.cs index 5cd349339..b48a6ee26 100644 --- a/src/NadekoBot/Modules/Administration/PermOverrides/DiscordPermOverrideService.cs +++ b/src/NadekoBot/Modules/Administration/PermOverrides/DiscordPermOverrideService.cs @@ -56,7 +56,13 @@ public class DiscordPermOverrideService : INService, ILateBlocker .FirstOrDefaultAsync(x => x.GuildId == guildId && commandName == x.Command); if (over is null) - uow.Set().Add(over = new() { Command = commandName, Perm = perm, GuildId = guildId }); + uow.Set() + .Add(over = new() + { + Command = commandName, + Perm = perm, + GuildId = guildId + }); else over.Perm = perm; @@ -77,7 +83,8 @@ public class DiscordPermOverrideService : INService, ILateBlocker uow.RemoveRange(overrides); await uow.SaveChangesAsync(); - foreach (var over in overrides) _overrides.TryRemove((guildId, over.Command), out _); + foreach (var over in overrides) + _overrides.TryRemove((guildId, over.Command), out _); } public async Task RemoveOverride(ulong guildId, string commandName) diff --git a/src/NadekoBot/Modules/Administration/PlayingRotate/PlayingRotateService.cs b/src/NadekoBot/Modules/Administration/PlayingRotate/PlayingRotateService.cs index ec10f28cc..db40f679e 100644 --- a/src/NadekoBot/Modules/Administration/PlayingRotate/PlayingRotateService.cs +++ b/src/NadekoBot/Modules/Administration/PlayingRotate/PlayingRotateService.cs @@ -24,9 +24,7 @@ public sealed class PlayingRotateService : INService, IReadyExecutor _selfService = selfService; if (client.ShardId == 0) - { _rep = new ReplacementBuilder().WithClient(client).WithProviders(phProviders).Build(); - } } public async Task OnReadyAsync() @@ -37,7 +35,7 @@ public sealed class PlayingRotateService : INService, IReadyExecutor { try { - if (!_bss.Data.RotateStatuses) + if (!_bss.Data.RotateStatuses) continue; IReadOnlyList rotatingStatuses; @@ -82,7 +80,11 @@ public sealed class PlayingRotateService : INService, IReadyExecutor public async Task AddPlaying(ActivityType t, string status) { await using var uow = _db.GetDbContext(); - var toAdd = new RotatingPlayingStatus { Status = status, Type = t }; + var toAdd = new RotatingPlayingStatus + { + Status = status, + Type = t + }; uow.Add(toAdd); await uow.SaveChangesAsync(); } diff --git a/src/NadekoBot/Modules/Administration/Protection/ProtectionCommands.cs b/src/NadekoBot/Modules/Administration/Protection/ProtectionCommands.cs index ed9c1892d..04523c2a8 100644 --- a/src/NadekoBot/Modules/Administration/Protection/ProtectionCommands.cs +++ b/src/NadekoBot/Modules/Administration/Protection/ProtectionCommands.cs @@ -27,7 +27,10 @@ public partial class Administration [Cmd] [RequireContext(ContextType.Guild)] [UserPerm(GuildPerm.Administrator)] - public async partial Task AntiAlt(StoopidTime minAge, PunishmentAction action, [Leftover] StoopidTime punishTime = null) + public async partial Task AntiAlt( + StoopidTime minAge, + PunishmentAction action, + [Leftover] StoopidTime punishTime = null) { var minAgeMinutes = (int)minAge.Time.TotalMinutes; var punishTimeMinutes = (int?)punishTime?.Time.TotalMinutes ?? 0; @@ -120,7 +123,8 @@ public partial class Administration var stats = await _service.StartAntiRaidAsync(ctx.Guild.Id, userThreshold, seconds, action, time); - if (stats is null) return; + if (stats is null) + return; await SendConfirmAsync(GetText(strs.prot_enable("Anti-Raid")), $"{ctx.User.Mention} {GetAntiRaidString(stats)}"); @@ -244,7 +248,8 @@ public partial class Administration ignoredString = "none"; var add = string.Empty; - if (settings.MuteTime > 0) add = $" ({TimeSpan.FromMinutes(settings.MuteTime):hh\\hmm\\m})"; + if (settings.MuteTime > 0) + add = $" ({TimeSpan.FromMinutes(settings.MuteTime):hh\\hmm\\m})"; return GetText(strs.spam_stats(Format.Bold(settings.MessageThreshold.ToString()), Format.Bold(settings.Action + add), diff --git a/src/NadekoBot/Modules/Administration/Protection/ProtectionService.cs b/src/NadekoBot/Modules/Administration/Protection/ProtectionService.cs index 7cac8182e..36063f6f7 100644 --- a/src/NadekoBot/Modules/Administration/Protection/ProtectionService.cs +++ b/src/NadekoBot/Modules/Administration/Protection/ProtectionService.cs @@ -25,7 +25,11 @@ public class ProtectionService : INService private readonly UserPunishService _punishService; private readonly Channel _punishUserQueue = - Channel.CreateUnbounded(new() { SingleReader = true, SingleWriter = false }); + Channel.CreateUnbounded(new() + { + SingleReader = true, + SingleWriter = false + }); public ProtectionService( DiscordSocketClient client, @@ -51,7 +55,8 @@ public class ProtectionService : INService .Where(x => ids.Contains(x.GuildId)) .ToList(); - foreach (var gc in configs) Initialize(gc); + foreach (var gc in configs) + Initialize(gc); } _client.MessageReceived += HandleAntiSpam; @@ -94,7 +99,7 @@ public class ProtectionService : INService private Task _client_LeftGuild(SocketGuild guild) { - _= Task.Run(async () => + _ = Task.Run(async () => { TryStopAntiRaid(guild.Id); TryStopAntiSpam(guild.Id); @@ -123,12 +128,18 @@ public class ProtectionService : INService if (raid is not null) { - var raidStats = new AntiRaidStats { AntiRaidSettings = raid }; + var raidStats = new AntiRaidStats + { + AntiRaidSettings = raid + }; _antiRaidGuilds[gc.GuildId] = raidStats; } if (spam is not null) - _antiSpamGuilds[gc.GuildId] = new() { AntiSpamSettings = spam }; + _antiSpamGuilds[gc.GuildId] = new() + { + AntiSpamSettings = spam + }; var alt = gc.AntiAltSetting; if (alt is not null) @@ -202,12 +213,16 @@ public class ProtectionService : INService if (msg.Channel is not ITextChannel channel) return Task.CompletedTask; - _= Task.Run(async () => + + _ = Task.Run(async () => { try { if (!_antiSpamGuilds.TryGetValue(channel.Guild.Id, out var spamSettings) - || spamSettings.AntiSpamSettings.IgnoredChannels.Contains(new() { ChannelId = channel.Id })) + || spamSettings.AntiSpamSettings.IgnoredChannels.Contains(new() + { + ChannelId = channel.Id + })) return; var stats = spamSettings.UserStats.AddOrUpdate(msg.Author.Id, @@ -251,6 +266,7 @@ public class ProtectionService : INService gus[0].Guild.Name); foreach (var gu in gus) + { await _punishUserQueue.Writer.WriteAsync(new() { Action = action, @@ -259,6 +275,7 @@ public class ProtectionService : INService MuteTime = muteTime, RoleId = roleId }); + } _ = OnAntiProtectionTriggered(action, pt, gus); } @@ -385,18 +402,23 @@ public class ProtectionService : INService public async Task AntiSpamIgnoreAsync(ulong guildId, ulong channelId) { - var obj = new AntiSpamIgnore { ChannelId = channelId }; + var obj = new AntiSpamIgnore + { + ChannelId = channelId + }; bool added; await using var uow = _db.GetDbContext(); var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting).ThenInclude(x => x.IgnoredChannels)); var spam = gc.AntiSpamSetting; - if (spam is null) return null; + if (spam is null) + return null; if (spam.IgnoredChannels.Add(obj)) // if adding to db is successful { if (_antiSpamGuilds.TryGetValue(guildId, out var temp)) temp.AntiSpamSettings.IgnoredChannels.Add(obj); // add to local cache + added = true; } else @@ -405,6 +427,7 @@ public class ProtectionService : INService uow.Set().Remove(toRemove); // remove from db if (_antiSpamGuilds.TryGetValue(guildId, out var temp)) temp.AntiSpamSettings.IgnoredChannels.Remove(toRemove); // remove from local cache + added = false; } diff --git a/src/NadekoBot/Modules/Administration/Protection/UserSpamStats.cs b/src/NadekoBot/Modules/Administration/Protection/UserSpamStats.cs index b3e5b86d1..234ba1175 100644 --- a/src/NadekoBot/Modules/Administration/Protection/UserSpamStats.cs +++ b/src/NadekoBot/Modules/Administration/Protection/UserSpamStats.cs @@ -10,7 +10,7 @@ public sealed class UserSpamStats lock (_applyLock) { Cleanup(); - Log.Information("{Count}",_messageTracker.Count.ToString()); + Log.Information("{Count}", _messageTracker.Count.ToString()); return _messageTracker.Count; } } diff --git a/src/NadekoBot/Modules/Administration/Role/RoleCommands.cs b/src/NadekoBot/Modules/Administration/Role/RoleCommands.cs index 74fe8ed2b..b2d36858c 100644 --- a/src/NadekoBot/Modules/Administration/Role/RoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/Role/RoleCommands.cs @@ -40,13 +40,18 @@ public partial class Administration } var role = (IRole)roleResult.BestMatch; - if (role.Position > ((IGuildUser)ctx.User).GetRoles() - .Select(r => r.Position) - .Max() + if (role.Position + > ((IGuildUser)ctx.User).GetRoles() + .Select(r => r.Position) + .Max() && ctx.User.Id != ctx.Guild.OwnerId) return null; var emote = x.Last().ToIEmote(); - return new { role, emote }; + return new + { + role, + emote + }; }) .Where(x => x is not null) .WhenAll(); @@ -59,7 +64,10 @@ public partial class Administration try { await target.AddReactionAsync(x.emote, - new() { RetryMode = RetryMode.Retry502 | RetryMode.RetryRatelimit }); + new() + { + RetryMode = RetryMode.Retry502 | RetryMode.RetryRatelimit + }); } catch (HttpException ex) when (ex.HttpCode == HttpStatusCode.BadRequest) { @@ -79,9 +87,10 @@ public partial class Administration ReactionRoles = all.Select(x => { return new ReactionRole - { - EmoteName = x.emote.ToString(), RoleId = x.role.Id - }; + { + EmoteName = x.emote.ToString(), + RoleId = x.role.Id + }; }) .ToList() })) @@ -144,7 +153,8 @@ public partial class Administration { var ch = g.GetTextChannel(rr.ChannelId); IUserMessage msg = null; - if (ch is not null) msg = await ch.GetMessageAsync(rr.MessageId) as IUserMessage; + if (ch is not null) + msg = await ch.GetMessageAsync(rr.MessageId) as IUserMessage; var content = msg?.Content.TrimTo(30) ?? "DELETED!"; embed.AddField($"**{rr.Index + 1}.** {ch?.Name ?? "DELETED!"}", GetText(strs.reaction_roles_message(rr.ReactionRoles?.Count ?? 0, content))); diff --git a/src/NadekoBot/Modules/Administration/Role/RoleCommandsService.cs b/src/NadekoBot/Modules/Administration/Role/RoleCommandsService.cs index 597f7d8f0..a2052c3d6 100644 --- a/src/NadekoBot/Modules/Administration/Role/RoleCommandsService.cs +++ b/src/NadekoBot/Modules/Administration/Role/RoleCommandsService.cs @@ -89,7 +89,10 @@ public class RoleCommandsService : INService var dl = await msg.GetOrDownloadAsync(); await dl.RemoveReactionAsync(reaction.Emote, dl.Author, - new() { RetryMode = RetryMode.RetryRatelimit | RetryMode.Retry502 }); + new() + { + RetryMode = RetryMode.RetryRatelimit | RetryMode.Retry502 + }); Log.Warning("User {Author} is adding unrelated reactions to the reaction roles message", dl.Author); } }); diff --git a/src/NadekoBot/Modules/Administration/Self/SelfCommands.cs b/src/NadekoBot/Modules/Administration/Self/SelfCommands.cs index 1a3c3f7b1..7c20d37c1 100644 --- a/src/NadekoBot/Modules/Administration/Self/SelfCommands.cs +++ b/src/NadekoBot/Modules/Administration/Self/SelfCommands.cs @@ -304,7 +304,7 @@ public partial class Administration var toLeave = _client.Guilds .Where(s => s.MemberCount == 1 && s.Users.Count == 1) .ToList(); - + foreach (var server in toLeave) { try @@ -425,7 +425,8 @@ public partial class Administration { var success = await _service.SetAvatar(img); - if (success) await ReplyConfirmLocalizedAsync(strs.set_avatar); + if (success) + await ReplyConfirmLocalizedAsync(strs.set_avatar); } [Cmd] diff --git a/src/NadekoBot/Modules/Administration/Self/SelfService.cs b/src/NadekoBot/Modules/Administration/Self/SelfService.cs index d138a3936..ef32ee82b 100644 --- a/src/NadekoBot/Modules/Administration/Self/SelfService.cs +++ b/src/NadekoBot/Modules/Administration/Self/SelfService.cs @@ -59,7 +59,8 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService HandleStatusChanges(); - if (_client.ShardId == 0) _pubSub.Sub(_imagesReloadKey, async _ => await _imgs.Reload()); + if (_client.ShardId == 0) + _pubSub.Sub(_imagesReloadKey, async _ => await _imgs.Reload()); _pubSub.Sub(_guildLeaveKey, async input => @@ -70,7 +71,8 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService var server = _client.Guilds.FirstOrDefault(g => g.Id.ToString() == guildStr || g.Name.Trim().ToUpperInvariant() == guildStr); - if (server is null) return; + if (server is null) + return; if (server.OwnerId != _client.CurrentUser.Id) { @@ -90,15 +92,16 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService await using var uow = _db.GetDbContext(); autoCommands = uow.AutoCommands.AsNoTracking() - .Where(x => x.Interval >= 5) - .AsEnumerable() - .GroupBy(x => x.GuildId) - .ToDictionary(x => x.Key, - y => y.ToDictionary(x => x.Id, TimerFromAutoCommand).ToConcurrent()) - .ToConcurrent(); + .Where(x => x.Interval >= 5) + .AsEnumerable() + .GroupBy(x => x.GuildId) + .ToDictionary(x => x.Key, + y => y.ToDictionary(x => x.Id, TimerFromAutoCommand).ToConcurrent()) + .ToConcurrent(); var startupCommands = uow.AutoCommands.AsNoTracking().Where(x => x.Interval == 0); foreach (var cmd in startupCommands) + { try { await ExecuteCommand(cmd); @@ -106,8 +109,10 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService catch { } + } - if (_client.ShardId == 0) await LoadOwnerChannels(); + if (_client.ShardId == 0) + await LoadOwnerChannels(); } private Timer TimerFromAutoCommand(AutoCommand x) @@ -171,13 +176,14 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService private async Task LoadOwnerChannels() { var channels = await _creds.OwnerIds.Select(id => - { - var user = _client.GetUser(id); - if (user is null) - return Task.FromResult(null); + { + var user = _client.GetUser(id); + if (user is null) + return Task.FromResult(null); - return user.CreateDMChannelAsync(); - }).WhenAll(); + return user.CreateDMChannelAsync(); + }) + .WhenAll(); ownerChannels = channels.Where(x => x is not null) .ToDictionary(x => x.Recipient.Id, x => x) @@ -187,7 +193,9 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService Log.Warning( "No owner channels created! Make sure you've specified the correct OwnerId in the creds.yml file and invited the bot to a Discord server"); else - Log.Information("Created {OwnerChannelCount} out of {TotalOwnerChannelCount} owner message channels", ownerChannels.Count, _creds.OwnerIds.Count); + Log.Information("Created {OwnerChannelCount} out of {TotalOwnerChannelCount} owner message channels", + ownerChannels.Count, + _creds.OwnerIds.Count); } public Task LeaveGuild(string guildStr) @@ -214,6 +222,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService var allOwnerChannels = ownerChannels.Values; foreach (var ownerCh in allOwnerChannels.Where(ch => ch.Recipient.Id != msg.Author.Id)) + { try { await ownerCh.SendConfirmAsync(_eb, title, toSend); @@ -222,6 +231,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService { Log.Warning("Can't contact owner with id {OwnerId}", ownerCh.Recipient.Id); } + } } else { @@ -337,10 +347,22 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService }); public Task SetGameAsync(string game, ActivityType type) - => _pubSub.Pub(_activitySetKey, new() { Name = game, Link = null, Type = type }); + => _pubSub.Pub(_activitySetKey, + new() + { + Name = game, + Link = null, + Type = type + }); public Task SetStreamAsync(string name, string link) - => _pubSub.Pub(_activitySetKey, new() { Name = name, Link = link, Type = ActivityType.Streaming }); + => _pubSub.Pub(_activitySetKey, + new() + { + Name = name, + Link = link, + Type = ActivityType.Streaming + }); private sealed class ActivityPubData { diff --git a/src/NadekoBot/Modules/Administration/SelfAssignableRoles/SelfAssignedRolesCommands.cs b/src/NadekoBot/Modules/Administration/SelfAssignableRoles/SelfAssignedRolesCommands.cs index a42a3fc7d..aabeb7ecd 100644 --- a/src/NadekoBot/Modules/Administration/SelfAssignableRoles/SelfAssignedRolesCommands.cs +++ b/src/NadekoBot/Modules/Administration/SelfAssignableRoles/SelfAssignedRolesCommands.cs @@ -112,6 +112,7 @@ public partial class Administration rolesStr.AppendLine("\t\t\t\t ⟪" + groupNameText + "⟫"); foreach (var (model, role) in kvp.AsEnumerable()) + { if (role is null) { } @@ -123,6 +124,7 @@ public partial class Administration else rolesStr.AppendLine("‌‌ " + role.Name + $" (lvl {model.LevelRequirement}+)"); } + } rolesStr.AppendLine(); } diff --git a/src/NadekoBot/Modules/Administration/SelfAssignableRoles/SelfAssignedRolesService.cs b/src/NadekoBot/Modules/Administration/SelfAssignableRoles/SelfAssignedRolesService.cs index bd72cf3b4..609cf640a 100644 --- a/src/NadekoBot/Modules/Administration/SelfAssignableRoles/SelfAssignedRolesService.cs +++ b/src/NadekoBot/Modules/Administration/SelfAssignableRoles/SelfAssignedRolesService.cs @@ -34,9 +34,15 @@ public class SelfAssignedRolesService : INService { using var uow = _db.GetDbContext(); var roles = uow.SelfAssignableRoles.GetFromGuild(guildId); - if (roles.Any(s => s.RoleId == role.Id && s.GuildId == role.Guild.Id)) return false; + if (roles.Any(s => s.RoleId == role.Id && s.GuildId == role.Guild.Id)) + return false; - uow.SelfAssignableRoles.Add(new() { Group = group, RoleId = role.Id, GuildId = role.Guild.Id }); + uow.SelfAssignableRoles.Add(new() + { + Group = group, + RoleId = role.Id, + GuildId = role.Guild.Id + }); uow.SaveChanges(); return true; } @@ -67,7 +73,8 @@ public class SelfAssignedRolesService : INService return (AssignResult.ErrNotAssignable, autoDelete, null); if (theRoleYouWant.LevelRequirement > userLevelData.Level) return (AssignResult.ErrLvlReq, autoDelete, theRoleYouWant.LevelRequirement); - if (guildUser.RoleIds.Contains(role.Id)) return (AssignResult.ErrAlreadyHave, autoDelete, null); + if (guildUser.RoleIds.Contains(role.Id)) + return (AssignResult.ErrAlreadyHave, autoDelete, null); var roleIds = roles.Where(x => x.Group == theRoleYouWant.Group).Select(x => x.RoleId).ToArray(); if (exclusive) @@ -116,7 +123,11 @@ public class SelfAssignedRolesService : INService } else if (toUpdate is null) { - gc.SelfAssignableRoleGroupNames.Add(new() { Name = name, Number = group }); + gc.SelfAssignableRoleGroupNames.Add(new() + { + Name = name, + Number = group + }); set = true; } else @@ -136,7 +147,8 @@ public class SelfAssignedRolesService : INService if (roles.FirstOrDefault(r => r.RoleId == role.Id) is null) return (RemoveResult.ErrNotAssignable, autoDelete); - if (!guildUser.RoleIds.Contains(role.Id)) return (RemoveResult.ErrNotHave, autoDelete); + if (!guildUser.RoleIds.Contains(role.Id)) + return (RemoveResult.ErrNotHave, autoDelete); try { await guildUser.RemoveRoleAsync(role); @@ -198,7 +210,8 @@ public class SelfAssignedRolesService : INService return areExclusive; } - public (bool Exclusive, IReadOnlyCollection<(SelfAssignedRole Model, IRole Role)> Roles, IDictionary GroupNames + public (bool Exclusive, IReadOnlyCollection<(SelfAssignedRole Model, IRole Role)> Roles, IDictionary + GroupNames ) GetRoles(IGuild guild) { var exclusive = false; diff --git a/src/NadekoBot/Modules/Administration/ServerLog/ServerLogCommandService.cs b/src/NadekoBot/Modules/Administration/ServerLog/ServerLogCommandService.cs index a3eeb1060..4e076e57c 100644 --- a/src/NadekoBot/Modules/Administration/ServerLog/ServerLogCommandService.cs +++ b/src/NadekoBot/Modules/Administration/ServerLog/ServerLogCommandService.cs @@ -138,7 +138,11 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor if (removed == 0) { - var toAdd = new IgnoredLogItem { LogItemId = itemId, ItemType = itemType }; + var toAdd = new IgnoredLogItem + { + LogItemId = itemId, + ItemType = itemType + }; logSetting.LogIgnores.Add(toAdd); } @@ -183,7 +187,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_UserUpdated(SocketUser before, SocketUser uAfter) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -306,7 +310,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_UserVoiceStateUpdated_TTS(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -351,7 +355,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor IUser mod, MuteType muteType, string reason) - => _= Task.Run(async () => + => _ = Task.Run(async () => { try { @@ -396,7 +400,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor IUser mod, MuteType muteType, string reason) - => _= Task.Run(async () => + => _ = Task.Run(async () => { try { @@ -443,7 +447,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor public Task TriggeredAntiProtection(PunishmentAction action, ProtectionType protection, params IGuildUser[] users) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -453,7 +457,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor if (!GuildLogSettings.TryGetValue(users.First().Guild.Id, out var logSetting) || logSetting.LogOtherId is null) return; - + ITextChannel? logChannel; if ((logChannel = await TryGetLogChannel(users.First().Guild, logSetting, LogType.Other)) is null) return; @@ -513,7 +517,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_GuildUserUpdated(Cacheable optBefore, SocketGuildUser after) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -575,7 +579,8 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor if (!before.IsBot && logSetting.LogUserPresenceId is not null - && (logChannel = await TryGetLogChannel(before.Guild, logSetting, LogType.UserPresence)) is not null) + && (logChannel = + await TryGetLogChannel(before.Guild, logSetting, LogType.UserPresence)) is not null) { if (before.Status != after.Status) { @@ -585,7 +590,10 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor strs.user_status_change("👤" + Format.Bold(after.Username), Format.Bold(after.Status.ToString()))); PresenceUpdates.AddOrUpdate(logChannel, - new List { str }, + new List + { + str + }, (_, list) => { list.Add(str); @@ -597,7 +605,10 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor var str = $"👾`{PrettyCurrentTime(after.Guild)}`👤__**{after.Username}**__ is now playing **{after.Activities.FirstOrDefault()?.Name ?? "-"}**."; PresenceUpdates.AddOrUpdate(logChannel, - new List { str }, + new List + { + str + }, (_, list) => { list.Add(str); @@ -616,7 +627,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_ChannelUpdated(IChannel cbefore, IChannel cafter) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -664,7 +675,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_ChannelDestroyed(IChannel ich) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -702,7 +713,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_ChannelCreated(IChannel ich) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -738,7 +749,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -784,7 +795,10 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor if (!string.IsNullOrWhiteSpace(str)) PresenceUpdates.AddOrUpdate(logChannel, - new List { str }, + new List + { + str + }, (_, list) => { list.Add(str); @@ -801,7 +815,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_UserLeft(SocketGuild guild, SocketUser usr) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -836,7 +850,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_UserJoined(IGuildUser usr) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -875,7 +889,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_UserUnbanned(IUser usr, IGuild guild) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -910,7 +924,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_UserBanned(IUser usr, IGuild guild) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -947,7 +961,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor private Task _client_MessageDeleted(Cacheable optMsg, Cacheable optCh) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -1001,7 +1015,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor SocketMessage imsg2, ISocketMessageChannel ch) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { diff --git a/src/NadekoBot/Modules/Administration/UserPunish/UserPunishCommands.cs b/src/NadekoBot/Modules/Administration/UserPunish/UserPunishCommands.cs index b5c56b8f7..b9c92e1eb 100644 --- a/src/NadekoBot/Modules/Administration/UserPunish/UserPunishCommands.cs +++ b/src/NadekoBot/Modules/Administration/UserPunish/UserPunishCommands.cs @@ -89,7 +89,8 @@ public partial class Administration Log.Warning(ex, "Exception occured while warning a user"); var errorEmbed = _eb.Create().WithErrorColor().WithDescription(GetText(strs.cant_apply_punishment)); - if (dmFailed) errorEmbed.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); + if (dmFailed) + errorEmbed.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); await ctx.Channel.EmbedAsync(errorEmbed); return; @@ -102,7 +103,8 @@ public partial class Administration embed.WithDescription(GetText(strs.user_warned_and_punished(Format.Bold(user.ToString()), Format.Bold(punishment.Punishment.ToString())))); - if (dmFailed) embed.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); + if (dmFailed) + embed.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); await ctx.Channel.EmbedAsync(embed); } @@ -359,7 +361,8 @@ public partial class Administration [UserPerm(GuildPerm.BanMembers)] public async partial Task WarnPunish(int number) { - if (!_service.WarnPunishRemove(ctx.Guild.Id, number)) return; + if (!_service.WarnPunishRemove(ctx.Guild.Id, number)) + return; await ReplyConfirmLocalizedAsync(strs.warn_punish_rem(Format.Bold(number.ToString()))); } @@ -402,7 +405,8 @@ public partial class Administration { var defaultMessage = GetText(strs.bandm(Format.Bold(ctx.Guild.Name), msg)); var embed = _service.GetBanUserDmEmbed(Context, guildUser, defaultMessage, msg, time.Time); - if (embed is not null) await guildUser.SendAsync(embed); + if (embed is not null) + await guildUser.SendAsync(embed); } catch { @@ -419,7 +423,8 @@ public partial class Administration time.Time.Humanize(3, minUnit: TimeUnit.Minute, culture: Culture), true); - if (dmFailed) toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); + if (dmFailed) + toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); await ctx.Channel.EmbedAsync(toSend); } @@ -463,7 +468,8 @@ public partial class Administration { var defaultMessage = GetText(strs.bandm(Format.Bold(ctx.Guild.Name), msg)); var embed = _service.GetBanUserDmEmbed(Context, user, defaultMessage, msg, null); - if (embed is not null) await ctx.User.SendAsync(embed); + if (embed is not null) + await ctx.User.SendAsync(embed); } catch { @@ -478,7 +484,8 @@ public partial class Administration .AddField(GetText(strs.username), user.ToString(), true) .AddField("ID", user.Id.ToString(), true); - if (dmFailed) toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); + if (dmFailed) + toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); await ctx.Channel.EmbedAsync(toSend); } @@ -648,7 +655,8 @@ public partial class Administration .AddField(GetText(strs.username), user.ToString(), true) .AddField("ID", user.Id.ToString(), true); - if (dmFailed) toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); + if (dmFailed) + toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); await ctx.Channel.EmbedAsync(toSend); } @@ -699,7 +707,8 @@ public partial class Administration .AddField(GetText(strs.username), user.ToString(), true) .AddField("ID", user.Id.ToString(), true); - if (dmFailed) toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); + if (dmFailed) + toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user)); await ctx.Channel.EmbedAsync(toSend); } @@ -719,6 +728,7 @@ public partial class Administration await ctx.Channel.TriggerTypingAsync(); foreach (var userStr in userStrings) + { if (ulong.TryParse(userStr, out var userId)) { IUser user = await ctx.Guild.GetUserAsync(userId) @@ -739,7 +749,8 @@ public partial class Administration } //Hierachy checks only if the user is in the guild - if (user is IGuildUser gu && !await CheckRoleHierarchy(gu)) return; + if (user is IGuildUser gu && !await CheckRoleHierarchy(gu)) + return; banning.Add(user); } @@ -747,6 +758,7 @@ public partial class Administration { missing.Add(userStr); } + } var missStr = string.Join("\n", missing); if (string.IsNullOrWhiteSpace(missStr)) @@ -760,6 +772,7 @@ public partial class Administration var banningMessage = await ctx.Channel.EmbedAsync(toSend); foreach (var toBan in banning) + { try { await ctx.Guild.AddBanAsync(toBan.Id, 7, $"{ctx.User} | Massban"); @@ -768,6 +781,7 @@ public partial class Administration { Log.Warning(ex, "Error banning {User} user in {GuildId} server", toBan.Id, ctx.Guild.Id); } + } await banningMessage.ModifyAsync(x => x.Embed = _eb.Create() .WithDescription( @@ -805,7 +819,10 @@ public partial class Administration .Select(x => ctx.Guild.AddBanAsync(x.Id.Value, 7, x.Reason, - new() { RetryMode = RetryMode.AlwaysRetry }))); + new() + { + RetryMode = RetryMode.AlwaysRetry + }))); //wait for the message and edit it var banningMessage = await banningMessageTask; diff --git a/src/NadekoBot/Modules/Administration/UserPunish/UserPunishService.cs b/src/NadekoBot/Modules/Administration/UserPunish/UserPunishService.cs index 87e1f4fb4..b8c308c28 100644 --- a/src/NadekoBot/Modules/Administration/UserPunish/UserPunishService.cs +++ b/src/NadekoBot/Modules/Administration/UserPunish/UserPunishService.cs @@ -30,12 +30,12 @@ public class UserPunishService : INService, IReadyExecutor _bcs = bcs; _client = client; } - + public async Task OnReadyAsync() { if (_client.ShardId != 0) return; - + var expiryTimer = new PeriodicTimer(TimeSpan.FromHours(12)); do { @@ -429,7 +429,11 @@ WHERE GuildId={guildId} } else if (template is null) { - uow.BanTemplates.Add(new() { GuildId = guildId, Text = text }); + uow.BanTemplates.Add(new() + { + GuildId = guildId, + Text = text + }); } else { @@ -485,7 +489,8 @@ WHERE GuildId={guildId} if (string.IsNullOrWhiteSpace(template)) template = JsonConvert.SerializeObject(new { - color = _bcs.Data.Color.Error.PackedValue >> 8, description = defaultMessage + color = _bcs.Data.Color.Error.PackedValue >> 8, + description = defaultMessage }); // if template is set to "-" do not dm the user else if (template == "-") @@ -495,7 +500,8 @@ WHERE GuildId={guildId} else if (!SmartText.CreateFrom(template).IsEmbed) template = JsonConvert.SerializeObject(new { - color = _bcs.Data.Color.Error.PackedValue >> 8, description = template + color = _bcs.Data.Color.Error.PackedValue >> 8, + description = template }); var output = SmartText.CreateFrom(template); diff --git a/src/NadekoBot/Modules/Administration/VcRole/VcRoleService.cs b/src/NadekoBot/Modules/Administration/VcRole/VcRoleService.cs index 9404bef22..9b4b3feed 100644 --- a/src/NadekoBot/Modules/Administration/VcRole/VcRoleService.cs +++ b/src/NadekoBot/Modules/Administration/VcRole/VcRoleService.cs @@ -49,11 +49,13 @@ public class VcRoleService : INService { if (add) { - if (!user.RoleIds.Contains(role.Id)) await user.AddRoleAsync(role); + if (!user.RoleIds.Contains(role.Id)) + await user.AddRoleAsync(role); } else { - if (user.RoleIds.Contains(role.Id)) await user.RemoveRoleAsync(role); + if (user.RoleIds.Contains(role.Id)) + await user.RemoveRoleAsync(role); } } catch @@ -80,7 +82,7 @@ public class VcRoleService : INService using (var uow = _db.GetDbContext()) { var configWithVcRole = uow.GuildConfigsForId(arg.GuildId, set => set.Include(x => x.VcRoleInfos)); - _= InitializeVcRole(configWithVcRole); + _ = InitializeVcRole(configWithVcRole); } return Task.CompletedTask; @@ -137,8 +139,13 @@ public class VcRoleService : INService using var uow = _db.GetDbContext(); var conf = uow.GuildConfigsForId(guildId, set => set.Include(x => x.VcRoleInfos)); var toDelete = conf.VcRoleInfos.FirstOrDefault(x => x.VoiceChannelId == vcId); // remove old one - if (toDelete is not null) uow.Remove(toDelete); - conf.VcRoleInfos.Add(new() { VoiceChannelId = vcId, RoleId = role.Id }); // add new one + if (toDelete is not null) + uow.Remove(toDelete); + conf.VcRoleInfos.Add(new() + { + VoiceChannelId = vcId, + RoleId = role.Id + }); // add new one uow.SaveChanges(); } @@ -166,7 +173,7 @@ public class VcRoleService : INService var oldVc = oldState.VoiceChannel; var newVc = newState.VoiceChannel; - _= Task.Run(() => + _ = Task.Run(() => { try { @@ -181,7 +188,8 @@ public class VcRoleService : INService if (oldVc is not null && guildVcRoles.TryGetValue(oldVc.Id, out var role)) Assign(false, gusr, role); //add new - if (newVc is not null && guildVcRoles.TryGetValue(newVc.Id, out role)) Assign(true, gusr, role); + if (newVc is not null && guildVcRoles.TryGetValue(newVc.Id, out role)) + Assign(true, gusr, role); } } } diff --git a/src/NadekoBot/Modules/CustomReactions/NadekoExpressions.cs b/src/NadekoBot/Modules/CustomReactions/NadekoExpressions.cs index cf1d2301d..3461c7bf8 100644 --- a/src/NadekoBot/Modules/CustomReactions/NadekoExpressions.cs +++ b/src/NadekoBot/Modules/CustomReactions/NadekoExpressions.cs @@ -92,16 +92,16 @@ public partial class NadekoExpressions : NadekoModule curPage => { var desc = expressions.OrderBy(ex => ex.Trigger) - .Skip(curPage * 20) - .Take(20) - .Select(ex => $"{(ex.ContainsAnywhere ? "🗯" : "◾")}" - + $"{(ex.DmResponse ? "✉" : "◾")}" - + $"{(ex.AutoDeleteTrigger ? "❌" : "◾")}" - + $"`{(kwum)ex.Id}` {ex.Trigger}" - + (string.IsNullOrWhiteSpace(ex.Reactions) - ? string.Empty - : " // " + string.Join(" ", ex.GetReactions()))) - .Join('\n'); + .Skip(curPage * 20) + .Take(20) + .Select(ex => $"{(ex.ContainsAnywhere ? "🗯" : "◾")}" + + $"{(ex.DmResponse ? "✉" : "◾")}" + + $"{(ex.AutoDeleteTrigger ? "❌" : "◾")}" + + $"`{(kwum)ex.Id}` {ex.Trigger}" + + (string.IsNullOrWhiteSpace(ex.Reactions) + ? string.Empty + : " // " + string.Join(" ", ex.GetReactions()))) + .Join('\n'); return _eb.Create().WithOkColor().WithTitle(GetText(strs.custom_reactions)).WithDescription(desc); }, diff --git a/src/NadekoBot/Modules/CustomReactions/NadekoExpressionsService.cs b/src/NadekoBot/Modules/CustomReactions/NadekoExpressionsService.cs index 426f4b266..55bfb87c2 100644 --- a/src/NadekoBot/Modules/CustomReactions/NadekoExpressionsService.cs +++ b/src/NadekoBot/Modules/CustomReactions/NadekoExpressionsService.cs @@ -113,14 +113,14 @@ public sealed class NadekoExpressionsService : IEarlyBehavior, IReadyExecutor .ToListAsync(); newGuildReactions = guildItems.GroupBy(k => k.GuildId!.Value) - .ToDictionary(g => g.Key, - g => g.Select(x => - { - x.Trigger = x.Trigger.Replace(MENTION_PH, _bot.Mention); - return x; - }) - .ToArray()) - .ToConcurrent(); + .ToDictionary(g => g.Key, + g => g.Select(x => + { + x.Trigger = x.Trigger.Replace(MENTION_PH, _bot.Mention); + return x; + }) + .ToArray()) + .ToConcurrent(); lock (_gexprWriteLock) { @@ -180,7 +180,8 @@ public sealed class NadekoExpressionsService : IEarlyBehavior, IReadyExecutor var wp = content.GetWordPosition(trigger); // if it is, then that's valid - if (wp != WordPosition.None) result.Add(expr); + if (wp != WordPosition.None) + result.Add(expr); // if it's not, then it cant' work under any circumstance, // because content is greater than the trigger length @@ -204,7 +205,8 @@ public sealed class NadekoExpressionsService : IEarlyBehavior, IReadyExecutor { // if input length is the same as trigger length // reaction can only trigger if the strings are equal - if (content.SequenceEqual(expr.Trigger)) result.Add(expr); + if (content.SequenceEqual(expr.Trigger)) + result.Add(expr); } } @@ -345,8 +347,11 @@ public sealed class NadekoExpressionsService : IEarlyBehavior, IReadyExecutor { var newArray = old.ToArray(); for (var i = 0; i < newArray.Length; i++) + { if (newArray[i].Id == expr.Id) newArray[i] = expr; + } + return newArray; }); else @@ -354,8 +359,10 @@ public sealed class NadekoExpressionsService : IEarlyBehavior, IReadyExecutor { var exprs = globalReactions; for (var i = 0; i < exprs.Length; i++) + { if (exprs[i].Id == expr.Id) exprs[i] = expr; + } } } @@ -386,7 +393,8 @@ public sealed class NadekoExpressionsService : IEarlyBehavior, IReadyExecutor lock (_gexprWriteLock) { var expr = Array.Find(globalReactions, item => item.Id == id); - if (expr is not null) return _pubSub.Pub(_gexprDeletedkey, expr.Id); + if (expr is not null) + return _pubSub.Pub(_gexprDeletedkey, expr.Id); } return Task.CompletedTask; @@ -516,17 +524,17 @@ public sealed class NadekoExpressionsService : IEarlyBehavior, IReadyExecutor { var trigger = entry.Key; await uow.Expressions.AddRangeAsync(entry.Value.Where(expr => !string.IsNullOrWhiteSpace(expr.Res)) - .Select(expr => new NadekoExpression - { - GuildId = guildId, - Response = expr.Res, - Reactions = expr.React?.Join("@@@"), - Trigger = trigger, - AllowTarget = expr.At, - ContainsAnywhere = expr.Ca, - DmResponse = expr.Dm, - AutoDeleteTrigger = expr.Ad - })); + .Select(expr => new NadekoExpression + { + GuildId = guildId, + Response = expr.Res, + Reactions = expr.React?.Join("@@@"), + Trigger = trigger, + AllowTarget = expr.At, + ContainsAnywhere = expr.Ca, + DmResponse = expr.Dm, + AutoDeleteTrigger = expr.Ad + })); } await uow.SaveChangesAsync(); @@ -560,11 +568,13 @@ public sealed class NadekoExpressionsService : IEarlyBehavior, IReadyExecutor lock (_gexprWriteLock) { for (var i = 0; i < globalReactions.Length; i++) + { if (globalReactions[i].Id == c.Id) { globalReactions[i] = c; return default; } + } // if edited expr is not found?! // add it @@ -614,7 +624,12 @@ public sealed class NadekoExpressionsService : IEarlyBehavior, IReadyExecutor public async Task AddAsync(ulong? guildId, string key, string message) { key = key.ToLowerInvariant(); - var expr = new NadekoExpression { GuildId = guildId, Trigger = key, Response = message }; + var expr = new NadekoExpression + { + GuildId = guildId, + Trigger = key, + Response = message + }; if (expr.Response.Contains("%target%", StringComparison.OrdinalIgnoreCase)) expr.AllowTarget = true; diff --git a/src/NadekoBot/Modules/Gambling/AnimalRacing/AnimalRace.cs b/src/NadekoBot/Modules/Gambling/AnimalRacing/AnimalRace.cs index b888843e9..10f1ebcf7 100644 --- a/src/NadekoBot/Modules/Gambling/AnimalRacing/AnimalRace.cs +++ b/src/NadekoBot/Modules/Gambling/AnimalRacing/AnimalRace.cs @@ -99,8 +99,10 @@ public sealed class AnimalRace : IDisposable if (_users.Count <= 1) { foreach (var user in _users) + { if (user.Bet > 0) await _currency.AddAsync(user.UserId, user.Bet, new("animalrace", "refund")); + } _ = OnStartingFailed?.Invoke(this); CurrentPhase = Phase.Ended; diff --git a/src/NadekoBot/Modules/Gambling/AnimalRacing/AnimalRacingCommands.cs b/src/NadekoBot/Modules/Gambling/AnimalRacing/AnimalRacingCommands.cs index f4b75e2df..7fe0bad52 100644 --- a/src/NadekoBot/Modules/Gambling/AnimalRacing/AnimalRacingCommands.cs +++ b/src/NadekoBot/Modules/Gambling/AnimalRacing/AnimalRacingCommands.cs @@ -48,7 +48,7 @@ public partial class Gambling Task ClientMessageReceived(SocketMessage arg) { - _= Task.Run(() => + _ = Task.Run(() => { try { diff --git a/src/NadekoBot/Modules/Gambling/BlackJack/BlackJackCommands.cs b/src/NadekoBot/Modules/Gambling/BlackJack/BlackJackCommands.cs index 925a9785e..1dda8914a 100644 --- a/src/NadekoBot/Modules/Gambling/BlackJack/BlackJackCommands.cs +++ b/src/NadekoBot/Modules/Gambling/BlackJack/BlackJackCommands.cs @@ -75,9 +75,7 @@ public partial class Gambling try { if (msg is not null) - { - _= msg.DeleteAsync(); - } + _ = msg.DeleteAsync(); var c = bj.Dealer.Cards.Select(x => x.GetEmojiString()) .ToList(); @@ -99,7 +97,8 @@ public partial class Gambling .WithTitle("BlackJack") .AddField($"{dealerIcon} Dealer's Hand | Value: {bj.Dealer.GetHandValue()}", cStr); - if (bj.CurrentUser is not null) embed.WithFooter($"Player to make a choice: {bj.CurrentUser.DiscordUser}"); + if (bj.CurrentUser is not null) + embed.WithFooter($"Player to make a choice: {bj.CurrentUser.DiscordUser}"); foreach (var p in bj.Players) { diff --git a/src/NadekoBot/Modules/Gambling/BlackJack/Blackjack.cs b/src/NadekoBot/Modules/Gambling/BlackJack/Blackjack.cs index 9a45e6da7..a60ae1b1e 100644 --- a/src/NadekoBot/Modules/Gambling/BlackJack/Blackjack.cs +++ b/src/NadekoBot/Modules/Gambling/BlackJack/Blackjack.cs @@ -33,7 +33,7 @@ public class Blackjack } public void Start() - => _= GameLoop(); + => _ = GameLoop(); public async Task GameLoop() { @@ -73,11 +73,13 @@ public class Blackjack //go through all users and ask them what they want to do foreach (var usr in Players.Where(x => !x.Done)) + { while (!usr.Done) { Log.Information("Waiting for {DiscordUser}'s move", usr.DiscordUser); await PromptUserMove(usr); } + } await PrintState(); State = GameState.Ended; @@ -85,13 +87,13 @@ public class Blackjack Log.Information("Dealer moves"); await DealerMoves(); await PrintState(); - _= GameEnded?.Invoke(this); + _ = GameEnded?.Invoke(this); } catch (Exception ex) { Log.Error(ex, "REPORT THE MESSAGE BELOW IN #NadekoLog SERVER PLEASE"); State = GameState.Ended; - _= GameEnded?.Invoke(this); + _ = GameEnded?.Invoke(this); } } @@ -106,14 +108,10 @@ public class Blackjack // if he doesn't - stand var finished = await Task.WhenAny(pause, currentUserMove.Task); if (finished == pause) - { await Stand(usr); - } else - { cts.Cancel(); - } - + CurrentUser = null; currentUserMove = null; } @@ -129,10 +127,11 @@ public class Blackjack if (Players.Count >= 5) return false; - if (!await _cs.RemoveAsync(user, bet, new("blackjack","gamble"))) return false; + if (!await _cs.RemoveAsync(user, bet, new("blackjack", "gamble"))) + return false; Players.Add(new(user, bet)); - _= PrintState(); + _ = PrintState(); return true; } finally @@ -204,22 +203,28 @@ public class Blackjack if (hw > 21) foreach (var usr in Players) + { if (usr.State is User.UserState.Stand or User.UserState.Blackjack) usr.State = User.UserState.Won; else usr.State = User.UserState.Lost; + } else foreach (var usr in Players) + { if (usr.State == User.UserState.Blackjack) usr.State = User.UserState.Won; else if (usr.State == User.UserState.Stand) usr.State = hw < usr.GetHandValue() ? User.UserState.Won : User.UserState.Lost; else usr.State = User.UserState.Lost; + } foreach (var usr in Players) + { if (usr.State is User.UserState.Won or User.UserState.Blackjack) await _cs.AddAsync(usr.DiscordUser.Id, usr.Bet * 2, new("blackjack", "win")); + } } public async Task Double(IUser u) diff --git a/src/NadekoBot/Modules/Gambling/BlackJack/Player.cs b/src/NadekoBot/Modules/Gambling/BlackJack/Player.cs index 60f3e407f..c1d1a3ba3 100644 --- a/src/NadekoBot/Modules/Gambling/BlackJack/Player.cs +++ b/src/NadekoBot/Modules/Gambling/BlackJack/Player.cs @@ -13,7 +13,8 @@ public abstract class Player // reduce the value by 10 until it drops below 22 // (emulating the fact that ace is either a 1 or a 11) var i = Cards.Count(x => x.Number == 1); - while (val > 21 && i-- > 0) val -= 10; + while (val > 21 && i-- > 0) + val -= 10; return val; } diff --git a/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs b/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs index a3de6a7dc..14da475d3 100644 --- a/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs +++ b/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs @@ -81,14 +81,15 @@ public sealed class Connect4Game : IDisposable _cs = cs; _rng = new(); - for (var i = 0; i < NUMBER_OF_COLUMNS * NUMBER_OF_ROWS; i++) _gameState[i] = Field.Empty; + for (var i = 0; i < NUMBER_OF_COLUMNS * NUMBER_OF_ROWS; i++) + _gameState[i] = Field.Empty; } public void Initialize() { if (CurrentPhase != Phase.Joining) return; - _= Task.Run(async () => + _ = Task.Run(async () => { await Task.Delay(15000); await _locker.WaitAsync(); @@ -173,11 +174,13 @@ public sealed class Connect4Game : IDisposable var start = NUMBER_OF_ROWS * inputCol; for (var i = start; i < start + NUMBER_OF_ROWS; i++) + { if (_gameState[i] == Field.Empty) { _gameState[i] = GetPlayerPiece(userId); break; } + } //check winnning condition // ok, i'll go from [0-2] in rows (and through all columns) and check upward if 4 are connected @@ -233,7 +236,8 @@ public sealed class Connect4Game : IDisposable EndGame(Result.CurrentPlayerWon, CurrentPlayer.UserId); else continue; - else break; + else + break; } } } @@ -271,7 +275,8 @@ public sealed class Connect4Game : IDisposable var cur = _gameState[curRow + (curCol * NUMBER_OF_ROWS)]; if (cur == first) same++; - else break; + else + break; } if (same == 4) @@ -298,7 +303,8 @@ public sealed class Connect4Game : IDisposable var cur = _gameState[curRow + (curCol * NUMBER_OF_ROWS)]; if (cur == first) same++; - else break; + else + break; } if (same == 4) @@ -311,7 +317,8 @@ public sealed class Connect4Game : IDisposable } //check draw? if it's even possible - if (_gameState.All(x => x != Field.Empty)) EndGame(Result.Draw, null); + if (_gameState.All(x => x != Field.Empty)) + EndGame(Result.Draw, null); if (CurrentPhase != Phase.Ended) { @@ -323,7 +330,7 @@ public sealed class Connect4Game : IDisposable ResetTimer(); } - _= OnGameStateUpdated?.Invoke(this); + _ = OnGameStateUpdated?.Invoke(this); return true; } finally { _locker.Release(); } @@ -337,7 +344,7 @@ public sealed class Connect4Game : IDisposable { if (CurrentPhase == Phase.Ended) return; - _= OnGameEnded?.Invoke(this, result); + _ = OnGameEnded?.Invoke(this, result); CurrentPhase = Phase.Ended; if (result == Result.Draw) @@ -359,8 +366,11 @@ public sealed class Connect4Game : IDisposable { var start = NUMBER_OF_ROWS * column; for (var i = start; i < start + NUMBER_OF_ROWS; i++) + { if (_gameState[i] == Field.Empty) return false; + } + return true; } diff --git a/src/NadekoBot/Modules/Gambling/Connect4/Connect4Commands.cs b/src/NadekoBot/Modules/Gambling/Connect4/Connect4Commands.cs index ef85cf8c1..55fca4cfd 100644 --- a/src/NadekoBot/Modules/Gambling/Connect4/Connect4Commands.cs +++ b/src/NadekoBot/Modules/Gambling/Connect4/Connect4Commands.cs @@ -23,7 +23,8 @@ public partial class Gambling { if (value is < 0 or > 7) repostCounter = 0; - else repostCounter = value; + else + repostCounter = value; } } @@ -88,10 +89,11 @@ public partial class Gambling if (ctx.Channel.Id != arg.Channel.Id) return Task.CompletedTask; - _= Task.Run(async () => + _ = Task.Run(async () => { var success = false; - if (int.TryParse(arg.Content, out var col)) success = await game.Input(arg.Author.Id, col); + if (int.TryParse(arg.Content, out var col)) + success = await game.Input(arg.Author.Id, col); if (success) { @@ -100,7 +102,8 @@ public partial class Gambling } else { - if (game.CurrentPhase is Connect4Game.Phase.Joining or Connect4Game.Phase.Ended) return; + if (game.CurrentPhase is Connect4Game.Phase.Joining or Connect4Game.Phase.Ended) + return; RepostCounter++; if (RepostCounter == 0) try { msg = await ctx.Channel.SendMessageAsync("", embed: (Embed)msg.Embeds.First()); } @@ -185,7 +188,8 @@ public partial class Gambling sb.AppendLine(); } - for (var i = 0; i < Connect4Game.NUMBER_OF_COLUMNS; i++) sb.Append(_numbers[i]); + for (var i = 0; i < Connect4Game.NUMBER_OF_COLUMNS; i++) + sb.Append(_numbers[i]); return sb.ToString(); } } diff --git a/src/NadekoBot/Modules/Gambling/DiceRoll/DiceRollCommands.cs b/src/NadekoBot/Modules/Gambling/DiceRoll/DiceRollCommands.cs index 20805ea65..e03a37dc8 100644 --- a/src/NadekoBot/Modules/Gambling/DiceRoll/DiceRollCommands.cs +++ b/src/NadekoBot/Modules/Gambling/DiceRoll/DiceRollCommands.cs @@ -83,11 +83,13 @@ public partial class Gambling toInsert = 0; else if (randomNumber != 1) for (var j = 0; j < dice.Count; j++) + { if (values[j] < randomNumber) { toInsert = j; break; } + } } else { @@ -100,7 +102,8 @@ public partial class Gambling using var bitmap = dice.Merge(out var format); await using var ms = bitmap.ToStream(format); - foreach (var d in dice) d.Dispose(); + foreach (var d in dice) + d.Dispose(); await ctx.Channel.SendFileAsync(ms, $"dice.{format.FileExtensions.First()}", @@ -123,7 +126,8 @@ public partial class Gambling var rolls = new List(); - for (var i = 0; i < n1; i++) rolls.Add(_fateRolls[rng.Next(0, _fateRolls.Length)]); + for (var i = 0; i < n1; i++) + rolls.Add(_fateRolls[rng.Next(0, _fateRolls.Length)]); var embed = _eb.Create() .WithOkColor() .WithDescription(ctx.User.Mention @@ -150,7 +154,8 @@ public partial class Gambling sub = 0; var arr = new int[n1]; - for (var i = 0; i < n1; i++) arr[i] = rng.Next(1, n2 + 1); + for (var i = 0; i < n1; i++) + arr[i] = rng.Next(1, n2 + 1); var sum = arr.Sum(); var embed = _eb.Create() diff --git a/src/NadekoBot/Modules/Gambling/Draw/DrawCommands.cs b/src/NadekoBot/Modules/Gambling/Draw/DrawCommands.cs index 9f49dee14..4214af0a1 100644 --- a/src/NadekoBot/Modules/Gambling/Draw/DrawCommands.cs +++ b/src/NadekoBot/Modules/Gambling/Draw/DrawCommands.cs @@ -47,7 +47,8 @@ public partial class Gambling } using var img = images.Merge(); - foreach (var i in images) i.Dispose(); + foreach (var i in images) + i.Dispose(); var toSend = $"{Format.Bold(ctx.User.ToString())}"; if (cardObjects.Count == 5) diff --git a/src/NadekoBot/Modules/Gambling/Events/GameStatusEvent.cs b/src/NadekoBot/Modules/Gambling/Events/GameStatusEvent.cs index f60914a55..8abaa7e09 100644 --- a/src/NadekoBot/Modules/Gambling/Events/GameStatusEvent.cs +++ b/src/NadekoBot/Modules/Gambling/Events/GameStatusEvent.cs @@ -68,7 +68,8 @@ public class GameStatusEvent : ICurrencyEvent { var potEmpty = PotEmptied; var toAward = new List(); - while (_toAward.TryDequeue(out var x)) toAward.Add(x); + while (_toAward.TryDequeue(out var x)) + toAward.Add(x); if (!toAward.Any()) return; @@ -85,7 +86,10 @@ public class GameStatusEvent : ICurrencyEvent { m.Embed = GetEmbed(PotSize).Build(); }, - new() { RetryMode = RetryMode.AlwaysRetry }); + new() + { + RetryMode = RetryMode.AlwaysRetry + }); Log.Information("Awarded {Count} users {Amount} currency.{Remaining}", toAward.Count, @@ -93,9 +97,7 @@ public class GameStatusEvent : ICurrencyEvent _isPotLimited ? $" {PotSize} left." : ""); if (potEmpty) - { - _= StopEvent(); - } + _ = StopEvent(); } catch (Exception ex) { @@ -117,7 +119,8 @@ public class GameStatusEvent : ICurrencyEvent private async Task OnMessageDeleted(Cacheable message, Cacheable cacheable) { - if (message.Id == msg.Id) await StopEvent(); + if (message.Id == msg.Id) + await StopEvent(); } public async Task StopEvent() @@ -135,7 +138,7 @@ public class GameStatusEvent : ICurrencyEvent _ = _client.SetGameAsync(null); try { - _= msg.DeleteAsync(); + _ = msg.DeleteAsync(); } catch { } @@ -145,7 +148,7 @@ public class GameStatusEvent : ICurrencyEvent private Task HandleMessage(SocketMessage message) { - _= Task.Run(async () => + _ = Task.Run(async () => { if (message.Author is not IGuildUser gu // no unknown users, as they could be bots, or alts || gu.IsBot // no bots @@ -163,7 +166,10 @@ public class GameStatusEvent : ICurrencyEvent try { - await message.DeleteAsync(new() { RetryMode = RetryMode.AlwaysFail }); + await message.DeleteAsync(new() + { + RetryMode = RetryMode.AlwaysFail + }); } catch { } }); diff --git a/src/NadekoBot/Modules/Gambling/Events/ReactionEvent.cs b/src/NadekoBot/Modules/Gambling/Events/ReactionEvent.cs index de22a8185..0618e0a2f 100644 --- a/src/NadekoBot/Modules/Gambling/Events/ReactionEvent.cs +++ b/src/NadekoBot/Modules/Gambling/Events/ReactionEvent.cs @@ -58,13 +58,14 @@ public class ReactionEvent : ICurrencyEvent } private void EventTimeout(object state) - => _= StopEvent(); + => _ = StopEvent(); private async void OnTimerTick(object state) { var potEmpty = PotEmptied; var toAward = new List(); - while (_toAward.TryDequeue(out var x)) toAward.Add(x); + while (_toAward.TryDequeue(out var x)) + toAward.Add(x); if (!toAward.Any()) return; @@ -78,7 +79,10 @@ public class ReactionEvent : ICurrencyEvent { m.Embed = GetEmbed(PotSize).Build(); }, - new() { RetryMode = RetryMode.AlwaysRetry }); + new() + { + RetryMode = RetryMode.AlwaysRetry + }); Log.Information("Awarded {Count} users {Amount} currency.{Remaining}", toAward.Count, @@ -86,9 +90,7 @@ public class ReactionEvent : ICurrencyEvent _isPotLimited ? $" {PotSize} left." : ""); if (potEmpty) - { - _= StopEvent(); - } + _ = StopEvent(); } catch (Exception ex) { @@ -114,7 +116,8 @@ public class ReactionEvent : ICurrencyEvent private async Task OnMessageDeleted(Cacheable message, Cacheable cacheable) { - if (message.Id == msg.Id) await StopEvent(); + if (message.Id == msg.Id) + await StopEvent(); } public async Task StopEvent() @@ -131,7 +134,7 @@ public class ReactionEvent : ICurrencyEvent _timeout?.Change(Timeout.Infinite, Timeout.Infinite); try { - _= msg.DeleteAsync(); + _ = msg.DeleteAsync(); } catch { } @@ -144,7 +147,7 @@ public class ReactionEvent : ICurrencyEvent Cacheable cacheable, SocketReaction r) { - _= Task.Run(() => + _ = Task.Run(() => { if (emote.Name != r.Emote.Name) return; diff --git a/src/NadekoBot/Modules/Gambling/FlipCoin/FlipCoinCommands.cs b/src/NadekoBot/Modules/Gambling/FlipCoin/FlipCoinCommands.cs index b1a2286ae..9d449b7c0 100644 --- a/src/NadekoBot/Modules/Gambling/FlipCoin/FlipCoinCommands.cs +++ b/src/NadekoBot/Modules/Gambling/FlipCoin/FlipCoinCommands.cs @@ -63,7 +63,8 @@ public partial class Gambling using var img = imgs.Merge(out var format); await using var stream = img.ToStream(format); - foreach (var i in imgs) i.Dispose(); + foreach (var i in imgs) + i.Dispose(); var msg = count != 1 ? Format.Bold(ctx.User.ToString()) + " " + GetText(strs.flip_results(count, headCount, tailCount)) : Format.Bold(ctx.User.ToString()) diff --git a/src/NadekoBot/Modules/Gambling/Gambling.cs b/src/NadekoBot/Modules/Gambling/Gambling.cs index aadaec64a..d34b6294b 100644 --- a/src/NadekoBot/Modules/Gambling/Gambling.cs +++ b/src/NadekoBot/Modules/Gambling/Gambling.cs @@ -86,11 +86,11 @@ public partial class Gambling : GamblingModule { var ec = _service.GetEconomy(); decimal onePercent = 0; - + // This stops the top 1% from owning more than 100% of the money if (ec.Cash > 0) onePercent = ec.OnePercent / (ec.Cash - ec.Bot); - + // [21:03] Bob Page: Kinda remids me of US economy var embed = _eb.Create() .WithTitle(GetText(strs.economy_state)) @@ -103,7 +103,7 @@ public partial class Gambling : GamblingModule .AddField(GetText(strs.total), ((BigInteger)(ec.Cash + ec.Planted + ec.Waifus)).ToString("N", Culture) + CurrencySign) .WithOkColor(); - + // ec.Cash already contains ec.Bot as it's the total of all values in the CurrencyAmount column of the DiscordUser table await ctx.Channel.EmbedAsync(embed); } @@ -165,7 +165,8 @@ public partial class Gambling : GamblingModule var members = (await role.GetMembersAsync()).Where(u => u.Status != UserStatus.Offline); var membersArray = members as IUser[] ?? members.ToArray(); - if (membersArray.Length == 0) return; + if (membersArray.Length == 0) + return; var usr = membersArray[new NadekoRandom().Next(0, membersArray.Length)]; await SendConfirmAsync("🎟 " + GetText(strs.raffled_user), $"**{usr.Username}#{usr.Discriminator}**", @@ -180,7 +181,8 @@ public partial class Gambling : GamblingModule var members = await role.GetMembersAsync(); var membersArray = members as IUser[] ?? members.ToArray(); - if (membersArray.Length == 0) return; + if (membersArray.Length == 0) + return; var usr = membersArray[new NadekoRandom().Next(0, membersArray.Length)]; await SendConfirmAsync("🎟 " + GetText(strs.raffled_user), $"**{usr.Username}#{usr.Discriminator}**", @@ -228,13 +230,13 @@ public partial class Gambling : GamblingModule var change = tr.Amount >= 0 ? "🔵" : "🔴"; var kwumId = new kwum(tr.Id).ToString(); var date = $"#{Format.Code(kwumId)} `〖{GetFormattedCurtrDate(tr)}〗`"; - - + + sb.AppendLine($"\\{change} {date} {Format.Bold(N(tr.Amount))}"); var transactionString = GetHumanReadableTransaction(tr.Type, tr.Extra, tr.OtherId); - if(transactionString is not null) + if (transactionString is not null) sb.AppendLine(transactionString); - + if (!string.IsNullOrWhiteSpace(tr.Note)) sb.AppendLine($"\t`Note:` {tr.Note.TrimTo(50)}"); } @@ -265,7 +267,7 @@ public partial class Gambling : GamblingModule } var eb = _eb.Create(ctx) - .WithOkColor(); + .WithOkColor(); eb.WithAuthor(ctx.User); eb.WithTitle(GetText(strs.transaction)); @@ -273,16 +275,16 @@ public partial class Gambling : GamblingModule eb.AddField("Amount", N(tr.Amount)); eb.AddField("Type", tr.Type, true); eb.AddField("Extra", tr.Extra, true); - + if (tr.OtherId is ulong other) eb.AddField("From Id", other); - + if (!string.IsNullOrWhiteSpace(tr.Note)) eb.AddField("Note", tr.Note); eb.WithFooter(GetFormattedCurtrDate(tr)); - + await ctx.Channel.EmbedAsync(eb); } @@ -325,7 +327,7 @@ public partial class Gambling : GamblingModule { if (amount <= 0 || ctx.User.Id == receiver.Id || receiver.IsBot) return; - + if (!await _cs.TransferAsync(ctx.User.Id, receiver.Id, amount, ctx.User.ToString(), msg)) { await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign)); @@ -373,7 +375,7 @@ public partial class Gambling : GamblingModule await _cs.AddAsync(usr.Id, amount, - new TxData("award", ctx.User.ToString()!, msg, ctx.User.Id) + new("award", ctx.User.ToString()!, msg, ctx.User.Id) ); await ReplyConfirmLocalizedAsync(strs.awarded(N(amount), $"<@{usrId}>")); } @@ -431,7 +433,7 @@ public partial class Gambling : GamblingModule ctx.User.ToString()!, null, ctx.User.Id); - + if (await _cs.RemoveAsync(user.Id, amount, extra)) await ReplyConfirmLocalizedAsync(strs.take(N(amount), Format.Bold(user.ToString()))); else @@ -450,7 +452,7 @@ public partial class Gambling : GamblingModule ctx.User.ToString()!, null, ctx.User.Id); - + if (await _cs.RemoveAsync(usrId, amount, extra)) await ReplyConfirmLocalizedAsync(strs.take(N(amount), $"<@{usrId}>")); else @@ -689,7 +691,6 @@ public partial class Gambling : GamblingModule var nadekoPick = (RpsPick)new NadekoRandom().Next(0, 3); if (amount > 0) - { if (!await _cs.RemoveAsync(ctx.User.Id, amount, new("rps", "bet", ""))) @@ -697,7 +698,6 @@ public partial class Gambling : GamblingModule await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign)); return; } - } string msg; if (pick == nadekoPick) diff --git a/src/NadekoBot/Modules/Gambling/GamblingConfig.cs b/src/NadekoBot/Modules/Gambling/GamblingConfig.cs index b897bf223..91ad79a5a 100644 --- a/src/NadekoBot/Modules/Gambling/GamblingConfig.cs +++ b/src/NadekoBot/Modules/Gambling/GamblingConfig.cs @@ -109,8 +109,21 @@ Doesn't have to be ordered.")] public BetRollConfig() => Pairs = new BetRollPair[] { - new() { WhenAbove = 99, MultiplyBy = 10 }, new() { WhenAbove = 90, MultiplyBy = 4 }, - new() { WhenAbove = 66, MultiplyBy = 2 } + new() + { + WhenAbove = 99, + MultiplyBy = 10 + }, + new() + { + WhenAbove = 90, + MultiplyBy = 4 + }, + new() + { + WhenAbove = 66, + MultiplyBy = 2 + } }; } diff --git a/src/NadekoBot/Modules/Gambling/GamblingConfigService.cs b/src/NadekoBot/Modules/Gambling/GamblingConfigService.cs index feb40e454..c7d403ce6 100644 --- a/src/NadekoBot/Modules/Gambling/GamblingConfigService.cs +++ b/src/NadekoBot/Modules/Gambling/GamblingConfigService.cs @@ -8,6 +8,7 @@ public sealed class GamblingConfigService : ConfigServiceBase { private const string FILE_PATH = "data/gambling.yml"; private static readonly TypedKey _changeKey = new("config.gambling.updated"); + public override string Name => "gambling"; diff --git a/src/NadekoBot/Modules/Gambling/GamblingService.cs b/src/NadekoBot/Modules/Gambling/GamblingService.cs index 7054fc81c..85a82d306 100644 --- a/src/NadekoBot/Modules/Gambling/GamblingService.cs +++ b/src/NadekoBot/Modules/Gambling/GamblingService.cs @@ -86,7 +86,10 @@ WHERE CurrencyAmount > {config.Decay.MinThreshold} AND UserId!={_client.CurrentU var takeRes = await _cs.RemoveAsync(userId, amount, new("slot", "bet")); if (!takeRes) - return new() { Error = GamblingError.NotEnough }; + return new() + { + Error = GamblingError.NotEnough + }; var game = new SlotGame(); var result = game.Spin(); @@ -99,7 +102,11 @@ WHERE CurrencyAmount > {config.Decay.MinThreshold} AND UserId!={_client.CurrentU await _cs.AddAsync(userId, won, new("slot", "win", $"Slot Machine x{result.Multiplier}")); } - var toReturn = new SlotResponse { Multiplier = result.Multiplier, Won = won }; + var toReturn = new SlotResponse + { + Multiplier = result.Multiplier, + Won = won + }; toReturn.Rolls.AddRange(result.Rolls); diff --git a/src/NadekoBot/Modules/Gambling/GamblingTopLevelModule.cs b/src/NadekoBot/Modules/Gambling/GamblingTopLevelModule.cs index f8c319748..0616282c8 100644 --- a/src/NadekoBot/Modules/Gambling/GamblingTopLevelModule.cs +++ b/src/NadekoBot/Modules/Gambling/GamblingTopLevelModule.cs @@ -21,7 +21,8 @@ public abstract class GamblingModule : NadekoModule private async Task InternalCheckBet(long amount) { - if (amount < 1) return false; + if (amount < 1) + return false; if (amount < Config.MinBet) { await ReplyErrorLocalizedAsync(strs.min_bet_limit(Format.Bold(Config.MinBet.ToString()) + CurrencySign)); @@ -39,13 +40,15 @@ public abstract class GamblingModule : NadekoModule protected Task CheckBetMandatory(long amount) { - if (amount < 1) return Task.FromResult(false); + if (amount < 1) + return Task.FromResult(false); return InternalCheckBet(amount); } protected Task CheckBetOptional(long amount) { - if (amount == 0) return Task.FromResult(true); + if (amount == 0) + return Task.FromResult(true); return InternalCheckBet(amount); } } diff --git a/src/NadekoBot/Modules/Gambling/PlantPick/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Gambling/PlantPick/PlantAndPickCommands.cs index f5e56b1bc..12e3cf106 100644 --- a/src/NadekoBot/Modules/Gambling/PlantPick/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Gambling/PlantPick/PlantAndPickCommands.cs @@ -13,13 +13,14 @@ public partial class Gambling public PlantPickCommands(ILogCommandService logService, GamblingConfigService gss) : base(gss) - => this._logService = logService; + => _logService = logService; [Cmd] [RequireContext(ContextType.Guild)] public async partial Task Pick(string pass = null) { - if (!string.IsNullOrWhiteSpace(pass) && !pass.IsAlphaNumeric()) return; + if (!string.IsNullOrWhiteSpace(pass) && !pass.IsAlphaNumeric()) + return; var picked = await _service.PickAsync(ctx.Guild.Id, (ITextChannel)ctx.Channel, ctx.User.Id, pass); @@ -45,7 +46,8 @@ public partial class Gambling if (amount < 1) return; - if (!string.IsNullOrWhiteSpace(pass) && !pass.IsAlphaNumeric()) return; + if (!string.IsNullOrWhiteSpace(pass) && !pass.IsAlphaNumeric()) + return; if (((SocketGuild)ctx.Guild).CurrentUser.GuildPermissions.ManageMessages) { @@ -59,7 +61,8 @@ public partial class Gambling ctx.User.ToString(), amount, pass); - if (!success) await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign)); + if (!success) + await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign)); } [Cmd] diff --git a/src/NadekoBot/Modules/Gambling/PlantPick/PlantPickService.cs b/src/NadekoBot/Modules/Gambling/PlantPick/PlantPickService.cs index cb0ef3d4f..5ecd56e10 100644 --- a/src/NadekoBot/Modules/Gambling/PlantPick/PlantPickService.cs +++ b/src/NadekoBot/Modules/Gambling/PlantPick/PlantPickService.cs @@ -71,7 +71,10 @@ public class PlantPickService : INService using var uow = _db.GetDbContext(); var guildConfig = uow.GuildConfigsForId(gid, set => set.Include(gc => gc.GenerateCurrencyChannelIds)); - var toAdd = new GCChannelId { ChannelId = cid }; + var toAdd = new GCChannelId + { + ChannelId = cid + }; if (!guildConfig.GenerateCurrencyChannelIds.Contains(toAdd)) { guildConfig.GenerateCurrencyChannelIds.Add(toAdd); @@ -81,7 +84,8 @@ public class PlantPickService : INService else { var toDelete = guildConfig.GenerateCurrencyChannelIds.FirstOrDefault(x => x.Equals(toAdd)); - if (toDelete is not null) uow.Remove(toDelete); + if (toDelete is not null) + uow.Remove(toDelete); _generationChannels.TryRemove(cid); enabled = false; } @@ -172,7 +176,7 @@ public class PlantPickService : INService if (!_generationChannels.Contains(channel.Id)) return Task.CompletedTask; - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -277,7 +281,7 @@ public class PlantPickService : INService try { // delete all of the plant messages which have just been picked - _= ch.DeleteMessagesAsync(ids); + _ = ch.DeleteMessagesAsync(ids); } catch { } diff --git a/src/NadekoBot/Modules/Gambling/Raffle/CurrencyRaffleGame.cs b/src/NadekoBot/Modules/Gambling/Raffle/CurrencyRaffleGame.cs index 8ba4538c5..48e239a24 100644 --- a/src/NadekoBot/Modules/Gambling/Raffle/CurrencyRaffleGame.cs +++ b/src/NadekoBot/Modules/Gambling/Raffle/CurrencyRaffleGame.cs @@ -26,7 +26,11 @@ public class CurrencyRaffleGame if (GameType == Type.Normal && _users.Count > 0 && _users.First().Amount != amount) return false; - if (!_users.Add(new() { DiscordUser = usr, Amount = amount })) + if (!_users.Add(new() + { + DiscordUser = usr, + Amount = amount + })) return false; return true; diff --git a/src/NadekoBot/Modules/Gambling/Raffle/CurrencyRaffleService.cs b/src/NadekoBot/Modules/Gambling/Raffle/CurrencyRaffleService.cs index e9f4a4646..4c7c52100 100644 --- a/src/NadekoBot/Modules/Gambling/Raffle/CurrencyRaffleService.cs +++ b/src/NadekoBot/Modules/Gambling/Raffle/CurrencyRaffleService.cs @@ -52,7 +52,6 @@ public class CurrencyRaffleService : INService } if (newGame) - { _ = Task.Run(async () => { await Task.Delay(60000); @@ -69,7 +68,6 @@ public class CurrencyRaffleService : INService catch { } finally { _locker.Release(); } }); - } return (crg, null); } diff --git a/src/NadekoBot/Modules/Gambling/Shop/ShopCommands.cs b/src/NadekoBot/Modules/Gambling/Shop/ShopCommands.cs index 77474c5c1..dbb4e5466 100644 --- a/src/NadekoBot/Modules/Gambling/Shop/ShopCommands.cs +++ b/src/NadekoBot/Modules/Gambling/Shop/ShopCommands.cs @@ -225,7 +225,10 @@ public partial class Gambling var entries = new IndexedCollection(uow.GuildConfigsForId(ctx.Guild.Id, set => set.Include(x => x.ShopEntries) .ThenInclude(x => x.Items)) - .ShopEntries) { entry }; + .ShopEntries) + { + entry + }; uow.GuildConfigsForId(ctx.Guild.Id, set => set).ShopEntries = entries; uow.SaveChanges(); } @@ -254,7 +257,10 @@ public partial class Gambling var entries = new IndexedCollection(uow.GuildConfigsForId(ctx.Guild.Id, set => set.Include(x => x.ShopEntries) .ThenInclude(x => x.Items)) - .ShopEntries) { entry }; + .ShopEntries) + { + entry + }; uow.GuildConfigsForId(ctx.Guild.Id, set => set).ShopEntries = entries; uow.SaveChanges(); } @@ -270,7 +276,10 @@ public partial class Gambling index -= 1; if (index < 0) return; - var item = new ShopEntryItem { Text = itemText }; + var item = new ShopEntryItem + { + Text = itemText + }; ShopEntry entry; var rightType = false; var added = false; @@ -414,7 +423,6 @@ public partial class Gambling var embed = _eb.Create().WithOkColor(); if (entry.Type == ShopEntryType.Role) - { return embed .AddField(GetText(strs.name), GetText(strs.shop_role(Format.Bold(ctx.Guild.GetRole(entry.RoleId)?.Name @@ -422,14 +430,11 @@ public partial class Gambling true) .AddField(GetText(strs.price), entry.Price.ToString(), true) .AddField(GetText(strs.type), entry.Type.ToString(), true); - } if (entry.Type == ShopEntryType.List) - { return embed.AddField(GetText(strs.name), entry.Name, true) .AddField(GetText(strs.price), entry.Price.ToString(), true) .AddField(GetText(strs.type), GetText(strs.random_unique_item), true); - } //else if (entry.Type == ShopEntryType.Infinite_List) // return embed.AddField(GetText(strs.name), GetText(strs.shop_role(Format.Bold(entry.RoleName)), true)) diff --git a/src/NadekoBot/Modules/Gambling/Slot/SlotCommands.cs b/src/NadekoBot/Modules/Gambling/Slot/SlotCommands.cs index 362aba756..54fda72e1 100644 --- a/src/NadekoBot/Modules/Gambling/Slot/SlotCommands.cs +++ b/src/NadekoBot/Modules/Gambling/Slot/SlotCommands.cs @@ -211,7 +211,7 @@ public partial class Gambling } finally { - _= Task.Run(async () => + _ = Task.Run(async () => { await Task.Delay(1000); _runningUsers.Remove(ctx.User.Id); @@ -238,7 +238,8 @@ public partial class Gambling public static SlotResult Pull() { var numbers = new int[3]; - for (var i = 0; i < numbers.Length; i++) numbers[i] = new NadekoRandom().Next(0, MAX_VALUE + 1); + for (var i = 0; i < numbers.Length; i++) + numbers[i] = new NadekoRandom().Next(0, MAX_VALUE + 1); var multi = 0; foreach (var t in _winningCombos) { diff --git a/src/NadekoBot/Modules/Gambling/VoteRewardService.cs b/src/NadekoBot/Modules/Gambling/VoteRewardService.cs index 68574a049..0a8d7ae4c 100644 --- a/src/NadekoBot/Modules/Gambling/VoteRewardService.cs +++ b/src/NadekoBot/Modules/Gambling/VoteRewardService.cs @@ -37,7 +37,8 @@ public class VoteRewardService : INService, IReadyExecutor var http = new HttpClient(new HttpClientHandler { - AllowAutoRedirect = false, ServerCertificateCustomValidationCallback = delegate { return true; } + AllowAutoRedirect = false, + ServerCertificateCustomValidationCallback = delegate { return true; } }); while (true) diff --git a/src/NadekoBot/Modules/Gambling/Waifus/WaifuClaimCommands.cs b/src/NadekoBot/Modules/Gambling/Waifus/WaifuClaimCommands.cs index 9f11b182f..7bce5008a 100644 --- a/src/NadekoBot/Modules/Gambling/Waifus/WaifuClaimCommands.cs +++ b/src/NadekoBot/Modules/Gambling/Waifus/WaifuClaimCommands.cs @@ -112,7 +112,8 @@ public partial class Gambling public partial Task Divorce([Leftover] string target) { var waifuUserId = _service.GetWaifuUserId(ctx.User.Id, target); - if (waifuUserId == default) return ReplyErrorLocalizedAsync(strs.waifu_not_yours); + if (waifuUserId == default) + return ReplyErrorLocalizedAsync(strs.waifu_not_yours); return Divorce(waifuUserId); } diff --git a/src/NadekoBot/Modules/Gambling/Waifus/WaifuService.cs b/src/NadekoBot/Modules/Gambling/Waifus/WaifuService.cs index 8434052af..4b5a30a5b 100644 --- a/src/NadekoBot/Modules/Gambling/Waifus/WaifuService.cs +++ b/src/NadekoBot/Modules/Gambling/Waifus/WaifuService.cs @@ -55,7 +55,8 @@ public class WaifuService : INService } else // if not, pay 10% fee { - if (!await _cs.RemoveAsync(owner.Id, waifu.Price / 10, new("waifu", "transfer"))) return false; + if (!await _cs.RemoveAsync(owner.Id, waifu.Price / 10, new("waifu", "transfer"))) + return false; waifu.Price = (int)(waifu.Price * 0.95); // half of 10% = 5% price reduction if (waifu.Price < settings.Waifu.MinPrice) @@ -150,10 +151,19 @@ public class WaifuService : INService } else { - uow.WaifuInfo.Add(w = new() { Waifu = waifu, Claimer = claimer, Affinity = null, Price = amount }); + uow.WaifuInfo.Add(w = new() + { + Waifu = waifu, + Claimer = claimer, + Affinity = null, + Price = amount + }); uow.WaifuUpdates.Add(new() { - User = waifu, Old = null, New = claimer, UpdateType = WaifuUpdateType.Claimed + User = waifu, + Old = null, + New = claimer, + UpdateType = WaifuUpdateType.Claimed }); result = WaifuClaimResult.Success; } @@ -173,7 +183,10 @@ public class WaifuService : INService uow.WaifuUpdates.Add(new() { - User = w.Waifu, Old = oldClaimer, New = w.Claimer, UpdateType = WaifuUpdateType.Claimed + User = w.Waifu, + Old = oldClaimer, + New = w.Claimer, + UpdateType = WaifuUpdateType.Claimed }); } } @@ -192,7 +205,10 @@ public class WaifuService : INService uow.WaifuUpdates.Add(new() { - User = w.Waifu, Old = oldClaimer, New = w.Claimer, UpdateType = WaifuUpdateType.Claimed + User = w.Waifu, + Old = oldClaimer, + New = w.Claimer, + UpdateType = WaifuUpdateType.Claimed }); } } @@ -226,12 +242,21 @@ public class WaifuService : INService else if (w is null) { var thisUser = uow.GetOrCreateUser(user); - uow.WaifuInfo.Add(new() { Affinity = newAff, Waifu = thisUser, Price = 1, Claimer = null }); + uow.WaifuInfo.Add(new() + { + Affinity = newAff, + Waifu = thisUser, + Price = 1, + Claimer = null + }); success = true; uow.WaifuUpdates.Add(new() { - User = thisUser, Old = null, New = newAff, UpdateType = WaifuUpdateType.AffinityChanged + User = thisUser, + Old = null, + New = newAff, + UpdateType = WaifuUpdateType.AffinityChanged }); } else @@ -243,7 +268,10 @@ public class WaifuService : INService uow.WaifuUpdates.Add(new() { - User = w.Waifu, Old = oldAff, New = newAff, UpdateType = WaifuUpdateType.AffinityChanged + User = w.Waifu, + Old = oldAff, + New = newAff, + UpdateType = WaifuUpdateType.AffinityChanged }); } @@ -304,7 +332,10 @@ public class WaifuService : INService uow.WaifuUpdates.Add(new() { - User = w.Waifu, Old = oldClaimer, New = null, UpdateType = WaifuUpdateType.Claimed + User = w.Waifu, + Old = oldClaimer, + New = null, + UpdateType = WaifuUpdateType.Claimed }); } @@ -316,19 +347,27 @@ public class WaifuService : INService public async Task GiftWaifuAsync(IUser from, IUser giftedWaifu, WaifuItemModel itemObj) { - if (!await _cs.RemoveAsync(from, itemObj.Price, new("waifu", "item"))) return false; + if (!await _cs.RemoveAsync(from, itemObj.Price, new("waifu", "item"))) + return false; await using var uow = _db.GetDbContext(); var w = uow.WaifuInfo.ByWaifuUserId(giftedWaifu.Id, set => set.Include(x => x.Items).Include(x => x.Claimer)); if (w is null) uow.WaifuInfo.Add(w = new() { - Affinity = null, Claimer = null, Price = 1, Waifu = uow.GetOrCreateUser(giftedWaifu) + Affinity = null, + Claimer = null, + Price = 1, + Waifu = uow.GetOrCreateUser(giftedWaifu) }); if (!itemObj.Negative) { - w.Items.Add(new() { Name = itemObj.Name.ToLowerInvariant(), ItemEmoji = itemObj.ItemEmoji }); + w.Items.Add(new() + { + Name = itemObj.Name.ToLowerInvariant(), + ItemEmoji = itemObj.ItemEmoji + }); if (w.Claimer?.UserId == from.Id) w.Price += (int)(itemObj.Price * _gss.Data.Waifu.Multipliers.GiftEffect); diff --git a/src/NadekoBot/Modules/Gambling/Wheel/WheelOfFortune.cs b/src/NadekoBot/Modules/Gambling/Wheel/WheelOfFortune.cs index ae866214c..14a9ed4fb 100644 --- a/src/NadekoBot/Modules/Gambling/Wheel/WheelOfFortune.cs +++ b/src/NadekoBot/Modules/Gambling/Wheel/WheelOfFortune.cs @@ -31,7 +31,11 @@ public class WheelOfFortuneGame if (amount > 0) await _cs.AddAsync(_userId, amount, new("wheel", "win")); - return new() { Index = result, Amount = amount }; + return new() + { + Index = result, + Amount = amount + }; } public class Result diff --git a/src/NadekoBot/Modules/Gambling/~Shared/BetRoll.cs b/src/NadekoBot/Modules/Gambling/~Shared/BetRoll.cs index 86735a823..ce9e64d11 100644 --- a/src/NadekoBot/Modules/Gambling/~Shared/BetRoll.cs +++ b/src/NadekoBot/Modules/Gambling/~Shared/BetRoll.cs @@ -18,9 +18,18 @@ public class Betroll var pair = _thresholdPairs.FirstOrDefault(x => x.WhenAbove < roll); if (pair is null) - return new() { Multiplier = 0, Roll = roll }; + return new() + { + Multiplier = 0, + Roll = roll + }; - return new() { Multiplier = pair.MultiplyBy, Roll = roll, Threshold = pair.WhenAbove }; + return new() + { + Multiplier = pair.MultiplyBy, + Roll = roll, + Threshold = pair.WhenAbove + }; } public class Result diff --git a/src/NadekoBot/Modules/Gambling/~Shared/Decks/Deck.cs b/src/NadekoBot/Modules/Gambling/~Shared/Decks/Deck.cs index 977f54ef9..aa6c2a2e2 100644 --- a/src/NadekoBot/Modules/Gambling/~Shared/Decks/Deck.cs +++ b/src/NadekoBot/Modules/Gambling/~Shared/Decks/Deck.cs @@ -98,7 +98,8 @@ public class Deck /// private void Shuffle() { - if (CardPool.Count <= 1) return; + if (CardPool.Count <= 1) + return; var orderedPool = CardPool.Shuffle(); CardPool ??= orderedPool.ToList(); } @@ -128,7 +129,8 @@ public class Deck if (cards.GroupBy(card => card.Number).Count() != cards.Count()) return false; var toReturn = cards.Max(card => card.Number) - cards.Min(card => card.Number) == 4; - if (toReturn || cards.All(c => c.Number != 1)) return toReturn; + if (toReturn || cards.All(c => c.Number != 1)) + return toReturn; var newCards = cards.Select(c => c.Number == 1 ? new(c.Suit, 14) : c).ToArray(); return newCards.Max(card => card.Number) - newCards.Min(card => card.Number) == 4; @@ -194,8 +196,9 @@ public class Deck { if (handValues is null) InitHandValues(); - - foreach (var kvp in handValues.Where(x => x.Value(cards))) return kvp.Key; + + foreach (var kvp in handValues.Where(x => x.Value(cards))) + return kvp.Key; return "High card " + (cards.FirstOrDefault(c => c.Number == 1)?.GetValueText() ?? cards.Max().GetValueText()); } @@ -203,7 +206,10 @@ public class Deck { private static readonly IReadOnlyDictionary _suitToSuitChar = new Dictionary { - { CardSuit.Diamonds, "♦" }, { CardSuit.Clubs, "♣" }, { CardSuit.Spades, "♠" }, { CardSuit.Hearts, "♥" } + { CardSuit.Diamonds, "♦" }, + { CardSuit.Clubs, "♣" }, + { CardSuit.Spades, "♠" }, + { CardSuit.Hearts, "♥" } }; private static readonly IReadOnlyDictionary _suitCharToSuit = new Dictionary @@ -272,7 +278,8 @@ public class Deck public int CompareTo(object obj) { - if (obj is not Card card) return 0; + if (obj is not Card card) + return 0; return Number - card.Number; } diff --git a/src/NadekoBot/Modules/Games/Acrophobia/Acrophobia.cs b/src/NadekoBot/Modules/Games/Acrophobia/Acrophobia.cs index 18475c080..8e6ac0ec1 100644 --- a/src/NadekoBot/Modules/Games/Acrophobia/Acrophobia.cs +++ b/src/NadekoBot/Modules/Games/Acrophobia/Acrophobia.cs @@ -127,7 +127,7 @@ public sealed class AcrophobiaGame : IDisposable || !_usersWhoVoted.Add(userId)) break; ++_submissions[toVoteFor]; - _= Task.Run(() => OnUserVoted(userName)); + _ = Task.Run(() => OnUserVoted(userName)); return true; } diff --git a/src/NadekoBot/Modules/Games/Acrophobia/AcropobiaCommands.cs b/src/NadekoBot/Modules/Games/Acrophobia/AcropobiaCommands.cs index 7ceef0135..af4ea9fb3 100644 --- a/src/NadekoBot/Modules/Games/Acrophobia/AcropobiaCommands.cs +++ b/src/NadekoBot/Modules/Games/Acrophobia/AcropobiaCommands.cs @@ -48,7 +48,7 @@ public partial class Games if (msg.Channel.Id != ctx.Channel.Id) return Task.CompletedTask; - _= Task.Run(async () => + _ = Task.Run(async () => { try { diff --git a/src/NadekoBot/Modules/Games/ChatterBot/ChatterbotService.cs b/src/NadekoBot/Modules/Games/ChatterBot/ChatterbotService.cs index 1a917846d..4ea788798 100644 --- a/src/NadekoBot/Modules/Games/ChatterBot/ChatterbotService.cs +++ b/src/NadekoBot/Modules/Games/ChatterBot/ChatterbotService.cs @@ -137,7 +137,7 @@ Message: {Content}", usrMsg.Author, usrMsg.Author.Id, usrMsg.Content); - + return true; } } diff --git a/src/NadekoBot/Modules/Games/GamesConfig.cs b/src/NadekoBot/Modules/Games/GamesConfig.cs index f826627ef..a597d934c 100644 --- a/src/NadekoBot/Modules/Games/GamesConfig.cs +++ b/src/NadekoBot/Modules/Games/GamesConfig.cs @@ -11,10 +11,17 @@ public sealed partial class GamesConfig : ICloneable public int Version { get; set; } [Comment("Hangman related settings (.hangman command)")] - public HangmanConfig Hangman { get; set; } = new() { CurrencyReward = 0 }; + public HangmanConfig Hangman { get; set; } = new() + { + CurrencyReward = 0 + }; [Comment("Trivia related settings (.t command)")] - public TriviaConfig Trivia { get; set; } = new() { CurrencyReward = 0, MinimumWinReq = 1 }; + public TriviaConfig Trivia { get; set; } = new() + { + CurrencyReward = 0, + MinimumWinReq = 1 + }; [Comment("List of responses for the .8ball command. A random one will be selected every time")] public List EightBallResponses { get; set; } = new() @@ -47,14 +54,46 @@ public sealed partial class GamesConfig : ICloneable [Comment("List of animals which will be used for the animal race game (.race)")] public List RaceAnimals { get; set; } = new() { - new() { Icon = "🐼", Name = "Panda" }, - new() { Icon = "🐻", Name = "Bear" }, - new() { Icon = "🐧", Name = "Pengu" }, - new() { Icon = "🐨", Name = "Koala" }, - new() { Icon = "🐬", Name = "Dolphin" }, - new() { Icon = "🐞", Name = "Ladybird" }, - new() { Icon = "🦀", Name = "Crab" }, - new() { Icon = "🦄", Name = "Unicorn" } + new() + { + Icon = "🐼", + Name = "Panda" + }, + new() + { + Icon = "🐻", + Name = "Bear" + }, + new() + { + Icon = "🐧", + Name = "Pengu" + }, + new() + { + Icon = "🐨", + Name = "Koala" + }, + new() + { + Icon = "🐬", + Name = "Dolphin" + }, + new() + { + Icon = "🐞", + Name = "Ladybird" + }, + new() + { + Icon = "🦀", + Name = "Crab" + }, + new() + { + Icon = "🦄", + Name = "Unicorn" + } }; } diff --git a/src/NadekoBot/Modules/Games/GamesConfigService.cs b/src/NadekoBot/Modules/Games/GamesConfigService.cs index 6041fb7d8..a9d9a6694 100644 --- a/src/NadekoBot/Modules/Games/GamesConfigService.cs +++ b/src/NadekoBot/Modules/Games/GamesConfigService.cs @@ -38,7 +38,10 @@ public sealed class GamesConfigService : ConfigServiceBase ModifyConfig(c => { c.Version = 1; - c.Hangman = new() { CurrencyReward = 0 }; + c.Hangman = new() + { + CurrencyReward = 0 + }; }); } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Games/GamesService.cs b/src/NadekoBot/Modules/Games/GamesService.cs index fcf859f61..5b1fbd4c7 100644 --- a/src/NadekoBot/Modules/Games/GamesService.cs +++ b/src/NadekoBot/Modules/Games/GamesService.cs @@ -38,7 +38,10 @@ public class GamesService : INService { _gamesConfig = gamesConfig; _httpFactory = httpFactory; - _8BallCache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 500_000 }); + _8BallCache = new MemoryCache(new MemoryCacheOptions + { + SizeLimit = 500_000 + }); Ratings = new(GetRatingTexts); _rng = new NadekoRandom(); diff --git a/src/NadekoBot/Modules/Games/Hangman/DefaultHangmanSource.cs b/src/NadekoBot/Modules/Games/Hangman/DefaultHangmanSource.cs index ee1ec387a..82466eb59 100644 --- a/src/NadekoBot/Modules/Games/Hangman/DefaultHangmanSource.cs +++ b/src/NadekoBot/Modules/Games/Hangman/DefaultHangmanSource.cs @@ -24,6 +24,7 @@ public sealed class DefaultHangmanSource : IHangmanSource var qs = new Dictionary(); foreach (var file in Directory.EnumerateFiles("data/hangman/", "*.yml")) + { try { var data = Yaml.Deserializer.Deserialize(File.ReadAllText(file)); @@ -33,6 +34,7 @@ public sealed class DefaultHangmanSource : IHangmanSource { Log.Error(ex, "Loading {HangmanFile} failed", file); } + } termsDict = qs; diff --git a/src/NadekoBot/Modules/Games/Hangman/HangmanCommands.cs b/src/NadekoBot/Modules/Games/Hangman/HangmanCommands.cs index 58ee38ba5..eca95894d 100644 --- a/src/NadekoBot/Modules/Games/Hangman/HangmanCommands.cs +++ b/src/NadekoBot/Modules/Games/Hangman/HangmanCommands.cs @@ -62,7 +62,8 @@ public partial class Games [RequireContext(ContextType.Guild)] public async partial Task HangmanStop() { - if (await _service.StopHangman(ctx.Channel.Id)) await ReplyConfirmLocalizedAsync(strs.hangman_stopped); + if (await _service.StopHangman(ctx.Channel.Id)) + await ReplyConfirmLocalizedAsync(strs.hangman_stopped); } } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Games/Hangman/HangmanService.cs b/src/NadekoBot/Modules/Games/Hangman/HangmanService.cs index 7c044d42c..2d5bb4641 100644 --- a/src/NadekoBot/Modules/Games/Hangman/HangmanService.cs +++ b/src/NadekoBot/Modules/Games/Hangman/HangmanService.cs @@ -54,7 +54,8 @@ public sealed class HangmanService : IHangmanService, ILateExecutor { lock (_locker) { - if (_hangmanGames.TryRemove(channelId, out _)) return new(true); + if (_hangmanGames.TryRemove(channelId, out _)) + return new(true); } return new(false); @@ -88,7 +89,10 @@ public sealed class HangmanService : IHangmanService, ILateExecutor if (state.GuessResult is HangmanGame.GuessResult.Incorrect or HangmanGame.GuessResult.AlreadyTried) _cdCache.Set(msg.Author.Id, string.Empty, - new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(3) }); + new MemoryCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(3) + }); if (state.Phase == HangmanGame.Phase.Ended) if (_hangmanGames.TryRemove(msg.Channel.Id, out _)) diff --git a/src/NadekoBot/Modules/Games/Nunchi/Nunchi.cs b/src/NadekoBot/Modules/Games/Nunchi/Nunchi.cs index cd35335cc..c47803bac 100644 --- a/src/NadekoBot/Modules/Games/Nunchi/Nunchi.cs +++ b/src/NadekoBot/Modules/Games/Nunchi/Nunchi.cs @@ -85,7 +85,7 @@ public sealed class NunchiGame : IDisposable KILL_TIMEOUT); CurrentPhase = Phase.Playing; - _= OnGameStarted?.Invoke(this); + _ = OnGameStarted?.Invoke(this); _ = OnRoundStarted?.Invoke(this, CurrentNumber); return true; } @@ -122,7 +122,7 @@ public sealed class NunchiGame : IDisposable { killTimer.Change(Timeout.Infinite, Timeout.Infinite); CurrentPhase = Phase.Ended; - _= OnGameEnded?.Invoke(this, userTuple.Name); + _ = OnGameEnded?.Invoke(this, userTuple.Name); } else // else just start the new round without the user who was the last { diff --git a/src/NadekoBot/Modules/Games/Nunchi/NunchiCommands.cs b/src/NadekoBot/Modules/Games/Nunchi/NunchiCommands.cs index 11edb8c61..2ac83c328 100644 --- a/src/NadekoBot/Modules/Games/Nunchi/NunchiCommands.cs +++ b/src/NadekoBot/Modules/Games/Nunchi/NunchiCommands.cs @@ -55,7 +55,7 @@ public partial class Games Task ClientMessageReceived(SocketMessage arg) { - _= Task.Run(async () => + _ = Task.Run(async () => { if (arg.Channel.Id != ctx.Channel.Id) return; diff --git a/src/NadekoBot/Modules/Games/Polls/PollRunner.cs b/src/NadekoBot/Modules/Games/Polls/PollRunner.cs index b6bf69499..730a981be 100644 --- a/src/NadekoBot/Modules/Games/Polls/PollRunner.cs +++ b/src/NadekoBot/Modules/Games/Polls/PollRunner.cs @@ -39,11 +39,15 @@ public class PollRunner if (usr is null) return false; - voteObj = new() { UserId = msg.Author.Id, VoteIndex = vote }; + voteObj = new() + { + UserId = msg.Author.Id, + VoteIndex = vote + }; if (!Poll.Votes.Add(voteObj)) return false; - _= OnVoted?.Invoke(msg, usr); + _ = OnVoted?.Invoke(msg, usr); } finally { _locker.Release(); } diff --git a/src/NadekoBot/Modules/Games/Polls/PollService.cs b/src/NadekoBot/Modules/Games/Polls/PollService.cs index e1a1549c3..5a29ce755 100644 --- a/src/NadekoBot/Modules/Games/Polls/PollService.cs +++ b/src/NadekoBot/Modules/Games/Polls/PollService.cs @@ -44,7 +44,11 @@ public class PollService : IEarlyBehavior if (data.Length < 3) return null; - var col = new IndexedCollection(data.Skip(1).Select(x => new PollAnswer { Text = x })); + var col = new IndexedCollection(data.Skip(1) + .Select(x => new PollAnswer + { + Text = x + })); return new() { diff --git a/src/NadekoBot/Modules/Games/SpeedTyping/SpeedTypingCommands.cs b/src/NadekoBot/Modules/Games/SpeedTyping/SpeedTypingCommands.cs index 645565cca..e90e37edf 100644 --- a/src/NadekoBot/Modules/Games/SpeedTyping/SpeedTypingCommands.cs +++ b/src/NadekoBot/Modules/Games/SpeedTyping/SpeedTypingCommands.cs @@ -89,7 +89,8 @@ public partial class Games { var removed = _service.RemoveTypingArticle(--index); - if (removed is null) return; + if (removed is null) + return; var embed = _eb.Create() .WithTitle($"Removed typing article #{index + 1}") diff --git a/src/NadekoBot/Modules/Games/SpeedTyping/TypingGame.cs b/src/NadekoBot/Modules/Games/SpeedTyping/TypingGame.cs index 9545b945f..0b6be439d 100644 --- a/src/NadekoBot/Modules/Games/SpeedTyping/TypingGame.cs +++ b/src/NadekoBot/Modules/Games/SpeedTyping/TypingGame.cs @@ -41,7 +41,8 @@ public class TypingGame public async Task Stop() { - if (!IsActive) return false; + if (!IsActive) + return false; _client.MessageReceived -= AnswerReceived; _finishedUserIds.Clear(); IsActive = false; @@ -60,7 +61,8 @@ public class TypingGame public async Task Start() { - if (IsActive) return; // can't start running game + if (IsActive) + return; // can't start running game IsActive = true; CurrentSentence = GetRandomSentence(); var i = (int)(CurrentSentence.Length / WORD_VALUE * 1.7f); @@ -73,7 +75,10 @@ public class TypingGame var time = _options.StartTime; var msg = await Channel.SendMessageAsync($"Starting new typing contest in **{time}**...", - options: new() { RetryMode = RetryMode.AlwaysRetry }); + options: new() + { + RetryMode = RetryMode.AlwaysRetry + }); do { @@ -117,7 +122,7 @@ public class TypingGame private Task AnswerReceived(SocketMessage imsg) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -126,7 +131,8 @@ public class TypingGame if (imsg is not SocketUserMessage msg) return; - if (Channel is null || Channel.Id != msg.Channel.Id) return; + if (Channel is null || Channel.Id != msg.Channel.Id) + return; var guess = msg.Content; diff --git a/src/NadekoBot/Modules/Games/TicTacToe/TicTacToe.cs b/src/NadekoBot/Modules/Games/TicTacToe/TicTacToe.cs index 14e6b3fcf..d5da3f6e4 100644 --- a/src/NadekoBot/Modules/Games/TicTacToe/TicTacToe.cs +++ b/src/NadekoBot/Modules/Games/TicTacToe/TicTacToe.cs @@ -175,14 +175,17 @@ public class TicTacToe { for (var i = 0; i < 3; i++) for (var j = 0; j < 3; j++) + { if (_state[i, j] is null) return false; + } + return true; } private Task Client_MessageReceived(SocketMessage msg) { - _= Task.Run(async () => + _ = Task.Run(async () => { await _moveLock.WaitAsync(); try @@ -266,7 +269,8 @@ public class TicTacToe try { - if (del2 is not null) await del2; + if (del2 is not null) + await del2; } catch { } }); diff --git a/src/NadekoBot/Modules/Games/TicTacToe/TicTacToeCommands.cs b/src/NadekoBot/Modules/Games/TicTacToe/TicTacToeCommands.cs index 964accac5..e04a8c287 100644 --- a/src/NadekoBot/Modules/Games/TicTacToe/TicTacToeCommands.cs +++ b/src/NadekoBot/Modules/Games/TicTacToe/TicTacToeCommands.cs @@ -28,7 +28,7 @@ public partial class Games { if (_service.TicTacToeGames.TryGetValue(channel.Id, out var game)) { - _= Task.Run(async () => + _ = Task.Run(async () => { await game.Start((IGuildUser)ctx.User); }); diff --git a/src/NadekoBot/Modules/Games/Trivia/TriviaCommands.cs b/src/NadekoBot/Modules/Games/Trivia/TriviaCommands.cs index 20a746427..8b357386d 100644 --- a/src/NadekoBot/Modules/Games/Trivia/TriviaCommands.cs +++ b/src/NadekoBot/Modules/Games/Trivia/TriviaCommands.cs @@ -40,7 +40,8 @@ public partial class Games var (opts, _) = OptionsParser.ParseFrom(new TriviaOptions(), args); var config = _gamesConfig.Data; - if (config.Trivia.MinimumWinReq > 0 && config.Trivia.MinimumWinReq > opts.WinRequirement) return; + if (config.Trivia.MinimumWinReq > 0 && config.Trivia.MinimumWinReq > opts.WinRequirement) + return; var trivia = new TriviaGame(Strings, _client, diff --git a/src/NadekoBot/Modules/Games/Trivia/TriviaGame.cs b/src/NadekoBot/Modules/Games/Trivia/TriviaGame.cs index 26eb3913d..2bb6f526d 100644 --- a/src/NadekoBot/Modules/Games/Trivia/TriviaGame.cs +++ b/src/NadekoBot/Modules/Games/Trivia/TriviaGame.cs @@ -198,7 +198,7 @@ public class TriviaGame private Task PotentialGuess(SocketMessage imsg) { - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -226,7 +226,8 @@ public class TriviaGame } finally { _guessLock.Release(); } - if (!guess) return; + if (!guess) + return; triviaCancelSource.Cancel(); diff --git a/src/NadekoBot/Modules/Games/Trivia/TriviaQuestion.cs b/src/NadekoBot/Modules/Games/Trivia/TriviaQuestion.cs index 8f75e5689..0d662ef20 100644 --- a/src/NadekoBot/Modules/Games/Trivia/TriviaQuestion.cs +++ b/src/NadekoBot/Modules/Games/Trivia/TriviaQuestion.cs @@ -11,7 +11,10 @@ public class TriviaQuestion //represents the min size to judge levDistance with private static readonly HashSet> _strictness = new() { - new(9, 0), new(14, 1), new(19, 2), new(22, 3) + new(9, 0), + new(14, 1), + new(19, 2), + new(22, 3) }; public string Category { get; set; } @@ -44,9 +47,11 @@ public class TriviaQuestion public bool IsAnswerCorrect(string guess) { - if (Answer.Equals(guess, StringComparison.InvariantCulture)) return true; + if (Answer.Equals(guess, StringComparison.InvariantCulture)) + return true; var cleanGuess = Clean(guess); - if (CleanAnswer.Equals(cleanGuess, StringComparison.InvariantCulture)) return true; + if (CleanAnswer.Equals(cleanGuess, StringComparison.InvariantCulture)) + return true; var levDistanceClean = CleanAnswer.LevenshteinDistance(cleanGuess); var levDistanceNormal = Answer.LevenshteinDistance(guess); @@ -57,12 +62,14 @@ public class TriviaQuestion private static bool JudgeGuess(int guessLength, int answerLength, int levDistance) { foreach (var level in _strictness) + { if (guessLength <= level.Item1 || answerLength <= level.Item1) { if (levDistance <= level.Item2) return true; return false; } + } return false; } diff --git a/src/NadekoBot/Modules/Games/Trivia/TriviaQuestionPool.cs b/src/NadekoBot/Modules/Games/Trivia/TriviaQuestionPool.cs index 865eb6aed..f98bce405 100644 --- a/src/NadekoBot/Modules/Games/Trivia/TriviaQuestionPool.cs +++ b/src/NadekoBot/Modules/Games/Trivia/TriviaQuestionPool.cs @@ -37,7 +37,7 @@ public class TriviaQuestionPool TriviaQuestion randomQuestion; while (exclude.Contains(randomQuestion = Pool[_rng.Next(0, Pool.Length)])) - { + { // if too many questions are excluded, clear the exclusion list and start over if (exclude.Count > Pool.Length / 10 * 9) { diff --git a/src/NadekoBot/Modules/Help/Help.cs b/src/NadekoBot/Modules/Help/Help.cs index e4fa12ba5..f24fbfaec 100644 --- a/src/NadekoBot/Modules/Help/Help.cs +++ b/src/NadekoBot/Modules/Help/Help.cs @@ -14,7 +14,7 @@ public partial class Help : NadekoModule { public const string PATREON_URL = "https://patreon.com/nadekobot"; public const string PAYPAL_URL = "https://paypal.me/Kwoth"; - + private readonly CommandService _cmds; private readonly BotConfigService _bss; private readonly GlobalPermissionService _perms; @@ -317,7 +317,8 @@ public partial class Help : NadekoModule var opt = ((NadekoOptionsAttribute)com.Attributes.FirstOrDefault(static x => x is NadekoOptionsAttribute)) ?.OptionType; - if (opt is not null) optHelpStr = HelpService.GetCommandOptionHelpList(opt); + if (opt is not null) + optHelpStr = HelpService.GetCommandOptionHelpList(opt); return new CommandJsonObject { @@ -346,12 +347,16 @@ public partial class Help : NadekoModule // if all env vars are set, upload the unindented file (to save space) there if (!(serviceUrl is null || accessKey is null || secretAcccessKey is null)) { - var config = new AmazonS3Config { ServiceURL = serviceUrl }; + var config = new AmazonS3Config + { + ServiceURL = serviceUrl + }; using var dlClient = new AmazonS3Client(accessKey, secretAcccessKey, config); var oldVersionObject = await dlClient.GetObjectAsync(new() { - BucketName = "nadeko-pictures", Key = "cmds/versions.json" + BucketName = "nadeko-pictures", + Key = "cmds/versions.json" }); using (var client = new AmazonS3Client(accessKey, secretAcccessKey, config)) @@ -377,7 +382,10 @@ public partial class Help : NadekoModule // save the file with new version added // versionList.Add(StatsService.BotVersion); versionListString = JsonSerializer.Serialize(versionList.Prepend(StatsService.BOT_VERSION), - new JsonSerializerOptions { WriteIndented = true }); + new JsonSerializerOptions + { + WriteIndented = true + }); // upload the updated version list using var client = new AmazonS3Client(accessKey, secretAcccessKey, config); diff --git a/src/NadekoBot/Modules/Help/HelpService.cs b/src/NadekoBot/Modules/Help/HelpService.cs index 750562418..ef02561bc 100644 --- a/src/NadekoBot/Modules/Help/HelpService.cs +++ b/src/NadekoBot/Modules/Help/HelpService.cs @@ -130,7 +130,7 @@ public class HelpService : ILateExecutor, INService { if (userPerm.ChannelPermission is { } cPerm) userPermString = GetPreconditionString(cPerm); - + if (userPerm.GuildPermission is { } gPerm) userPermString = GetPreconditionString(gPerm); } diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index 3ebffafad..3ae4244bd 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -239,7 +239,8 @@ public sealed partial class Music : NadekoModule return; var success = await _service.PlayAsync(ctx.Guild.Id, ((IGuildUser)ctx.User).VoiceChannel.Id); - if (!success) await ReplyErrorLocalizedAsync(strs.no_player); + if (!success) + await ReplyErrorLocalizedAsync(strs.no_player); } // list queue, relevant page @@ -276,7 +277,8 @@ public sealed partial class Music : NadekoModule { var desc = string.Empty; var current = mp.GetCurrentTrack(out var currentIndex); - if (current is not null) desc = $"`🔊` {current.PrettyFullName()}\n\n" + desc; + if (current is not null) + desc = $"`🔊` {current.PrettyFullName()}\n\n" + desc; var repeatType = mp.Repeat; var add = string.Empty; diff --git a/src/NadekoBot/Modules/Music/PlaylistCommands.cs b/src/NadekoBot/Modules/Music/PlaylistCommands.cs index 6ad262b27..1f276acc9 100644 --- a/src/NadekoBot/Modules/Music/PlaylistCommands.cs +++ b/src/NadekoBot/Modules/Music/PlaylistCommands.cs @@ -139,7 +139,10 @@ public sealed partial class Music { playlist = new() { - Name = name, Author = ctx.User.Username, AuthorId = ctx.User.Id, Songs = songs.ToList() + Name = name, + Author = ctx.User.Username, + AuthorId = ctx.User.Id, + Songs = songs.ToList() }; uow.MusicPlaylists.Add(playlist); await uow.SaveChangesAsync(); @@ -212,7 +215,8 @@ public sealed partial class Music await mp.EnqueueManyAsync(mpl.Songs.Select(x => (x.Query, (MusicPlatform)x.ProviderType)), ctx.User.ToString()); - if (msg is not null) await msg.ModifyAsync(m => m.Content = GetText(strs.playlist_queue_complete)); + if (msg is not null) + await msg.ModifyAsync(m => m.Content = GetText(strs.playlist_queue_complete)); } finally { diff --git a/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs b/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs index 94d1071c7..7f70bc715 100644 --- a/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs +++ b/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs @@ -133,7 +133,8 @@ public sealed class AyuVoiceStateService : INService Task OnVoiceServerUpdated(SocketVoiceServer data) { - if (data.Guild.Id == guildId) voiceServerUpdatedSource.TrySetResult(data); + if (data.Guild.Id == guildId) + voiceServerUpdatedSource.TrySetResult(data); return Task.CompletedTask; } @@ -157,14 +158,10 @@ public sealed class AyuVoiceStateService : INService // wait for both to end (max 1s) and check if either of them is a delay task var results = await Task.WhenAll(maybeUpdateTask, maybeServerTask); if (results[0] == delayTask || results[1] == delayTask) - { // if either is delay, return null - connection unsuccessful return null; - } else - { cts.Cancel(); - } // if both are succesful, that means we can safely get // the values from completion sources diff --git a/src/NadekoBot/Modules/Music/Services/MusicService.cs b/src/NadekoBot/Modules/Music/Services/MusicService.cs index ca4258f63..0e024f858 100644 --- a/src/NadekoBot/Modules/Music/Services/MusicService.cs +++ b/src/NadekoBot/Modules/Music/Services/MusicService.cs @@ -63,7 +63,8 @@ public sealed class MusicService : IMusicService private void RemoveMusicPlayer(ulong guildId) { _outputChannels.TryRemove(guildId, out _); - if (_players.TryRemove(guildId, out var mp)) DisposeMusicPlayer(mp); + if (_players.TryRemove(guildId, out var mp)) + DisposeMusicPlayer(mp); } private Task ClientOnLeftGuild(SocketGuild guild) @@ -139,7 +140,8 @@ public sealed class MusicService : IMusicService var queue = new MusicQueue(); var resolver = _trackResolveProvider; - if (!_voiceStateService.TryGetProxy(guildId, out var proxy)) return null; + if (!_voiceStateService.TryGetProxy(guildId, out var proxy)) + return null; var settings = await GetSettingsInternalAsync(guildId); @@ -226,7 +228,8 @@ public sealed class MusicService : IMusicService // this has to be done because dragging bot to another vc isn't supported yet public async Task PlayAsync(ulong guildId, ulong voiceChannelId) { - if (!TryGetMusicPlayer(guildId, out var mp)) return false; + if (!TryGetMusicPlayer(guildId, out var mp)) + return false; if (mp.IsStopped) if (!_voiceStateService.TryGetProxy(guildId, out var proxy) @@ -254,7 +257,8 @@ public sealed class MusicService : IMusicService try { IList<(string, string)> videos = await SearchYtLoaderVideosAsync(query); - if (videos.Count > 0) return videos; + if (videos.Count > 0) + return videos; } catch (Exception ex) { diff --git a/src/NadekoBot/Modules/Music/_Common/Impl/MusicPlayer.cs b/src/NadekoBot/Modules/Music/_Common/Impl/MusicPlayer.cs index d64d108f0..6269d6fef 100644 --- a/src/NadekoBot/Modules/Music/_Common/Impl/MusicPlayer.cs +++ b/src/NadekoBot/Modules/Music/_Common/Impl/MusicPlayer.cs @@ -54,7 +54,7 @@ public sealed class MusicPlayer : IMusicPlayer _songBuffer = new PoopyBufferImmortalized(_vc.InputLength); - _thread = new(async() => + _thread = new(async () => { await PlayLoop(); }); @@ -282,7 +282,8 @@ public sealed class MusicPlayer : IMusicPlayer var data = sb.Read(vc.InputLength, out var length); // if nothing is read from the buffer, song is finished - if (data.Length == 0) return null; + if (data.Length == 0) + return null; _adjustVolume(data, Volume); return _proxy.SendPcmFrame(vc, data, length); @@ -325,7 +326,8 @@ public sealed class MusicPlayer : IMusicPlayer [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void AdjustVolumeInt16(Span audioSamples, float volume) { - if (Math.Abs(volume - 1f) < 0.0001f) return; + if (Math.Abs(volume - 1f) < 0.0001f) + return; var samples = MemoryMarshal.Cast(audioSamples); @@ -339,7 +341,8 @@ public sealed class MusicPlayer : IMusicPlayer [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void AdjustVolumeFloat32(Span audioSamples, float volume) { - if (Math.Abs(volume - 1f) < 0.0001f) return; + if (Math.Abs(volume - 1f) < 0.0001f) + return; var samples = MemoryMarshal.Cast(audioSamples); diff --git a/src/NadekoBot/Modules/Music/_Common/Impl/MusicQueue.cs b/src/NadekoBot/Modules/Music/_Common/Impl/MusicQueue.cs index 7c23386a1..80ff65662 100644 --- a/src/NadekoBot/Modules/Music/_Common/Impl/MusicQueue.cs +++ b/src/NadekoBot/Modules/Music/_Common/Impl/MusicQueue.cs @@ -87,7 +87,8 @@ public sealed partial class MusicQueue : IMusicQueue { lock (_locker) { - if (tracks.Count == 0) return Enqueue(trackInfo, queuer, out trackIndex); + if (tracks.Count == 0) + return Enqueue(trackInfo, queuer, out trackIndex); var currentNode = tracks.First!; int i; @@ -165,7 +166,8 @@ public sealed partial class MusicQueue : IMusicQueue { var removedNode = tracks.First!; int i; - for (i = 0; i < remoteAtIndex; i++) removedNode = removedNode.Next!; + for (i = 0; i < remoteAtIndex; i++) + removedNode = removedNode.Next!; trackInfo = removedNode.Value; tracks.Remove(removedNode); @@ -303,7 +305,8 @@ public sealed partial class MusicQueue : IMusicQueue if (remoteAt < 0 || remoteAt >= tracks.Count) return false; - if (remoteAt == index) isCurrent = true; + if (remoteAt == index) + isCurrent = true; RemoveAtInternal(remoteAt, out trackInfo); diff --git a/src/NadekoBot/Modules/Music/_Common/Impl/VoiceProxy.cs b/src/NadekoBot/Modules/Music/_Common/Impl/VoiceProxy.cs index 33842d5b6..2d4a0e545 100644 --- a/src/NadekoBot/Modules/Music/_Common/Impl/VoiceProxy.cs +++ b/src/NadekoBot/Modules/Music/_Common/Impl/VoiceProxy.cs @@ -35,7 +35,8 @@ public sealed class VoiceProxy : IVoiceProxy try { var gw = gateway; - if (gw is null || gw.Stopped || !gw.Started) return false; + if (gw is null || gw.Stopped || !gw.Started) + return false; vc.SendPcmFrame(gw, data, 0, length); return true; @@ -51,7 +52,8 @@ public sealed class VoiceProxy : IVoiceProxy var errorCount = 0; do { - if (State == VoiceProxyState.Stopped) break; + if (State == VoiceProxyState.Stopped) + break; try { diff --git a/src/NadekoBot/Modules/Music/_Common/Resolvers/LocalTrackResolver.cs b/src/NadekoBot/Modules/Music/_Common/Resolvers/LocalTrackResolver.cs index 850ee5420..c5a07039e 100644 --- a/src/NadekoBot/Modules/Music/_Common/Resolvers/LocalTrackResolver.cs +++ b/src/NadekoBot/Modules/Music/_Common/Resolvers/LocalTrackResolver.cs @@ -43,7 +43,8 @@ public sealed class LocalTrackResolver : ILocalTrackResolver .Where(x => { if (!x.Attributes.HasFlag(FileAttributes.Hidden | FileAttributes.System) - && _musicExtensions.Contains(x.Extension.ToUpperInvariant())) return true; + && _musicExtensions.Contains(x.Extension.ToUpperInvariant())) + return true; return false; }) .ToList(); diff --git a/src/NadekoBot/Modules/Music/_Common/Resolvers/SoundcloudResolver.cs b/src/NadekoBot/Modules/Music/_Common/Resolvers/SoundcloudResolver.cs index 0ee1ff945..d4c0defd2 100644 --- a/src/NadekoBot/Modules/Music/_Common/Resolvers/SoundcloudResolver.cs +++ b/src/NadekoBot/Modules/Music/_Common/Resolvers/SoundcloudResolver.cs @@ -27,14 +27,16 @@ public sealed class SoundcloudResolver : ISoundcloudResolver using var http = _httpFactory.CreateClient(); var responseString = await http.GetStringAsync($"https://scapi.nadeko.bot/resolve?url={playlist}"); var scvids = JObject.Parse(responseString)["tracks"]?.ToObject(); - if (scvids is null) yield break; + if (scvids is null) + yield break; foreach (var videosChunk in scvids.Where(x => x.Streamable is true).Chunk(5)) { var cachableTracks = videosChunk.Select(VideoModelToCachedData).ToList(); await cachableTracks.Select(_trackCacher.CacheTrackDataAsync).WhenAll(); - foreach (var info in cachableTracks.Select(CachableDataToTrackInfo)) yield return info; + foreach (var info in cachableTracks.Select(CachableDataToTrackInfo)) + yield return info; } } diff --git a/src/NadekoBot/Modules/Nsfw/Nsfw.cs b/src/NadekoBot/Modules/Nsfw/Nsfw.cs index ccadc3a03..3f5517c45 100644 --- a/src/NadekoBot/Modules/Nsfw/Nsfw.cs +++ b/src/NadekoBot/Modules/Nsfw/Nsfw.cs @@ -65,7 +65,8 @@ public partial class NSFW : NadekoModule if (interval == 0) { - if (!_service.AutoHentaiTimers.TryRemove(ctx.Channel.Id, out t)) return; + if (!_service.AutoHentaiTimers.TryRemove(ctx.Channel.Id, out t)) + return; t.Change(Timeout.Infinite, Timeout.Infinite); //proper way to disable the timer await ReplyConfirmLocalizedAsync(strs.stopped); @@ -120,7 +121,8 @@ public partial class NSFW : NadekoModule if (interval == 0) { - if (!_service.AutoBoobTimers.TryRemove(ctx.Channel.Id, out t)) return; + if (!_service.AutoBoobTimers.TryRemove(ctx.Channel.Id, out t)) + return; t.Change(Timeout.Infinite, Timeout.Infinite); await ReplyConfirmLocalizedAsync(strs.stopped); @@ -166,7 +168,8 @@ public partial class NSFW : NadekoModule if (interval == 0) { - if (!_service.AutoButtTimers.TryRemove(ctx.Channel.Id, out t)) return; + if (!_service.AutoButtTimers.TryRemove(ctx.Channel.Id, out t)) + return; t.Change(Timeout.Infinite, Timeout.Infinite); //proper way to disable the timer await ReplyConfirmLocalizedAsync(strs.stopped); diff --git a/src/NadekoBot/Modules/Nsfw/SearchImageCacher.cs b/src/NadekoBot/Modules/Nsfw/SearchImageCacher.cs index 13d4e2998..27359c2b4 100644 --- a/src/NadekoBot/Modules/Nsfw/SearchImageCacher.cs +++ b/src/NadekoBot/Modules/Nsfw/SearchImageCacher.cs @@ -87,6 +87,7 @@ public class SearchImageCacher : INService // both 'kiss' (real tag returned by the image) and 'kissing' will be populated with // retreived images foreach (var tag in img.Tags.Concat(tags).Distinct()) + { if (typeUsedTags.Contains(tag)) { var set = _cache.GetOrCreate>(Key(type, tag), @@ -99,6 +100,7 @@ public class SearchImageCacher : INService if (set.Count < 100) set.Add(img); } + } } } @@ -127,10 +129,12 @@ public class SearchImageCacher : INService foreach (var tag in tags) // if any tag is missing from cache, that means there is no result + { if (_cache.TryGetValue>(Key(type, tag), out var set)) setList.Add(set); else return null; + } if (setList.Count == 0) return null; @@ -169,8 +173,11 @@ public class SearchImageCacher : INService // remove from cache foreach (var tag in tags) + { if (_cache.TryGetValue>(Key(type, tag), out var items)) items.Remove(toReturn); + } + return toReturn; } } diff --git a/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs b/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs index b8e0cafc8..28f6d9565 100644 --- a/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs +++ b/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs @@ -75,7 +75,11 @@ public class SearchImagesService : ISearchImagesService, INService CancellationToken cancel) { if (!tags.All(x => IsValidTag(x))) - return new() { Error = "One or more tags are invalid.", Url = "" }; + return new() + { + Error = "One or more tags are invalid.", + Url = "" + }; Log.Information("Getting {V} image for Guild: {GuildId}...", dapi.ToString(), guildId); try @@ -84,22 +88,33 @@ public class SearchImagesService : ISearchImagesService, INService if (dapi == Booru.E621) for (var i = 0; i < tags.Length; ++i) + { if (tags[i] == "yuri") tags[i] = "female/female"; + } if (dapi == Booru.Derpibooru) for (var i = 0; i < tags.Length; ++i) + { if (tags[i] == "yuri") tags[i] = "lesbian"; + } var result = await _cache.GetImageNew(tags, forceExplicit, dapi, blTags ?? new HashSet(), cancel); if (result is null) - return new() { Error = "Image not found.", Url = "" }; + return new() + { + Error = "Image not found.", + Url = "" + }; var reply = new UrlReply { - Error = "", Url = result.FileUrl, Rating = result.Rating, Provider = result.SearchType.ToString() + Error = "", + Url = result.FileUrl, + Rating = result.Rating, + Provider = result.SearchType.ToString() }; reply.Tags.AddRange(result.Tags); @@ -109,7 +124,11 @@ public class SearchImagesService : ISearchImagesService, INService catch (Exception ex) { Log.Error(ex, "Failed getting {Dapi} image: {Message}", dapi, ex.Message); - return new() { Error = ex.Message, Url = "" }; + return new() + { + Error = ex.Message, + Url = "" + }; } } @@ -168,7 +187,10 @@ public class SearchImagesService : ISearchImagesService, INService } while (tasks.Count > 0); // keep looping as long as there is any task remaining to be attempted // if we ran out of tasks, that means all tasks failed - return an error - return new() { Error = "No hentai image found." }; + return new() + { + Error = "No hentai image found." + }; } public async Task Boobs() @@ -177,12 +199,20 @@ public class SearchImagesService : ISearchImagesService, INService { JToken obj; obj = JArray.Parse(await _http.GetStringAsync($"http://api.oboobs.ru/boobs/{_rng.Next(0, 12000)}"))[0]; - return new() { Error = "", Url = $"http://media.oboobs.ru/{obj["preview"]}" }; + return new() + { + Error = "", + Url = $"http://media.oboobs.ru/{obj["preview"]}" + }; } catch (Exception ex) { Log.Error(ex, "Error retreiving boob image: {Message}", ex.Message); - return new() { Error = ex.Message, Url = "" }; + return new() + { + Error = ex.Message, + Url = "" + }; } } @@ -203,7 +233,11 @@ public class SearchImagesService : ISearchImagesService, INService } else { - uow.NsfwBlacklistedTags.Add(new() { Tag = tag, GuildId = guildId }); + uow.NsfwBlacklistedTags.Add(new() + { + Tag = tag, + GuildId = guildId + }); uow.SaveChanges(); } @@ -216,7 +250,8 @@ public class SearchImagesService : ISearchImagesService, INService { lock (_taglock) { - if (BlacklistedTags.TryGetValue(guildId, out var tags)) return new(tags.ToArray()); + if (BlacklistedTags.TryGetValue(guildId, out var tags)) + return new(tags.ToArray()); return new(Array.Empty()); } @@ -228,12 +263,20 @@ public class SearchImagesService : ISearchImagesService, INService { JToken obj; obj = JArray.Parse(await _http.GetStringAsync($"http://api.obutts.ru/butts/{_rng.Next(0, 6100)}"))[0]; - return new() { Error = "", Url = $"http://media.obutts.ru/{obj["preview"]}" }; + return new() + { + Error = "", + Url = $"http://media.obutts.ru/{obj["preview"]}" + }; } catch (Exception ex) { Log.Error(ex, "Error retreiving butt image: {Message}", ex.Message); - return new() { Error = ex.Message, Url = "" }; + return new() + { + Error = ex.Message, + Url = "" + }; } } @@ -262,7 +305,11 @@ public class SearchImagesService : ISearchImagesService, INService model.NumPages, model.NumFavorites, model.UploadDate.ToUnixTimestamp().UtcDateTime, - model.Tags.Map(x => new Tag { Name = x.Name, Url = "https://nhentai.com/" + x.Url })); + model.Tags.Map(x => new Tag + { + Name = x.Name, + Url = "https://nhentai.com/" + x.Url + })); } private async Task GetNhentaiByIdInternalAsync(uint id) diff --git a/src/NadekoBot/Modules/Nsfw/_Common/Downloaders/DanbooruImageDownloader.cs b/src/NadekoBot/Modules/Nsfw/_Common/Downloaders/DanbooruImageDownloader.cs index dc283e798..4d3b7bcea 100644 --- a/src/NadekoBot/Modules/Nsfw/_Common/Downloaders/DanbooruImageDownloader.cs +++ b/src/NadekoBot/Modules/Nsfw/_Common/Downloaders/DanbooruImageDownloader.cs @@ -26,7 +26,8 @@ public sealed class DanbooruImageDownloader : DapiImageDownloader _baseUrl + "/tags.json" + $"?search[name_or_alias_matches]={tag}", _serializerOptions, cancel); - if (tags is { Length: > 0 }) return _existentTags[tag] = true; + if (tags is { Length: > 0 }) + return _existentTags[tag] = true; return _nonexistentTags[tag] = false; } diff --git a/src/NadekoBot/Modules/Nsfw/_Common/Downloaders/DapiImageDownloader.cs b/src/NadekoBot/Modules/Nsfw/_Common/Downloaders/DapiImageDownloader.cs index 17530562b..1dddb870c 100644 --- a/src/NadekoBot/Modules/Nsfw/_Common/Downloaders/DapiImageDownloader.cs +++ b/src/NadekoBot/Modules/Nsfw/_Common/Downloaders/DapiImageDownloader.cs @@ -19,8 +19,10 @@ public abstract class DapiImageDownloader : ImageDownloader // if any of the tags is not valid, the query is not valid foreach (var result in results) + { if (!result) return false; + } return true; } diff --git a/src/NadekoBot/Modules/Permissions/Blacklist/BlacklistCommands.cs b/src/NadekoBot/Modules/Permissions/Blacklist/BlacklistCommands.cs index 665aceb15..86a88aa07 100644 --- a/src/NadekoBot/Modules/Permissions/Blacklist/BlacklistCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Blacklist/BlacklistCommands.cs @@ -34,8 +34,8 @@ public partial class Permissions BlacklistType.User => Format.Code(i.ItemId.ToString()) + " " + ((await _client.Rest.GetUserAsync(i.ItemId)) - ?.ToString() - ?? ""), + ?.ToString() + ?? ""), BlacklistType.Server => Format.Code(i.ItemId.ToString()) + " " + (_client.GetGuild(i.ItemId)?.ToString() ?? ""), diff --git a/src/NadekoBot/Modules/Permissions/Blacklist/BlacklistService.cs b/src/NadekoBot/Modules/Permissions/Blacklist/BlacklistService.cs index 3e0ba46b4..638c71289 100644 --- a/src/NadekoBot/Modules/Permissions/Blacklist/BlacklistService.cs +++ b/src/NadekoBot/Modules/Permissions/Blacklist/BlacklistService.cs @@ -75,7 +75,8 @@ public sealed class BlacklistService : IEarlyBehavior using var uow = _db.GetDbContext(); var toPublish = uow.Blacklist.AsNoTracking().ToArray(); blacklist = toPublish; - if (publish) _pubSub.Pub(_blPubKey, toPublish); + if (publish) + _pubSub.Pub(_blPubKey, toPublish); } public void Blacklist(BlacklistType type, ulong id) @@ -84,7 +85,11 @@ public sealed class BlacklistService : IEarlyBehavior return; using var uow = _db.GetDbContext(); - var item = new BlacklistEntry { ItemId = id, Type = type }; + var item = new BlacklistEntry + { + ItemId = id, + Type = type + }; uow.Blacklist.Add(item); uow.SaveChanges(); @@ -110,7 +115,11 @@ public sealed class BlacklistService : IEarlyBehavior { var bc = uow.Blacklist; //blacklist the users - bc.AddRange(toBlacklist.Select(x => new BlacklistEntry { ItemId = x, Type = BlacklistType.User })); + bc.AddRange(toBlacklist.Select(x => new BlacklistEntry + { + ItemId = x, + Type = BlacklistType.User + })); //clear their currencies uow.DiscordUser.RemoveFromMany(toBlacklist); diff --git a/src/NadekoBot/Modules/Permissions/CommandCooldown/CmdCdService.cs b/src/NadekoBot/Modules/Permissions/CommandCooldown/CmdCdService.cs index 4a019c37e..7c8cb3e9e 100644 --- a/src/NadekoBot/Modules/Permissions/CommandCooldown/CmdCdService.cs +++ b/src/NadekoBot/Modules/Permissions/CommandCooldown/CmdCdService.cs @@ -28,9 +28,13 @@ public class CmdCdService : ILateBlocker, INService if (activeCdsForGuild.FirstOrDefault(ac => ac.UserId == user.Id && ac.Command == commandName) is not null) return Task.FromResult(true); - activeCdsForGuild.Add(new() { UserId = user.Id, Command = commandName }); + activeCdsForGuild.Add(new() + { + UserId = user.Id, + Command = commandName + }); - _= Task.Run(async () => + _ = Task.Run(async () => { try { diff --git a/src/NadekoBot/Modules/Permissions/CommandCooldown/CmdCdsCommands.cs b/src/NadekoBot/Modules/Permissions/CommandCooldown/CmdCdsCommands.cs index 86c09b5bc..9d05dcd1d 100644 --- a/src/NadekoBot/Modules/Permissions/CommandCooldown/CmdCdsCommands.cs +++ b/src/NadekoBot/Modules/Permissions/CommandCooldown/CmdCdsCommands.cs @@ -50,7 +50,11 @@ public partial class Permissions localSet.RemoveWhere(cc => cc.CommandName == name); if (secs != 0) { - var cc = new CommandCooldown { CommandName = name, Seconds = secs }; + var cc = new CommandCooldown + { + CommandName = name, + Seconds = secs + }; config.CommandCooldowns.Add(cc); localSet.Add(cc); } diff --git a/src/NadekoBot/Modules/Permissions/Filter/FilterCommands.cs b/src/NadekoBot/Modules/Permissions/Filter/FilterCommands.cs index 317d362c8..ed1fc7e1d 100644 --- a/src/NadekoBot/Modules/Permissions/Filter/FilterCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Filter/FilterCommands.cs @@ -62,7 +62,10 @@ public partial class Permissions { var config = uow.GuildConfigsForId(channel.Guild.Id, set => set.Include(gc => gc.FilterInvitesChannelIds)); - var match = new FilterChannelId { ChannelId = channel.Id }; + var match = new FilterChannelId + { + ChannelId = channel.Id + }; removed = config.FilterInvitesChannelIds.FirstOrDefault(fc => fc.Equals(match)); if (removed is null) @@ -121,7 +124,10 @@ public partial class Permissions { var config = uow.GuildConfigsForId(channel.Guild.Id, set => set.Include(gc => gc.FilterLinksChannelIds)); - var match = new FilterLinksChannelId { ChannelId = channel.Id }; + var match = new FilterLinksChannelId + { + ChannelId = channel.Id + }; removed = config.FilterLinksChannelIds.FirstOrDefault(fc => fc.Equals(match)); if (removed is null) @@ -181,7 +187,10 @@ public partial class Permissions var config = uow.GuildConfigsForId(channel.Guild.Id, set => set.Include(gc => gc.FilterWordsChannelIds)); - var match = new FilterWordsChannelId { ChannelId = channel.Id }; + var match = new FilterWordsChannelId + { + ChannelId = channel.Id + }; removed = config.FilterWordsChannelIds.FirstOrDefault(fc => fc.Equals(match)); if (removed is null) config.FilterWordsChannelIds.Add(match); @@ -221,7 +230,10 @@ public partial class Permissions removed = config.FilteredWords.FirstOrDefault(fw => fw.Word.Trim().ToLowerInvariant() == word); if (removed is null) - config.FilteredWords.Add(new() { Word = word }); + config.FilteredWords.Add(new() + { + Word = word + }); else uow.Remove(removed); diff --git a/src/NadekoBot/Modules/Permissions/Filter/FilterService.cs b/src/NadekoBot/Modules/Permissions/Filter/FilterService.cs index 79d72c6a5..a7f622bbd 100644 --- a/src/NadekoBot/Modules/Permissions/Filter/FilterService.cs +++ b/src/NadekoBot/Modules/Permissions/Filter/FilterService.cs @@ -62,7 +62,7 @@ public sealed class FilterService : IEarlyBehavior client.MessageUpdated += (oldData, newMsg, channel) => { - _= Task.Run(() => + _ = Task.Run(() => { var guild = (channel as ITextChannel)?.Guild; @@ -132,7 +132,6 @@ public sealed class FilterService : IEarlyBehavior var filteredServerWords = FilteredWordsForServer(guild.Id) ?? new ConcurrentHashSet(); var wordsInMessage = usrMsg.Content.ToLowerInvariant().Split(' '); if (filteredChannelWords.Count != 0 || filteredServerWords.Count != 0) - { foreach (var word in wordsInMessage) { if (filteredChannelWords.Contains(word) || filteredServerWords.Contains(word)) @@ -156,7 +155,6 @@ public sealed class FilterService : IEarlyBehavior return true; } } - } return false; } diff --git a/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs b/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs index 744e6ffda..b01582561 100644 --- a/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs +++ b/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs @@ -20,7 +20,8 @@ public static class PermissionExtensions var result = perm.CheckPermission(message, commandName, moduleName); - if (result is null) continue; + if (result is null) + continue; permIndex = i; return result.Value; } diff --git a/src/NadekoBot/Modules/Permissions/Permissions.cs b/src/NadekoBot/Modules/Permissions/Permissions.cs index 1a16d7934..0b2c2908e 100644 --- a/src/NadekoBot/Modules/Permissions/Permissions.cs +++ b/src/NadekoBot/Modules/Permissions/Permissions.cs @@ -24,7 +24,8 @@ public partial class Permissions : NadekoModule await using (var uow = _db.GetDbContext()) { var config = uow.GcWithPermissionsFor(ctx.Guild.Id); - if (action is null) action = new(!config.VerbosePermissions); // New behaviour, can toggle. + if (action is null) + action = new(!config.VerbosePermissions); // New behaviour, can toggle. config.VerbosePermissions = action.Value; await uow.SaveChangesAsync(); _service.UpdateCache(config); diff --git a/src/NadekoBot/Modules/Permissions/PermissionsService.cs b/src/NadekoBot/Modules/Permissions/PermissionsService.cs index 7363f94c3..e311d86d5 100644 --- a/src/NadekoBot/Modules/Permissions/PermissionsService.cs +++ b/src/NadekoBot/Modules/Permissions/PermissionsService.cs @@ -33,11 +33,15 @@ public class PermissionService : ILateBlocker, INService using var uow = _db.GetDbContext(); foreach (var x in uow.GuildConfigs.PermissionsForAll(client.Guilds.ToArray().Select(x => x.Id).ToList())) + { Cache.TryAdd(x.GuildId, new() { - Verbose = x.VerbosePermissions, PermRole = x.PermissionRole, Permissions = new(x.Permissions) + Verbose = x.VerbosePermissions, + PermRole = x.PermissionRole, + Permissions = new(x.Permissions) }); + } } public PermissionCache GetCacheFor(ulong guildId) @@ -99,7 +103,8 @@ public class PermissionService : ILateBlocker, INService var commandName = command.Name.ToLowerInvariant(); await Task.Yield(); - if (guild is null) return false; + if (guild is null) + return false; var resetCommand = commandName == "resetperms"; diff --git a/src/NadekoBot/Modules/Searches/Anime/AnimeSearchCommands.cs b/src/NadekoBot/Modules/Searches/Anime/AnimeSearchCommands.cs index 0885a52fc..e5c314e54 100644 --- a/src/NadekoBot/Modules/Searches/Anime/AnimeSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Anime/AnimeSearchCommands.cs @@ -38,9 +38,9 @@ public partial class Searches // await ctx.Channel.EmbedAsync(embed); // } - [NadekoCommand, Aliases] + [Cmd] [Priority(0)] - public async Task Mal([Leftover] string name) + public async partial Task Mal([Leftover] string name) { if (string.IsNullOrWhiteSpace(name)) return; diff --git a/src/NadekoBot/Modules/Searches/Crypto/CryptoCommands.cs b/src/NadekoBot/Modules/Searches/Crypto/CryptoCommands.cs index 603584fab..d7fee501d 100644 --- a/src/NadekoBot/Modules/Searches/Crypto/CryptoCommands.cs +++ b/src/NadekoBot/Modules/Searches/Crypto/CryptoCommands.cs @@ -24,7 +24,8 @@ public partial class Searches .WithDescription( GetText(strs.did_you_mean(Format.Bold($"{nearest.Name} ({nearest.Symbol})")))); - if (await PromptUserConfirmAsync(embed)) crypto = nearest; + if (await PromptUserConfirmAsync(embed)) + crypto = nearest; } if (crypto is null) @@ -43,7 +44,7 @@ public partial class Searches var volume = usd.Volume24h.ToString("n0", Culture); var marketCap = usd.MarketCap.ToString("n0", Culture); - + await ctx.Channel.EmbedAsync(_eb.Create() .WithOkColor() .WithAuthor($"#{crypto.CmcRank}") diff --git a/src/NadekoBot/Modules/Searches/Crypto/CryptoService.cs b/src/NadekoBot/Modules/Searches/Crypto/CryptoService.cs index cf8b97999..76b757129 100644 --- a/src/NadekoBot/Modules/Searches/Crypto/CryptoService.cs +++ b/src/NadekoBot/Modules/Searches/Crypto/CryptoService.cs @@ -67,7 +67,7 @@ public class CryptoService : INService + "&start=1" + "&limit=5000" + "&convert=USD"); - + return JsonSerializer.Serialize(strData); } catch (Exception ex) diff --git a/src/NadekoBot/Modules/Searches/Feeds/FeedCommands.cs b/src/NadekoBot/Modules/Searches/Feeds/FeedCommands.cs index 2635a5de7..ad8ca1d28 100644 --- a/src/NadekoBot/Modules/Searches/Feeds/FeedCommands.cs +++ b/src/NadekoBot/Modules/Searches/Feeds/FeedCommands.cs @@ -19,7 +19,8 @@ public partial class Searches public partial Task YtUploadNotif(string url, [Leftover] ITextChannel channel = null) { var m = _ytChannelRegex.Match(url); - if (!m.Success) return ReplyErrorLocalizedAsync(strs.invalid_input); + if (!m.Success) + return ReplyErrorLocalizedAsync(strs.invalid_input); var channelId = m.Groups["channelid"].Value; diff --git a/src/NadekoBot/Modules/Searches/Feeds/FeedsService.cs b/src/NadekoBot/Modules/Searches/Feeds/FeedsService.cs index 8c878c045..355686ca1 100644 --- a/src/NadekoBot/Modules/Searches/Feeds/FeedsService.cs +++ b/src/NadekoBot/Modules/Searches/Feeds/FeedsService.cs @@ -40,7 +40,7 @@ public class FeedsService : INService _client = client; _eb = eb; - _= Task.Run(TrackFeeds); + _ = Task.Run(TrackFeeds); } public async Task TrackFeeds() @@ -74,7 +74,8 @@ public class FeedsService : INService foreach (var (feedItem, itemUpdateDate) in items) { - if (itemUpdateDate <= lastFeedUpdate) continue; + if (itemUpdateDate <= lastFeedUpdate) + continue; var embed = _eb.Create().WithFooter(rssUrl); @@ -159,26 +160,36 @@ public class FeedsService : INService { ArgumentNullException.ThrowIfNull(rssFeed, nameof(rssFeed)); - var fs = new FeedSub { ChannelId = channelId, Url = rssFeed.Trim() }; + var fs = new FeedSub + { + ChannelId = channelId, + Url = rssFeed.Trim() + }; using var uow = _db.GetDbContext(); var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FeedSubs).ThenInclude(x => x.GuildConfig)); if (gc.FeedSubs.Any(x => x.Url.ToLower() == fs.Url.ToLower())) return false; - if (gc.FeedSubs.Count >= 10) return false; + if (gc.FeedSubs.Count >= 10) + return false; gc.FeedSubs.Add(fs); uow.SaveChanges(); //adding all, in case bot wasn't on this guild when it started foreach (var feed in gc.FeedSubs) + { _subs.AddOrUpdate(feed.Url.ToLower(), - new HashSet { feed }, + new HashSet + { + feed + }, (_, old) => { old.Add(feed); return old; }); + } return true; } diff --git a/src/NadekoBot/Modules/Searches/MemegenCommands.cs b/src/NadekoBot/Modules/Searches/MemegenCommands.cs index 2791c7b2d..71ee0315f 100644 --- a/src/NadekoBot/Modules/Searches/MemegenCommands.cs +++ b/src/NadekoBot/Modules/Searches/MemegenCommands.cs @@ -77,10 +77,12 @@ public partial class Searches var sb = new StringBuilder(); foreach (var c in input) + { if (_map.TryGetValue(c, out var tmp)) sb.Append(tmp); else sb.Append(c); + } return sb.ToString(); } diff --git a/src/NadekoBot/Modules/Searches/OsuCommands.cs b/src/NadekoBot/Modules/Searches/OsuCommands.cs index 7e83bc913..36e515458 100644 --- a/src/NadekoBot/Modules/Searches/OsuCommands.cs +++ b/src/NadekoBot/Modules/Searches/OsuCommands.cs @@ -129,7 +129,8 @@ public partial class Searches using var http = _httpFactory.CreateClient(); var m = 0; - if (!string.IsNullOrWhiteSpace(mode)) m = ResolveGameMode(mode); + if (!string.IsNullOrWhiteSpace(mode)) + m = ResolveGameMode(mode); var reqString = "https://osu.ppy.sh/api/get_user_best" + $"?k={_creds.OsuApiKey}" @@ -159,7 +160,8 @@ public partial class Searches var desc = $@"[/b/{item.BeatmapId}](https://osu.ppy.sh/b/{item.BeatmapId}) {pp + "pp",-7} | {acc + "%",-7} "; - if (mods != "+") desc += Format.Bold(mods); + if (mods != "+") + desc += Format.Bold(mods); return (title, desc); }); @@ -167,7 +169,8 @@ public partial class Searches var eb = _eb.Create().WithOkColor().WithTitle($"Top 5 plays for {user}"); var mapData = await mapTasks.WhenAll(); - foreach (var (title, desc) in mapData.Where(x => x != default)) eb.AddField(title, desc); + foreach (var (title, desc) in mapData.Where(x => x != default)) + eb.AddField(title, desc); await ctx.Channel.EmbedAsync(eb); } diff --git a/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs b/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs index 9058eabc8..7d886f09d 100644 --- a/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs +++ b/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs @@ -142,7 +142,8 @@ public partial class Searches return; } - if (!string.IsNullOrWhiteSpace(league)) characters.RemoveAll(c => c.League != league); + if (!string.IsNullOrWhiteSpace(league)) + characters.RemoveAll(c => c.League != league); await ctx.SendPaginatedConfirmAsync(page, curPage => @@ -155,7 +156,8 @@ public partial class Searches var tempList = characters.Skip(curPage * 9).Take(9).ToList(); - if (characters.Count == 0) return embed.WithDescription("This account has no characters."); + if (characters.Count == 0) + return embed.WithDescription("This account has no characters."); var sb = new StringBuilder(); sb.AppendLine($"```{"#",-5}{"Character Name",-23}{"League",-10}{"Class",-13}{"Level",-3}"); @@ -218,7 +220,10 @@ public partial class Searches } [Cmd] - public async partial Task PathOfExileCurrency(string leagueName, string currencyName, string convertName = "Chaos Orb") + public async partial Task PathOfExileCurrency( + string leagueName, + string currencyName, + string convertName = "Chaos Orb") { if (string.IsNullOrWhiteSpace(leagueName)) { @@ -293,7 +298,8 @@ public partial class Searches private string ShortCurrencyName(string str) { - if (currencyDictionary.ContainsValue(str)) return str; + if (currencyDictionary.ContainsValue(str)) + return str; var currency = currencyDictionary[str]; diff --git a/src/NadekoBot/Modules/Searches/PokemonSearchCommands.cs b/src/NadekoBot/Modules/Searches/PokemonSearchCommands.cs index 59ed37751..2b25f00ce 100644 --- a/src/NadekoBot/Modules/Searches/PokemonSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/PokemonSearchCommands.cs @@ -28,6 +28,7 @@ public partial class Searches return; foreach (var kvp in Pokemons) + { if (kvp.Key.ToUpperInvariant() == pokemon.ToUpperInvariant()) { var p = kvp.Value; @@ -46,6 +47,7 @@ public partial class Searches true)); return; } + } await ReplyErrorLocalizedAsync(strs.pokemon_none); } @@ -57,6 +59,7 @@ public partial class Searches if (string.IsNullOrWhiteSpace(ability)) return; foreach (var kvp in PokemonAbilities) + { if (kvp.Key.ToUpperInvariant() == ability) { await ctx.Channel.EmbedAsync(_eb.Create() @@ -70,6 +73,7 @@ public partial class Searches true)); return; } + } await ReplyErrorLocalizedAsync(strs.pokemon_ability_none); } diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index ae229e576..68a26f72e 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -218,6 +218,7 @@ public partial class Searches : NadekoModule var oterms = query?.Trim(); if (!await ValidateQuery(query)) return; + query = WebUtility.UrlEncode(oterms)?.Replace(' ', '+'); try { @@ -287,7 +288,10 @@ public partial class Searches : NadekoModule { using var http = _httpFactory.CreateClient(); using var req = new HttpRequestMessage(HttpMethod.Post, "https://goolnk.com/api/v1/shorten"); - var formData = new MultipartFormDataContent { { new StringContent(query), "url" } }; + var formData = new MultipartFormDataContent + { + { new StringContent(query), "url" } + }; req.Content = formData; using var res = await http.SendAsync(req); @@ -486,7 +490,7 @@ public partial class Searches : NadekoModule { e.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12); return http.GetStringAsync("https://api.pearson.com/v2/dictionaries/entries?headword=" - + WebUtility.UrlEncode(word)); + + WebUtility.UrlEncode(word)); }); var data = JsonConvert.DeserializeObject(res); @@ -572,6 +576,7 @@ public partial class Searches : NadekoModule if (string.IsNullOrWhiteSpace(imageLink)) return; + await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}"); } @@ -622,12 +627,6 @@ public partial class Searches : NadekoModule var avatarUrl = usr.RealAvatarUrl(2048); - if (avatarUrl is null) - { - await ReplyErrorLocalizedAsync(strs.avatar_none(usr.ToString())); - return; - } - await ctx.Channel.EmbedAsync( _eb.Create() .WithOkColor() @@ -737,7 +736,8 @@ public partial class Searches : NadekoModule private async Task ValidateQuery(string query) { - if (!string.IsNullOrWhiteSpace(query)) return true; + if (!string.IsNullOrWhiteSpace(query)) + return true; await ErrorLocalizedAsync(strs.specify_search_params); return false; diff --git a/src/NadekoBot/Modules/Searches/SearchesService.cs b/src/NadekoBot/Modules/Searches/SearchesService.cs index 5c2dbbd10..85165fd28 100644 --- a/src/NadekoBot/Modules/Searches/SearchesService.cs +++ b/src/NadekoBot/Modules/Searches/SearchesService.cs @@ -128,7 +128,8 @@ public class SearchesService : INService { TextOptions = new TextOptions { - HorizontalAlignment = HorizontalAlignment.Center, WrapTextWidth = 190 + HorizontalAlignment = HorizontalAlignment.Center, + WrapTextWidth = 190 }.WithFallbackFonts(_fonts.FallBackFonts) }, text, @@ -189,7 +190,8 @@ public class SearchesService : INService { query = query.Trim(); - if (string.IsNullOrEmpty(query)) return (default, TimeErrors.InvalidInput); + if (string.IsNullOrEmpty(query)) + return (default, TimeErrors.InvalidInput); if (string.IsNullOrWhiteSpace(_creds.LocationIqApiKey) || string.IsNullOrWhiteSpace(_creds.TimezoneDbApiKey)) return (default, TimeErrors.ApiKeyMissing); @@ -303,7 +305,12 @@ public class SearchesService : INService { using var http = _httpFactory.CreateClient(); var res = await http.GetStringAsync("https://official-joke-api.appspot.com/random_joke"); - var resObj = JsonConvert.DeserializeAnonymousType(res, new { setup = "", punchline = "" }); + var resObj = JsonConvert.DeserializeAnonymousType(res, + new + { + setup = "", + punchline = "" + }); return (resObj.setup, resObj.punchline); } @@ -395,7 +402,8 @@ public class SearchesService : INService ?? objs.FirstOrDefault(x => !string.IsNullOrEmpty(x.PlayerClass)) ?? objs.FirstOrDefault(); if (data is null) return null; - if (!string.IsNullOrWhiteSpace(data.Img)) data.Img = await _google.ShortenUrl(data.Img); + if (!string.IsNullOrWhiteSpace(data.Img)) + data.Img = await _google.ShortenUrl(data.Img); if (!string.IsNullOrWhiteSpace(data.Text)) { var converter = new Converter(); @@ -456,7 +464,14 @@ public class SearchesService : INService // https://api.steampowered.com/ISteamApps/GetAppList/v2/ var gamesStr = await http.GetStringAsync("https://api.steampowered.com/ISteamApps/GetAppList/v2/"); var apps = JsonConvert - .DeserializeAnonymousType(gamesStr, new { applist = new { apps = new List() } }) + .DeserializeAnonymousType(gamesStr, + new + { + applist = new + { + apps = new List() + } + }) .applist.apps; return apps.OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase) diff --git a/src/NadekoBot/Modules/Searches/StreamNotification/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/StreamNotification/StreamNotificationCommands.cs index c73acf2cf..891c833d0 100644 --- a/src/NadekoBot/Modules/Searches/StreamNotification/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/StreamNotification/StreamNotificationCommands.cs @@ -67,7 +67,8 @@ public partial class Searches [RequireContext(ContextType.Guild)] public async partial Task StreamList(int page = 1) { - if (page-- < 1) return; + if (page-- < 1) + return; var streams = new List(); await using (var uow = _db.GetDbContext()) diff --git a/src/NadekoBot/Modules/Searches/StreamNotification/StreamNotificationService.cs b/src/NadekoBot/Modules/Searches/StreamNotification/StreamNotificationService.cs index a6e192f5a..ca708ecf0 100644 --- a/src/NadekoBot/Modules/Searches/StreamNotification/StreamNotificationService.cs +++ b/src/NadekoBot/Modules/Searches/StreamNotification/StreamNotificationService.cs @@ -74,7 +74,11 @@ public sealed class StreamNotificationService : INService var followedStreams = guildConfigs.SelectMany(x => x.FollowedStreams).ToList(); - _shardTrackedStreams = followedStreams.GroupBy(x => new { x.Type, Name = x.Username.ToLower() }) + _shardTrackedStreams = followedStreams.GroupBy(x => new + { + x.Type, + Name = x.Username.ToLower() + }) .ToList() .ToDictionary( x => new StreamDataKey(x.Key.Type, x.Key.Name.ToLower()), @@ -87,9 +91,14 @@ public sealed class StreamNotificationService : INService { var allFollowedStreams = uow.Set().AsQueryable().ToList(); - foreach (var fs in allFollowedStreams) _streamTracker.CacheAddData(fs.CreateKey(), null, false); + foreach (var fs in allFollowedStreams) + _streamTracker.CacheAddData(fs.CreateKey(), null, false); - _trackCounter = allFollowedStreams.GroupBy(x => new { x.Type, Name = x.Username.ToLower() }) + _trackCounter = allFollowedStreams.GroupBy(x => new + { + x.Type, + Name = x.Username.ToLower() + }) .ToDictionary(x => new StreamDataKey(x.Key.Type, x.Key.Name), x => x.Select(fs => fs.GuildId).ToHashSet()); } @@ -171,7 +180,10 @@ public sealed class StreamNotificationService : INService if (_trackCounter.ContainsKey(key)) _trackCounter[key].Add(info.GuildId); else - _trackCounter[key] = new() { info.GuildId }; + _trackCounter[key] = new() + { + info.GuildId + }; } return default; @@ -351,10 +363,20 @@ public sealed class StreamNotificationService : INService } private void PublishFollowStream(FollowedStream fs) - => _pubSub.Pub(_streamFollowKey, new() { Key = fs.CreateKey(), GuildId = fs.GuildId }); + => _pubSub.Pub(_streamFollowKey, + new() + { + Key = fs.CreateKey(), + GuildId = fs.GuildId + }); private Task PublishUnfollowStream(FollowedStream fs) - => _pubSub.Pub(_streamUnfollowKey, new() { Key = fs.CreateKey(), GuildId = fs.GuildId }); + => _pubSub.Pub(_streamUnfollowKey, + new() + { + Key = fs.CreateKey(), + GuildId = fs.GuildId + }); public async Task FollowStream(ulong guildId, ulong channelId, string url) { @@ -370,7 +392,13 @@ public sealed class StreamNotificationService : INService var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FollowedStreams)); // add it to the database - fs = new() { Type = data.StreamType, Username = data.UniqueName, ChannelId = channelId, GuildId = guildId }; + fs = new() + { + Type = data.StreamType, + Username = data.UniqueName, + ChannelId = channelId, + GuildId = guildId + }; if (gc.FollowedStreams.Count >= 10) return null; @@ -454,7 +482,10 @@ public sealed class StreamNotificationService : INService return map[guildId] = new(); } - _shardTrackedStreams[key] = new() { { guildId, new() } }; + _shardTrackedStreams[key] = new() + { + { guildId, new() } + }; return _shardTrackedStreams[key][guildId]; } diff --git a/src/NadekoBot/Modules/Searches/Translate/TranslateService.cs b/src/NadekoBot/Modules/Searches/Translate/TranslateService.cs index ee2c65d9e..a148d7ef1 100644 --- a/src/NadekoBot/Modules/Searches/Translate/TranslateService.cs +++ b/src/NadekoBot/Modules/Searches/Translate/TranslateService.cs @@ -110,7 +110,12 @@ public sealed class TranslateService : ITranslateService, ILateExecutor, IReadyE if (old is null) { - ctx.AutoTranslateChannels.Add(new() { GuildId = guildId, ChannelId = channelId, AutoDelete = autoDelete }); + ctx.AutoTranslateChannels.Add(new() + { + GuildId = guildId, + ChannelId = channelId, + AutoDelete = autoDelete + }); await ctx.SaveChangesAsync(); @@ -169,7 +174,12 @@ public sealed class TranslateService : ITranslateService, ILateExecutor, IReadyE if (user is null) { - ch.Users.Add(user = new() { Source = from, Target = to, UserId = userId }); + ch.Users.Add(user = new() + { + Source = from, + Target = to, + UserId = userId + }); await ctx.SaveChangesAsync(); diff --git a/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/NotifChecker.cs b/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/NotifChecker.cs index 31cc473c2..cb747b3d9 100644 --- a/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/NotifChecker.cs +++ b/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/NotifChecker.cs @@ -31,7 +31,8 @@ public class NotifChecker { FollowedStream.FType.Trovo, new TrovoProvider(httpClientFactory, credsProvider) } }; _offlineBuffer = new(); - if (isMaster) CacheClearAllData(); + if (isMaster) + CacheClearAllData(); } // gets all streams which have been failing for more than the provided timespan @@ -45,12 +46,8 @@ public class NotifChecker .ToList(); if (remove) - { foreach (var toBeRemoved in toReturn) - { _streamProviders[toBeRemoved.Type].ClearErrorsFor(toBeRemoved.Name); - } - } return toReturn; } @@ -137,9 +134,11 @@ public class NotifChecker Task.Delay(30_000) }; - if (newlyOnline.Count > 0) tasks.Add(OnStreamsOnline(newlyOnline)); + if (newlyOnline.Count > 0) + tasks.Add(OnStreamsOnline(newlyOnline)); - if (newlyOffline.Count > 0) tasks.Add(OnStreamsOffline(newlyOffline)); + if (newlyOffline.Count > 0) + tasks.Add(OnStreamsOffline(newlyOffline)); await Task.WhenAll(tasks); } @@ -174,7 +173,8 @@ public class NotifChecker public Dictionary CacheGetAllData() { var db = _multi.GetDatabase(); - if (!db.KeyExists(_key)) return new(); + if (!db.KeyExists(_key)) + return new(); return db.HashGetAll(_key) .ToDictionary(entry => JsonConvert.DeserializeObject(entry.Name), diff --git a/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/PicartoProvider.cs b/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/PicartoProvider.cs index cdf178b87..5c8248a7d 100644 --- a/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/PicartoProvider.cs +++ b/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/PicartoProvider.cs @@ -41,7 +41,10 @@ public class PicartoProvider : Provider public override async Task GetStreamDataAsync(string id) { - var data = await GetStreamDataAsync(new List { id }); + var data = await GetStreamDataAsync(new List + { + id + }); return data.FirstOrDefault(); } @@ -54,6 +57,7 @@ public class PicartoProvider : Provider using var http = _httpClientFactory.CreateClient(); var toReturn = new List(); foreach (var login in logins) + { try { http.DefaultRequestHeaders.Accept.Add(new("application/json")); @@ -77,6 +81,7 @@ public class PicartoProvider : Provider ex.Message); _failingStreams.TryAdd(login, DateTime.UtcNow); } + } return toReturn; } diff --git a/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/TrovoProvider.cs b/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/TrovoProvider.cs index c648d5dd1..2e65c3177 100644 --- a/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/TrovoProvider.cs +++ b/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/TrovoProvider.cs @@ -11,8 +11,7 @@ public class TrovoProvider : Provider public override FollowedStream.FType Platform => FollowedStream.FType.Trovo; - private readonly Regex _urlRegex - = new Regex(@"trovo.live\/(?[\w\d\-_]+)/?", RegexOptions.Compiled); + private readonly Regex _urlRegex = new(@"trovo.live\/(?[\w\d\-_]+)/?", RegexOptions.Compiled); private readonly IBotCredsProvider _creds; @@ -40,12 +39,12 @@ public class TrovoProvider : Provider if (string.IsNullOrWhiteSpace(trovoClientId)) trovoClientId = "waiting for key"; - - + + http.DefaultRequestHeaders.Clear(); http.DefaultRequestHeaders.Add("Accept", "application/json"); http.DefaultRequestHeaders.Add("Client-ID", trovoClientId); - + // trovo ratelimit is very generous (1200 per minute) // so there is no need for ratelimit checks atm try @@ -60,7 +59,7 @@ public class TrovoProvider : Provider res.EnsureSuccessStatusCode(); var data = await res.Content.ReadFromJsonAsync(); - + if (data is null) { Log.Warning("An empty response received while retrieving stream data for trovo.live/{TrovoId}", id); @@ -79,7 +78,7 @@ public class TrovoProvider : Provider StreamType = FollowedStream.FType.Picarto, StreamUrl = data.ChannelUrl, UniqueName = data.Username, - Preview = data.Thumbnail, + Preview = data.Thumbnail }; } catch (Exception ex) diff --git a/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/TwitchProvider.cs b/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/TwitchProvider.cs index 226dcb73d..64950bfbf 100644 --- a/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/TwitchProvider.cs +++ b/src/NadekoBot/Modules/Searches/_Common/StreamNotifications/Providers/TwitchProvider.cs @@ -66,6 +66,7 @@ public class TwitchProvider : Provider var toReturn = new List(); foreach (var login in logins) + { try { // get id based on the username @@ -117,6 +118,7 @@ public class TwitchProvider : Provider ex.Message); _failingStreams.TryAdd(login, DateTime.UtcNow); } + } return toReturn; } diff --git a/src/NadekoBot/Modules/Utility/CommandMap/CommandMapCommands.cs b/src/NadekoBot/Modules/Utility/CommandMap/CommandMapCommands.cs index 2c26ae5c0..362a9b3b7 100644 --- a/src/NadekoBot/Modules/Utility/CommandMap/CommandMapCommands.cs +++ b/src/NadekoBot/Modules/Utility/CommandMap/CommandMapCommands.cs @@ -66,7 +66,11 @@ public partial class Utility using (var uow = _db.GetDbContext()) { var config = uow.GuildConfigsForId(ctx.Guild.Id, set => set.Include(x => x.CommandAliases)); - config.CommandAliases.Add(new() { Mapping = mapping, Trigger = trigger }); + config.CommandAliases.Add(new() + { + Mapping = mapping, + Trigger = trigger + }); uow.SaveChanges(); } @@ -80,7 +84,11 @@ public partial class Utility using (var uow = _db.GetDbContext()) { var config = uow.GuildConfigsForId(ctx.Guild.Id, set => set.Include(x => x.CommandAliases)); - var toAdd = new CommandAlias { Mapping = mapping, Trigger = trigger }; + var toAdd = new CommandAlias + { + Mapping = mapping, + Trigger = trigger + }; var toRemove = config.CommandAliases.Where(x => x.Trigger == trigger).ToArray(); if (toRemove.Any()) uow.RemoveRange(toRemove); diff --git a/src/NadekoBot/Modules/Utility/CommandMap/CommandMapService.cs b/src/NadekoBot/Modules/Utility/CommandMap/CommandMapService.cs index 9db69d29d..027e6f93c 100644 --- a/src/NadekoBot/Modules/Utility/CommandMap/CommandMapService.cs +++ b/src/NadekoBot/Modules/Utility/CommandMap/CommandMapService.cs @@ -74,10 +74,13 @@ public class CommandMapService : IInputTransformer, INService try { var toDelete = await channel.SendConfirmAsync(_eb, $"{input} => {newInput}"); - _= Task.Run(async () => + _ = Task.Run(async () => { await Task.Delay(1500); - await toDelete.DeleteAsync(new() { RetryMode = RetryMode.AlwaysRetry }); + await toDelete.DeleteAsync(new() + { + RetryMode = RetryMode.AlwaysRetry + }); }); } catch { } diff --git a/src/NadekoBot/Modules/Utility/ConfigCommands.cs b/src/NadekoBot/Modules/Utility/ConfigCommands.cs index 98045b598..b358c73f1 100644 --- a/src/NadekoBot/Modules/Utility/ConfigCommands.cs +++ b/src/NadekoBot/Modules/Utility/ConfigCommands.cs @@ -107,7 +107,8 @@ public partial class Utility if (string.IsNullOrWhiteSpace(value)) value = "-"; - if (prop != "currency.sign") value = Format.Code(Format.Sanitize(value.TrimTo(1000)), "json"); + if (prop != "currency.sign") + value = Format.Code(Format.Sanitize(value.TrimTo(1000)), "json"); var embed = _eb.Create() .WithOkColor() @@ -137,12 +138,13 @@ public partial class Utility private string GetPropsAndValuesString(IConfigService config, IReadOnlyCollection names) { var propValues = names.Select(pr => - { - var val = config.GetSetting(pr); - if (pr != "currency.sign") - val = val?.TrimTo(28); - return val?.Replace("\n", "") ?? "-"; - }).ToList(); + { + var val = config.GetSetting(pr); + if (pr != "currency.sign") + val = val?.TrimTo(28); + return val?.Replace("\n", "") ?? "-"; + }) + .ToList(); var strings = names.Zip(propValues, (name, value) => $"{name,-25} = {value}\n"); diff --git a/src/NadekoBot/Modules/Utility/Info/InfoCommands.cs b/src/NadekoBot/Modules/Utility/Info/InfoCommands.cs index b749e9fcd..c6f1f9c04 100644 --- a/src/NadekoBot/Modules/Utility/Info/InfoCommands.cs +++ b/src/NadekoBot/Modules/Utility/Info/InfoCommands.cs @@ -21,12 +21,12 @@ public partial class Utility [OwnerOnly] public partial Task ServerInfo([Leftover] string guildName) => InternalServerInfo(guildName); - + [Cmd] [RequireContext(ContextType.Guild)] public partial Task ServerInfo() => InternalServerInfo(); - + private async Task InternalServerInfo(string guildName = null) { var channel = (ITextChannel)ctx.Channel; @@ -101,7 +101,8 @@ public partial class Utility return; var embed = _eb.Create().AddField(GetText(strs.name), $"**{user.Username}**#{user.Discriminator}", true); - if (!string.IsNullOrWhiteSpace(user.Nickname)) embed.AddField(GetText(strs.nickname), user.Nickname, true); + if (!string.IsNullOrWhiteSpace(user.Nickname)) + embed.AddField(GetText(strs.nickname), user.Nickname, true); embed.AddField(GetText(strs.id), user.Id.ToString(), true) .AddField(GetText(strs.joined_server), $"{user.JoinedAt?.ToString("dd.MM.yyyy HH:mm") ?? "?"}", true) .AddField(GetText(strs.joined_discord), $"{user.CreatedAt:dd.MM.yyyy HH:mm}", true) @@ -131,12 +132,14 @@ public partial class Utility var str = new StringBuilder(); foreach (var kvp in _cmdHandler.UserMessagesSent.OrderByDescending(kvp => kvp.Value) - .Skip(page * activityPerPage) - .Take(activityPerPage)) + .Skip(page * activityPerPage) + .Take(activityPerPage)) + { str.AppendLine(GetText(strs.activity_line(++startCount, Format.Bold(kvp.Key.ToString()), kvp.Value / _stats.GetUptime().TotalSeconds, kvp.Value))); + } await ctx.Channel.EmbedAsync(_eb.Create() .WithTitle(GetText(strs.activity_page(page + 1))) diff --git a/src/NadekoBot/Modules/Utility/Patreon/PatreonRewardsService.cs b/src/NadekoBot/Modules/Utility/Patreon/PatreonRewardsService.cs index 358c890f3..28e5455e9 100644 --- a/src/NadekoBot/Modules/Utility/Patreon/PatreonRewardsService.cs +++ b/src/NadekoBot/Modules/Utility/Patreon/PatreonRewardsService.cs @@ -51,7 +51,7 @@ public class PatreonRewardsService : INService, IReadyExecutor { if (_client.ShardId != 0) return; - + var t = new PeriodicTimer(Interval); do { @@ -133,7 +133,7 @@ public class PatreonRewardsService : INService, IReadyExecutor var lastUpdate = LastAccessTokenUpdate(creds); var now = DateTime.UtcNow; - + if (lastUpdate.Year != now.Year || lastUpdate.Month != now.Month || string.IsNullOrWhiteSpace(creds.Patreon.AccessToken)) @@ -143,7 +143,7 @@ public class PatreonRewardsService : INService, IReadyExecutor // -> update access token if (!HasPatreonCreds(creds)) return; - + var success = await UpdateAccessToken(creds); if (!success) return; @@ -198,7 +198,8 @@ public class PatreonRewardsService : INService, IReadyExecutor }) .ToList(); - foreach (var pledge in userData) await ClaimReward(pledge.UserId, pledge.PatreonUserId, pledge.EntitledTo); + foreach (var pledge in userData) + await ClaimReward(pledge.UserId, pledge.PatreonUserId, pledge.EntitledTo); } catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Unauthorized) { @@ -229,7 +230,9 @@ public class PatreonRewardsService : INService, IReadyExecutor { users.Add(new() { - PatreonUserId = patreonUserId, LastReward = now, AmountRewardedThisMonth = eligibleFor + PatreonUserId = patreonUserId, + LastReward = now, + AmountRewardedThisMonth = eligibleFor }); await uow.SaveChangesAsync(); diff --git a/src/NadekoBot/Modules/Utility/Quote/QuoteCommands.cs b/src/NadekoBot/Modules/Utility/Quote/QuoteCommands.cs index 798e30e6c..f7596ddea 100644 --- a/src/NadekoBot/Modules/Utility/Quote/QuoteCommands.cs +++ b/src/NadekoBot/Modules/Utility/Quote/QuoteCommands.cs @@ -62,16 +62,12 @@ public partial class Utility } if (quotes.Any()) - { await SendConfirmAsync(GetText(strs.quotes_page(page + 1)), string.Join("\n", quotes.Select(q => $"`#{q.Id}` {Format.Bold(q.Keyword.SanitizeAllMentions()),-20} by {q.AuthorName.SanitizeAllMentions()}"))); - } else - { await ReplyErrorLocalizedAsync(strs.quotes_page_none); - } } [Cmd] @@ -281,7 +277,7 @@ public partial class Utility } var exprsDict = quotes.GroupBy(x => x.Keyword) - .ToDictionary(x => x.Key, x => x.Select(ExportedQuote.FromModel)); + .ToDictionary(x => x.Key, x => x.Select(ExportedQuote.FromModel)); var text = PREPEND_EXPORT + _exportSerializer.Serialize(exprsDict).UnescapeUnicodeCodePoints(); @@ -374,7 +370,10 @@ public partial class Utility public static ExportedQuote FromModel(Quote quote) => new() { - Id = ((kwum)quote.Id).ToString(), An = quote.AuthorName, Aid = quote.AuthorId, Txt = quote.Text + Id = ((kwum)quote.Id).ToString(), + An = quote.AuthorName, + Aid = quote.AuthorId, + Txt = quote.Text }; } } diff --git a/src/NadekoBot/Modules/Utility/Remind/RemindCommands.cs b/src/NadekoBot/Modules/Utility/Remind/RemindCommands.cs index b432c0393..9918218f9 100644 --- a/src/NadekoBot/Modules/Utility/Remind/RemindCommands.cs +++ b/src/NadekoBot/Modules/Utility/Remind/RemindCommands.cs @@ -50,7 +50,8 @@ public partial class Utility if (!await RemindInternal(target, meorhere == MeOrHere.Me || ctx.Guild is null, remindData.Time, - remindData.What)) await ReplyErrorLocalizedAsync(strs.remind_too_long); + remindData.What)) + await ReplyErrorLocalizedAsync(strs.remind_too_long); } [Cmd] @@ -184,7 +185,8 @@ public partial class Utility if (ctx.Guild is not null) { var perms = ((IGuildUser)ctx.User).GetPermissions((IGuildChannel)ctx.Channel); - if (!perms.MentionEveryone) message = message.SanitizeAllMentions(); + if (!perms.MentionEveryone) + message = message.SanitizeAllMentions(); } var rem = new Reminder diff --git a/src/NadekoBot/Modules/Utility/Remind/RemindService.cs b/src/NadekoBot/Modules/Utility/Remind/RemindService.cs index d9b70c798..f9eb9d6b9 100644 --- a/src/NadekoBot/Modules/Utility/Remind/RemindService.cs +++ b/src/NadekoBot/Modules/Utility/Remind/RemindService.cs @@ -65,8 +65,8 @@ public class RemindService : INService { await using var uow = _db.GetDbContext(); await uow.Reminders - .ToLinqToDBTable() - .DeleteAsync(x => reminders.Contains(x.Id)); + .ToLinqToDBTable() + .DeleteAsync(x => reminders.Contains(x.Id)); await uow.SaveChangesAsync(); } @@ -76,7 +76,7 @@ public class RemindService : INService using var uow = _db.GetDbContext(); return uow.Reminders .ToLinqToDBTable() - .Where(x => (x.ServerId / 4194304 % (ulong)_creds.TotalShards == (ulong)_client.ShardId) + .Where(x => x.ServerId / 4194304 % (ulong)_creds.TotalShards == (ulong)_client.ShardId && x.When < now) // .FromSqlInterpolated( // $"select * from reminders where ((serverid >> 22) % {_creds.TotalShards}) == {_client.ShardId} and \"when\" < {now};") @@ -88,7 +88,8 @@ public class RemindService : INService var m = _regex.Match(input); obj = default; - if (m.Length == 0) return false; + if (m.Length == 0) + return false; var values = new Dictionary(); @@ -102,7 +103,8 @@ public class RemindService : INService foreach (var groupName in _regex.GetGroupNames()) { - if (groupName is "0" or "what") continue; + if (groupName is "0" or "what") + continue; if (string.IsNullOrWhiteSpace(m.Groups[groupName].Value)) { values[groupName] = 0; @@ -126,7 +128,11 @@ public class RemindService : INService var ts = new TimeSpan((30 * values["mo"]) + (7 * values["w"]) + values["d"], values["h"], values["m"], 0); - obj = new() { Time = ts, What = what }; + obj = new() + { + Time = ts, + What = what + }; return true; } diff --git a/src/NadekoBot/Modules/Utility/Repeater/RepeatCommands.cs b/src/NadekoBot/Modules/Utility/Repeater/RepeatCommands.cs index 02ae8da27..fd51ae033 100644 --- a/src/NadekoBot/Modules/Utility/Repeater/RepeatCommands.cs +++ b/src/NadekoBot/Modules/Utility/Repeater/RepeatCommands.cs @@ -18,7 +18,8 @@ public partial class Utility return; var success = await _service.TriggerExternal(ctx.Guild.Id, index); - if (!success) await ReplyErrorLocalizedAsync(strs.repeat_invoke_none); + if (!success) + await ReplyErrorLocalizedAsync(strs.repeat_invoke_none); } [Cmd] diff --git a/src/NadekoBot/Modules/Utility/Repeater/RepeaterService.cs b/src/NadekoBot/Modules/Utility/Repeater/RepeaterService.cs index 73fdd8679..dbc077c0e 100644 --- a/src/NadekoBot/Modules/Utility/Repeater/RepeaterService.cs +++ b/src/NadekoBot/Modules/Utility/Repeater/RepeaterService.cs @@ -29,7 +29,7 @@ public sealed class RepeaterService : IReadyExecutor, INService var uow = _db.GetDbContext(); var shardRepeaters = uow.Set() - .Where(x => ((int)(x.GuildId / Math.Pow(2, 22)) % _creds.TotalShards) + .Where(x => (int)(x.GuildId / Math.Pow(2, 22)) % _creds.TotalShards == _client.ShardId) .AsNoTracking() .ToList(); @@ -80,10 +80,12 @@ public sealed class RepeaterService : IReadyExecutor, INService } // execute - foreach (var chunk in toExecute.Chunk(5)) await chunk.Select(Trigger).WhenAll(); + foreach (var chunk in toExecute.Chunk(5)) + await chunk.Select(Trigger).WhenAll(); // reinsert - foreach (var rep in toExecute) await HandlePostExecute(rep); + foreach (var rep in toExecute) + await HandlePostExecute(rep); } catch (Exception ex) { @@ -227,7 +229,8 @@ public sealed class RepeaterService : IReadyExecutor, INService try { var oldMsg = await channel.GetMessageAsync(lastMessageId); - if (oldMsg is not null) await oldMsg.DeleteAsync(); + if (oldMsg is not null) + await oldMsg.DeleteAsync(); } catch (Exception ex) { @@ -289,7 +292,10 @@ public sealed class RepeaterService : IReadyExecutor, INService await using var uow = _db.GetDbContext(); await uow.Repeaters.AsQueryable() .Where(x => x.Id == repeaterId) - .UpdateAsync(rep => new() { LastMessageId = lastMsgId }); + .UpdateAsync(rep => new() + { + LastMessageId = lastMsgId + }); } public async Task AddRepeaterAsync( diff --git a/src/NadekoBot/Modules/Utility/Repeater/RunningRepeater.cs b/src/NadekoBot/Modules/Utility/Repeater/RunningRepeater.cs index 8a737db95..97009da61 100644 --- a/src/NadekoBot/Modules/Utility/Repeater/RunningRepeater.cs +++ b/src/NadekoBot/Modules/Utility/Repeater/RunningRepeater.cs @@ -60,7 +60,8 @@ public sealed class RunningRepeater { // if the initial time is greater than now, that means the repeater didn't still execute a single time. // just schedule it - if (initialDateTime > DateTime.UtcNow) return initialDateTime; + if (initialDateTime > DateTime.UtcNow) + return initialDateTime; // else calculate based on minutes difference diff --git a/src/NadekoBot/Modules/Utility/StreamRole/StreamRoleService.cs b/src/NadekoBot/Modules/Utility/StreamRole/StreamRoleService.cs index ef2721b63..871cf0f7f 100644 --- a/src/NadekoBot/Modules/Utility/StreamRole/StreamRoleService.cs +++ b/src/NadekoBot/Modules/Utility/StreamRole/StreamRoleService.cs @@ -19,12 +19,12 @@ public class StreamRoleService : INService _client = client; _guildSettings = bot.AllGuildConfigs.ToDictionary(x => x.GuildId, x => x.StreamRole) - .Where(x => x.Value is { Enabled: true }) - .ToConcurrent(); + .Where(x => x.Value is { Enabled: true }) + .ToConcurrent(); _client.GuildMemberUpdated += Client_GuildMemberUpdated; - _= Task.Run(async () => + _ = Task.Run(async () => { try { @@ -39,10 +39,11 @@ public class StreamRoleService : INService private Task Client_GuildMemberUpdated(Cacheable cacheable, SocketGuildUser after) { - _= Task.Run(async () => + _ = Task.Run(async () => { //if user wasn't streaming or didn't have a game status at all - if (_guildSettings.TryGetValue(after.Guild.Id, out var setting)) await RescanUser(after, setting); + if (_guildSettings.TryGetValue(after.Guild.Id, out var setting)) + await RescanUser(after, setting); }); return Task.CompletedTask; @@ -73,7 +74,11 @@ public class StreamRoleService : INService if (listType == StreamRoleListType.Whitelist) { - var userObj = new StreamRoleWhitelistedUser { UserId = userId, Username = userName }; + var userObj = new StreamRoleWhitelistedUser + { + UserId = userId, + Username = userName + }; if (action == AddRemove.Rem) { @@ -91,15 +96,17 @@ public class StreamRoleService : INService } else { - var userObj = new StreamRoleBlacklistedUser { UserId = userId, Username = userName }; + var userObj = new StreamRoleBlacklistedUser + { + UserId = userId, + Username = userName + }; if (action == AddRemove.Rem) { var toRemove = streamRoleSettings.Blacklist.FirstOrDefault(x => x.Equals(userObj)); if (toRemove is not null) - { success = streamRoleSettings.Blacklist.Remove(toRemove); - } } else { @@ -111,7 +118,8 @@ public class StreamRoleService : INService UpdateCache(guild.Id, streamRoleSettings); } - if (success) await RescanUsers(guild); + if (success) + await RescanUsers(guild); return success; } @@ -186,8 +194,10 @@ public class StreamRoleService : INService UpdateCache(fromRole.Guild.Id, setting); foreach (var usr in await fromRole.GetMembersAsync()) + { if (usr is { } x) await RescanUser(x, setting, addRole); + } } /// @@ -294,8 +304,10 @@ public class StreamRoleService : INService var users = await guild.GetUsersAsync(CacheMode.CacheOnly); foreach (var usr in users.Where(x => x.RoleIds.Contains(setting.FromRoleId) || x.RoleIds.Contains(addRole.Id))) + { if (usr is { } x) await RescanUser(x, setting, addRole); + } } } diff --git a/src/NadekoBot/Modules/Utility/UnitConversion/ConverterService.cs b/src/NadekoBot/Modules/Utility/UnitConversion/ConverterService.cs index 8470a8cdb..3a55d3509 100644 --- a/src/NadekoBot/Modules/Utility/UnitConversion/ConverterService.cs +++ b/src/NadekoBot/Modules/Utility/UnitConversion/ConverterService.cs @@ -57,11 +57,15 @@ public class ConverterService : INService, IReadyExecutor var currencyRates = await GetCurrencyRates(); var baseType = new ConvertUnit { - Triggers = new[] { currencyRates.Base }, Modifier = decimal.One, UnitType = unitTypeString + Triggers = new[] { currencyRates.Base }, + Modifier = decimal.One, + UnitType = unitTypeString }; var range = currencyRates.ConversionRates.Select(u => new ConvertUnit { - Triggers = new[] { u.Key }, Modifier = u.Value, UnitType = unitTypeString + Triggers = new[] { u.Key }, + Modifier = u.Value, + UnitType = unitTypeString }) .ToArray(); diff --git a/src/NadekoBot/Modules/Utility/UnitConversion/UnitConversionCommands.cs b/src/NadekoBot/Modules/Utility/UnitConversion/UnitConversionCommands.cs index c604b035a..54dde93ea 100644 --- a/src/NadekoBot/Modules/Utility/UnitConversion/UnitConversionCommands.cs +++ b/src/NadekoBot/Modules/Utility/UnitConversion/UnitConversionCommands.cs @@ -9,7 +9,7 @@ public partial class Utility public partial class UnitConverterCommands : NadekoSubmodule { [Cmd] - public async partial Task ConvertList() + public async partial Task ConvertList() { var units = _service.Units; @@ -17,8 +17,10 @@ public partial class Utility foreach (var g in units.GroupBy(x => x.UnitType)) + { embed.AddField(g.Key.ToTitleCase(), string.Join(", ", g.Select(x => x.Triggers.FirstOrDefault()).OrderBy(x => x))); + } await ctx.Channel.EmbedAsync(embed); } diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index 73f43bebd..cebd87fb5 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -117,7 +117,7 @@ public partial class Utility : NadekoModule await _tracker.EnsureUsersDownloadedAsync(ctx.Guild); var users = await ctx.Guild.GetUsersAsync( - CacheMode.CacheOnly + CacheMode.CacheOnly ); var roleUsers = users.Where(u => role is null ? u.RoleIds.Count == 1 : u.RoleIds.Contains(role.Id)) diff --git a/src/NadekoBot/Modules/Utility/VerboseErrors/VerboseErrorsService.cs b/src/NadekoBot/Modules/Utility/VerboseErrors/VerboseErrorsService.cs index bf53dbf5c..8924e70cf 100644 --- a/src/NadekoBot/Modules/Utility/VerboseErrors/VerboseErrorsService.cs +++ b/src/NadekoBot/Modules/Utility/VerboseErrors/VerboseErrorsService.cs @@ -54,7 +54,8 @@ public class VerboseErrorsService : INService if (enabled == null) enabled = gc.VerboseErrors = !gc.VerboseErrors; // Old behaviour, now behind a condition - else gc.VerboseErrors = (bool)enabled; // New behaviour, just set it. + else + gc.VerboseErrors = (bool)enabled; // New behaviour, just set it. uow.SaveChanges(); } diff --git a/src/NadekoBot/Modules/Xp/Club/Club.cs b/src/NadekoBot/Modules/Xp/Club/Club.cs index ec2d7d582..566d83d7f 100644 --- a/src/NadekoBot/Modules/Xp/Club/Club.cs +++ b/src/NadekoBot/Modules/Xp/Club/Club.cs @@ -337,7 +337,8 @@ public partial class Xp var embed = _eb.Create().WithTitle(GetText(strs.club_leaderboard(page + 1))).WithOkColor(); var i = page * 9; - foreach (var club in clubs) embed.AddField($"#{++i} " + club, club.Xp + " xp"); + foreach (var club in clubs) + embed.AddField($"#{++i} " + club, club.Xp + " xp"); return ctx.Channel.EmbedAsync(embed); } diff --git a/src/NadekoBot/Modules/Xp/Club/ClubService.cs b/src/NadekoBot/Modules/Xp/Club/ClubService.cs index d67acca33..dd490910b 100644 --- a/src/NadekoBot/Modules/Xp/Club/ClubService.cs +++ b/src/NadekoBot/Modules/Xp/Club/ClubService.cs @@ -28,7 +28,12 @@ public class ClubService : INService if (xp.Level >= 5 && du.Club is null) { du.IsClubAdmin = true; - du.Club = new() { Name = clubName, Discrim = uow.Clubs.GetNextDiscrim(clubName), Owner = du }; + du.Club = new() + { + Name = clubName, + Discrim = uow.Clubs.GetNextDiscrim(clubName), + Owner = du + }; uow.Clubs.Add(du.Club); uow.SaveChanges(); } @@ -142,7 +147,11 @@ public class ClubService : INService // or doesn't min minumum level requirement, can't apply return false; - var app = new ClubApplicants { ClubId = club.Id, UserId = du.Id }; + var app = new ClubApplicants + { + ClubId = club.Id, + UserId = du.Id + }; uow.Set().Add(app); @@ -254,7 +263,11 @@ public class ClubService : INService || (usr.IsClubAdmin && club.Owner.UserId != bannerId)) // can't ban the owner kek, whew return false; - club.Bans.Add(new() { Club = club, User = usr }); + club.Bans.Add(new() + { + Club = club, + User = usr + }); club.Users.Remove(usr); var app = club.Applicants.FirstOrDefault(x => x.UserId == usr.Id); diff --git a/src/NadekoBot/Modules/Xp/Xp.cs b/src/NadekoBot/Modules/Xp/Xp.cs index 4c7349e5c..0a7089871 100644 --- a/src/NadekoBot/Modules/Xp/Xp.cs +++ b/src/NadekoBot/Modules/Xp/Xp.cs @@ -164,9 +164,11 @@ public partial class Xp : NadekoModule private string GetNotifLocationString(XpNotificationLocation loc) { - if (loc == XpNotificationLocation.Channel) return GetText(strs.xpn_notif_channel); + if (loc == XpNotificationLocation.Channel) + return GetText(strs.xpn_notif_channel); - if (loc == XpNotificationLocation.Dm) return GetText(strs.xpn_notif_dm); + if (loc == XpNotificationLocation.Dm) + return GetText(strs.xpn_notif_dm); return GetText(strs.xpn_notif_disabled); } @@ -323,7 +325,8 @@ public partial class Xp : NadekoModule else users = _service.GetUserXps(ctx.Guild.Id, curPage); - if (!users.Any()) return embed.WithDescription("-"); + if (!users.Any()) + return embed.WithDescription("-"); for (var i = 0; i < users.Count; i++) { diff --git a/src/NadekoBot/Modules/Xp/XpConfigService.cs b/src/NadekoBot/Modules/Xp/XpConfigService.cs index 3702bb70a..b6eba6321 100644 --- a/src/NadekoBot/Modules/Xp/XpConfigService.cs +++ b/src/NadekoBot/Modules/Xp/XpConfigService.cs @@ -7,6 +7,7 @@ public sealed class XpConfigService : ConfigServiceBase { private const string FILE_PATH = "data/xp.yml"; private static readonly TypedKey _changeKey = new("config.xp.updated"); + public override string Name => "xp"; diff --git a/src/NadekoBot/Modules/Xp/XpService.cs b/src/NadekoBot/Modules/Xp/XpService.cs index d93d52b43..78cb5d423 100644 --- a/src/NadekoBot/Modules/Xp/XpService.cs +++ b/src/NadekoBot/Modules/Xp/XpService.cs @@ -116,7 +116,8 @@ public class XpService : INService // Scan guilds on startup. _client.GuildAvailable += Client_OnGuildAvailable; - foreach (var guild in _client.Guilds) Client_OnGuildAvailable(guild); + foreach (var guild in _client.Guilds) + Client_OnGuildAvailable(guild); #endif _updateXpTask = Task.Run(UpdateLoop); } @@ -135,10 +136,12 @@ public class XpService : INService var curRewards = new Dictionary>(); var toAddTo = new List(); - while (_addMessageXp.TryDequeue(out var usr)) toAddTo.Add(usr); + while (_addMessageXp.TryDequeue(out var usr)) + toAddTo.Add(usr); var group = toAddTo.GroupBy(x => (GuildId: x.Guild.Id, x.User)); - if (toAddTo.Count == 0) continue; + if (toAddTo.Count == 0) + continue; await using (var uow = _db.GetDbContext()) { @@ -156,7 +159,8 @@ public class XpService : INService var oldGuildLevelData = new LevelStats(usr.Xp + usr.AwardedXp); usr.Xp += xp; du.TotalXp += xp; - if (du.Club is not null) du.Club.Xp += xp; + if (du.Club is not null) + du.Club.Xp += xp; var newGuildLevelData = new LevelStats(usr.Xp + usr.AwardedXp); if (oldGlobalLevelData.Level < newGlobalLevelData.Level) @@ -302,7 +306,11 @@ public class XpService : INService if (rew is not null) rew.Amount = amount; else - settings.CurrencyRewards.Add(new() { Level = level, Amount = amount }); + settings.CurrencyRewards.Add(new() + { + Level = level, + Amount = amount + }); } uow.SaveChanges(); @@ -354,7 +362,12 @@ public class XpService : INService } else { - settings.RoleRewards.Add(new() { Level = level, RoleId = roleId, Remove = remove }); + settings.RoleRewards.Add(new() + { + Level = level, + RoleId = roleId, + Remove = remove + }); } uow.SaveChanges(); @@ -411,7 +424,8 @@ public class XpService : INService { Task.Run(() => { - foreach (var channel in guild.VoiceChannels) ScanChannelForVoiceXp(channel); + foreach (var channel in guild.VoiceChannels) + ScanChannelForVoiceXp(channel); }); return Task.CompletedTask; @@ -422,9 +436,10 @@ public class XpService : INService if (socketUser is not SocketGuildUser user || user.IsBot) return Task.CompletedTask; - _= Task.Run(() => + _ = Task.Run(() => { - if (before.VoiceChannel is not null) ScanChannelForVoiceXp(before.VoiceChannel); + if (before.VoiceChannel is not null) + ScanChannelForVoiceXp(before.VoiceChannel); if (after.VoiceChannel is not null && after.VoiceChannel != before.VoiceChannel) ScanChannelForVoiceXp(after.VoiceChannel); @@ -482,7 +497,8 @@ public class XpService : INService _cache.Redis.GetDatabase().KeyDelete(key); // Allow for if this function gets called multiple times when a user leaves a channel. - if (value.IsNull) return; + if (value.IsNull) + return; if (!value.TryParse(out long startUnixTime)) return; @@ -494,14 +510,21 @@ public class XpService : INService var actualXp = (int)Math.Floor(xp); if (actualXp > 0) - _addMessageXp.Enqueue(new() { Guild = channel.Guild, User = user, XpAmount = actualXp }); + _addMessageXp.Enqueue(new() + { + Guild = channel.Guild, + User = user, + XpAmount = actualXp + }); } private bool ShouldTrackXp(SocketGuildUser user, ulong channelId) { - if (_excludedChannels.TryGetValue(user.Guild.Id, out var chans) && chans.Contains(channelId)) return false; + if (_excludedChannels.TryGetValue(user.Guild.Id, out var chans) && chans.Contains(channelId)) + return false; - if (_excludedServers.Contains(user.Guild.Id)) return false; + if (_excludedServers.Contains(user.Guild.Id)) + return false; if (_excludedRoles.TryGetValue(user.Guild.Id, out var roles) && user.Roles.Any(x => roles.Contains(x.Id))) return false; @@ -514,16 +537,18 @@ public class XpService : INService if (arg.Author is not SocketGuildUser user || user.IsBot) return Task.CompletedTask; - _= Task.Run(() => + _ = Task.Run(() => { if (!ShouldTrackXp(user, arg.Channel.Id)) return; var xpConf = _xpConfig.Data; var xp = 0; - if (arg.Attachments.Any(a => a.Height >= 128 && a.Width >= 128)) xp = xpConf.XpFromImage; + if (arg.Attachments.Any(a => a.Height >= 128 && a.Width >= 128)) + xp = xpConf.XpFromImage; - if (arg.Content.Contains(' ') || arg.Content.Length >= 5) xp = Math.Max(xp, xpConf.XpPerMessage); + if (arg.Content.Contains(' ') || arg.Content.Length >= 5) + xp = Math.Max(xp, xpConf.XpPerMessage); if (xp <= 0) return; @@ -531,16 +556,29 @@ public class XpService : INService if (!SetUserRewarded(user.Id)) return; - _addMessageXp.Enqueue(new() { Guild = user.Guild, Channel = arg.Channel, User = user, XpAmount = xp }); + _addMessageXp.Enqueue(new() + { + Guild = user.Guild, + Channel = arg.Channel, + User = user, + XpAmount = xp + }); }); return Task.CompletedTask; } public void AddXpDirectly(IGuildUser user, IMessageChannel channel, int amount) { - if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount)); + if (amount <= 0) + throw new ArgumentOutOfRangeException(nameof(amount)); - _addMessageXp.Enqueue(new() { Guild = user.Guild, Channel = channel, User = user, XpAmount = amount }); + _addMessageXp.Enqueue(new() + { + Guild = user.Guild, + Channel = channel, + User = user, + XpAmount = amount + }); } public void AddXp(ulong userId, ulong guildId, int amount) @@ -622,11 +660,16 @@ public class XpService : INService var roles = _excludedRoles.GetOrAdd(guildId, _ => new()); using var uow = _db.GetDbContext(); var xpSetting = uow.XpSettingsFor(guildId); - var excludeObj = new ExcludedItem { ItemId = rId, ItemType = ExcludedItemType.Role }; + var excludeObj = new ExcludedItem + { + ItemId = rId, + ItemType = ExcludedItemType.Role + }; if (roles.Add(rId)) { - if (xpSetting.ExclusionList.Add(excludeObj)) uow.SaveChanges(); + if (xpSetting.ExclusionList.Add(excludeObj)) + uow.SaveChanges(); return true; } @@ -648,18 +691,24 @@ public class XpService : INService var channels = _excludedChannels.GetOrAdd(guildId, _ => new()); using var uow = _db.GetDbContext(); var xpSetting = uow.XpSettingsFor(guildId); - var excludeObj = new ExcludedItem { ItemId = chId, ItemType = ExcludedItemType.Channel }; + var excludeObj = new ExcludedItem + { + ItemId = chId, + ItemType = ExcludedItemType.Channel + }; if (channels.Add(chId)) { - if (xpSetting.ExclusionList.Add(excludeObj)) uow.SaveChanges(); + if (xpSetting.ExclusionList.Add(excludeObj)) + uow.SaveChanges(); return true; } channels.TryRemove(chId); - if (xpSetting.ExclusionList.Remove(excludeObj)) uow.SaveChanges(); + if (xpSetting.ExclusionList.Remove(excludeObj)) + uow.SaveChanges(); return false; } @@ -678,7 +727,8 @@ public class XpService : INService { TextOptions = new() { - HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center + HorizontalAlignment = HorizontalAlignment.Left, + VerticalAlignment = VerticalAlignment.Center } }.WithFallbackFonts(_fonts.FallBackFonts); @@ -686,7 +736,8 @@ public class XpService : INService { TextOptions = new() { - HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top + HorizontalAlignment = HorizontalAlignment.Right, + VerticalAlignment = VerticalAlignment.Top } }.WithFallbackFonts(_fonts.FallBackFonts); @@ -864,7 +915,8 @@ public class XpService : INService } //club image - if (template.Club.Icon.Show) await DrawClubImage(img, stats); + if (template.Club.Icon.Show) + await DrawClubImage(img, stats); img.Mutate(x => x.Resize(template.OutputSize.X, template.OutputSize.Y)); return ((Stream)img.ToStream(imageFormat), imageFormat); diff --git a/src/NadekoBot/Modules/Xp/_Common/XpTemplate.cs b/src/NadekoBot/Modules/Xp/_Common/XpTemplate.cs index 0a827f9e4..cc750a00b 100644 --- a/src/NadekoBot/Modules/Xp/_Common/XpTemplate.cs +++ b/src/NadekoBot/Modules/Xp/_Common/XpTemplate.cs @@ -8,22 +8,102 @@ namespace NadekoBot.Modules.Xp; public class XpTemplate { [JsonProperty("output_size")] - public XpTemplatePos OutputSize { get; set; } = new() { X = 450, Y = 220 }; + public XpTemplatePos OutputSize { get; set; } = new() + { + X = 450, + Y = 220 + }; public XpTemplateUser User { get; set; } = new() { - Name = new() { FontSize = 50, Show = true, Pos = new() { X = 130, Y = 17 } }, - Icon = new() { Show = true, Pos = new() { X = 32, Y = 10 }, Size = new() { X = 69, Y = 70 } }, - GuildLevel = new() { Show = true, FontSize = 45, Pos = new() { X = 47, Y = 297 } }, - GlobalLevel = new() { Show = true, FontSize = 45, Pos = new() { X = 47, Y = 149 } }, - GuildRank = new() { Show = true, FontSize = 30, Pos = new() { X = 148, Y = 326 } }, - GlobalRank = new() { Show = true, FontSize = 30, Pos = new() { X = 148, Y = 179 } }, + Name = new() + { + FontSize = 50, + Show = true, + Pos = new() + { + X = 130, + Y = 17 + } + }, + Icon = new() + { + Show = true, + Pos = new() + { + X = 32, + Y = 10 + }, + Size = new() + { + X = 69, + Y = 70 + } + }, + GuildLevel = new() + { + Show = true, + FontSize = 45, + Pos = new() + { + X = 47, + Y = 297 + } + }, + GlobalLevel = new() + { + Show = true, + FontSize = 45, + Pos = new() + { + X = 47, + Y = 149 + } + }, + GuildRank = new() + { + Show = true, + FontSize = 30, + Pos = new() + { + X = 148, + Y = 326 + } + }, + GlobalRank = new() + { + Show = true, + FontSize = 30, + Pos = new() + { + X = 148, + Y = 179 + } + }, TimeOnLevel = new() { Format = "{0}d{1}h{2}m", - Global = new() { FontSize = 20, Show = true, Pos = new() { X = 50, Y = 204 } }, - Guild = new() { FontSize = 20, Show = true, Pos = new() { X = 50, Y = 351 } } + Global = new() + { + FontSize = 20, + Show = true, + Pos = new() + { + X = 50, + Y = 204 + } + }, + Guild = new() + { + FontSize = 20, + Show = true, + Pos = new() + { + X = 50, + Y = 351 + } + } }, Xp = new() { @@ -35,28 +115,93 @@ public class XpTemplate Direction = XpTemplateDirection.Right, Length = 450, Color = new(0, 0, 0, 0.4f), - PointA = new() { X = 321, Y = 104 }, - PointB = new() { X = 286, Y = 235 } + PointA = new() + { + X = 321, + Y = 104 + }, + PointB = new() + { + X = 286, + Y = 235 + } }, Guild = new() { Direction = XpTemplateDirection.Right, Length = 450, Color = new(0, 0, 0, 0.4f), - PointA = new() { X = 282, Y = 248 }, - PointB = new() { X = 247, Y = 379 } + PointA = new() + { + X = 282, + Y = 248 + }, + PointB = new() + { + X = 247, + Y = 379 + } } }, - Global = new() { Show = true, FontSize = 50, Pos = new() { X = 430, Y = 142 } }, - Guild = new() { Show = true, FontSize = 50, Pos = new() { X = 400, Y = 282 } }, - Awarded = new() { Show = true, FontSize = 25, Pos = new() { X = 445, Y = 347 } } + Global = new() + { + Show = true, + FontSize = 50, + Pos = new() + { + X = 430, + Y = 142 + } + }, + Guild = new() + { + Show = true, + FontSize = 50, + Pos = new() + { + X = 400, + Y = 282 + } + }, + Awarded = new() + { + Show = true, + FontSize = 25, + Pos = new() + { + X = 445, + Y = 347 + } + } } }; public XpTemplateClub Club { get; set; } = new() { - Icon = new() { Show = true, Pos = new() { X = 722, Y = 25 }, Size = new() { X = 45, Y = 45 } }, - Name = new() { FontSize = 35, Pos = new() { X = 650, Y = 49 }, Show = true } + Icon = new() + { + Show = true, + Pos = new() + { + X = 722, + Y = 25 + }, + Size = new() + { + X = 45, + Y = 45 + } + }, + Name = new() + { + FontSize = 35, + Pos = new() + { + X = 650, + Y = 49 + }, + Show = true + } }; } diff --git a/src/NadekoBot/NadekoBot.csproj b/src/NadekoBot/NadekoBot.csproj index dbdf9119a..d150a1b89 100644 --- a/src/NadekoBot/NadekoBot.csproj +++ b/src/NadekoBot/NadekoBot.csproj @@ -1,102 +1,102 @@  - - net6.0 - 10.0 - enable - True - true - - - $(MSBuildProjectDirectory) - exe - nadeko_icon.ico - - - - - None - CS1066 - - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - - - - - - - - + + net6.0 + 10.0 + enable + True + true - - - - - - - - - - - Protos\coordinator.proto - - - PreserveNewest - - - PreserveNewest - - - Always - - + + $(MSBuildProjectDirectory) + exe + nadeko_icon.ico - - 4.0.0 - $(VersionPrefix).$(VersionSuffix) - $(VersionPrefix) - - - - $(DefineConstants);GLOBAL_NADEKO - $(NoWarn);CS1573;CS1591 - + + + + None + CS1066 + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Protos\coordinator.proto + + + PreserveNewest + + + PreserveNewest + + + Always + + + + + 4.0.0 + $(VersionPrefix).$(VersionSuffix) + $(VersionPrefix) + + + + $(DefineConstants);GLOBAL_NADEKO + $(NoWarn);CS1573;CS1591 + diff --git a/src/NadekoBot/Services/Currency/CurrencyService.cs b/src/NadekoBot/Services/Currency/CurrencyService.cs index 5d8322848..c8b050a75 100644 --- a/src/NadekoBot/Services/Currency/CurrencyService.cs +++ b/src/NadekoBot/Services/Currency/CurrencyService.cs @@ -14,9 +14,7 @@ public class CurrencyService : ICurrencyService, INService public Task GetWalletAsync(ulong userId, CurrencyType type = CurrencyType.Default) { if (type == CurrencyType.Default) - { return Task.FromResult(new DefaultWallet(userId, _db.GetDbContext())); - } throw new ArgumentOutOfRangeException(nameof(type)); } @@ -111,10 +109,9 @@ public class CurrencyService : ICurrencyService, INService { await using var fromWallet = await GetWalletAsync(fromId); await using var toWallet = await GetWalletAsync(toId); - + var extra = new TxData("gift", fromName, note, fromId); - + return await fromWallet.Transfer(amount, toWallet, extra); } - } \ No newline at end of file diff --git a/src/NadekoBot/Services/Currency/CurrencyType.cs b/src/NadekoBot/Services/Currency/CurrencyType.cs index 5d2d28dd9..b7de00db0 100644 --- a/src/NadekoBot/Services/Currency/CurrencyType.cs +++ b/src/NadekoBot/Services/Currency/CurrencyType.cs @@ -2,5 +2,5 @@ public enum CurrencyType { - Default, + Default } \ No newline at end of file diff --git a/src/NadekoBot/Services/Currency/DefaultWallet.cs b/src/NadekoBot/Services/Currency/DefaultWallet.cs index 1ead11644..89937ce13 100644 --- a/src/NadekoBot/Services/Currency/DefaultWallet.cs +++ b/src/NadekoBot/Services/Currency/DefaultWallet.cs @@ -66,9 +66,8 @@ public class DefaultWallet : IWallet { CurrencyAmount = x.CurrencyAmount + amount }); - + if (changed == 0) - { await _ctx.DiscordUser .ToLinqToDBTable() .Value(x => x.UserId, UserId) @@ -76,7 +75,6 @@ public class DefaultWallet : IWallet .Value(x => x.Discriminator, "????") .Value(x => x.CurrencyAmount, amount) .InsertAsync(); - } await tran.CommitAsync(); } @@ -88,7 +86,7 @@ public class DefaultWallet : IWallet Note = txData.Note, Type = txData.Type, Extra = txData.Extra, - OtherId = txData.OtherId, + OtherId = txData.OtherId }; await _ctx.CreateLinqToDbContext() @@ -100,7 +98,7 @@ public class DefaultWallet : IWallet _ctx.SaveChanges(); _ctx.Dispose(); } - + public async ValueTask DisposeAsync() { await _ctx.SaveChangesAsync(); diff --git a/src/NadekoBot/Services/Currency/IWallet.cs b/src/NadekoBot/Services/Currency/IWallet.cs index 7172c7210..15bd2ebb3 100644 --- a/src/NadekoBot/Services/Currency/IWallet.cs +++ b/src/NadekoBot/Services/Currency/IWallet.cs @@ -3,11 +3,11 @@ namespace NadekoBot.Services.Currency; public interface IWallet : IDisposable, IAsyncDisposable { public ulong UserId { get; } - + public Task GetBalance(); public Task Take(long amount, TxData txData); public Task Add(long amount, TxData txData); - + public async Task Transfer( long amount, IWallet to, diff --git a/src/NadekoBot/Services/Currency/TxData.cs b/src/NadekoBot/Services/Currency/TxData.cs index 8f0e0e5f9..3e0c78d6a 100644 --- a/src/NadekoBot/Services/Currency/TxData.cs +++ b/src/NadekoBot/Services/Currency/TxData.cs @@ -1,3 +1,7 @@ namespace NadekoBot.Services.Currency; -public record class TxData(string Type, string Extra, string? Note = "", ulong? OtherId = null); \ No newline at end of file +public record class TxData( + string Type, + string Extra, + string? Note = "", + ulong? OtherId = null); \ No newline at end of file diff --git a/src/NadekoBot/Services/Impl/BehaviorExecutor.cs b/src/NadekoBot/Services/Impl/BehaviorExecutor.cs index cc4c8b195..16c5b1b48 100644 --- a/src/NadekoBot/Services/Impl/BehaviorExecutor.cs +++ b/src/NadekoBot/Services/Impl/BehaviorExecutor.cs @@ -26,8 +26,10 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService public async Task RunEarlyBehavioursAsync(SocketGuild guild, IUserMessage usrMsg) { foreach (var beh in earlyBehaviors) + { if (await beh.RunBehavior(guild, usrMsg)) return true; + } return false; } @@ -52,6 +54,7 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService public async Task RunLateBlockersAsync(ICommandContext ctx, CommandInfo cmd) { foreach (var exec in lateBlockers) + { if (await exec.TryBlockLate(ctx, cmd.Module.GetTopLevelModule().Name, cmd)) { Log.Information("Late blocking User [{User}] Command: [{Command}] in [{Module}]", @@ -60,6 +63,7 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService exec.GetType().Name); return true; } + } return false; } @@ -67,6 +71,7 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService public async Task RunLateExecutorsAsync(SocketGuild guild, IUserMessage usrMsg) { foreach (var exec in lateExecutors) + { try { await exec.LateExecute(guild, usrMsg); @@ -75,5 +80,6 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService { Log.Error(ex, "Error in {TypeName} late executor: {ErrorMessage}", exec.GetType().Name, ex.Message); } + } } } \ No newline at end of file diff --git a/src/NadekoBot/Services/Impl/BotCredsProvider.cs b/src/NadekoBot/Services/Impl/BotCredsProvider.cs index 2abd7ea1a..085ac08e5 100644 --- a/src/NadekoBot/Services/Impl/BotCredsProvider.cs +++ b/src/NadekoBot/Services/Impl/BotCredsProvider.cs @@ -42,7 +42,8 @@ public sealed class BotCredsProvider : IBotCredsProvider public BotCredsProvider(int? totalShards = null) { _totalShards = totalShards; - if (!File.Exists(CredsExamplePath)) File.WriteAllText(CredsExamplePath, Yaml.Serializer.Serialize(_creds)); + if (!File.Exists(CredsExamplePath)) + File.WriteAllText(CredsExamplePath, Yaml.Serializer.Serialize(_creds)); MigrateCredentials(); @@ -79,9 +80,17 @@ public sealed class BotCredsProvider : IBotCredsProvider || string.IsNullOrWhiteSpace(_creds.RestartCommand?.Args)) { if (Environment.OSVersion.Platform == PlatformID.Unix) - _creds.RestartCommand = new() { Args = "dotnet", Cmd = "NadekoBot.dll -- {0}" }; + _creds.RestartCommand = new() + { + Args = "dotnet", + Cmd = "NadekoBot.dll -- {0}" + }; else - _creds.RestartCommand = new() { Args = "NadekoBot.exe", Cmd = "{0}" }; + _creds.RestartCommand = new() + { + Args = "NadekoBot.exe", + Cmd = "{0}" + }; } if (string.IsNullOrWhiteSpace(_creds.RedisOptions)) diff --git a/src/NadekoBot/Services/Impl/FontProvider.cs b/src/NadekoBot/Services/Impl/FontProvider.cs index 2740766ba..af9346d8d 100644 --- a/src/NadekoBot/Services/Impl/FontProvider.cs +++ b/src/NadekoBot/Services/Impl/FontProvider.cs @@ -45,9 +45,12 @@ public class FontProvider : INService // any fonts present in data/fonts should be added as fallback fonts // this will allow support for special characters when drawing text foreach (var font in Directory.GetFiles(@"data/fonts")) + { if (font.EndsWith(".ttf")) FallBackFonts.Add(_fonts.Install(font)); - else if (font.EndsWith(".ttc")) FallBackFonts.AddRange(_fonts.InstallCollection(font)); + else if (font.EndsWith(".ttc")) + FallBackFonts.AddRange(_fonts.InstallCollection(font)); + } RipFont = NotoSans.CreateFont(20, FontStyle.Bold); DottyFont = FallBackFonts.First(x => x.Name == "dotty"); diff --git a/src/NadekoBot/Services/Impl/GoogleApiService.cs b/src/NadekoBot/Services/Impl/GoogleApiService.cs index fb1ea9445..3388cae90 100644 --- a/src/NadekoBot/Services/Impl/GoogleApiService.cs +++ b/src/NadekoBot/Services/Impl/GoogleApiService.cs @@ -164,7 +164,11 @@ public class GoogleApiService : IGoogleApiService, INService _creds = creds; _httpFactory = factory; - var bcs = new BaseClientService.Initializer { ApplicationName = "Nadeko Bot", ApiKey = _creds.GoogleApiKey }; + var bcs = new BaseClientService.Initializer + { + ApplicationName = "Nadeko Bot", + ApiKey = _creds.GoogleApiKey + }; _yt = new(bcs); _sh = new(bcs); @@ -181,7 +185,8 @@ public class GoogleApiService : IGoogleApiService, INService throw new ArgumentOutOfRangeException(nameof(count)); var match = _plRegex.Match(keywords); - if (match.Length > 1) return new[] { match.Groups["id"].Value }; + if (match.Length > 1) + return new[] { match.Groups["id"].Value }; var query = _yt.Search.List("snippet"); query.MaxResults = count; query.Type = "playlist"; @@ -256,7 +261,11 @@ public class GoogleApiService : IGoogleApiService, INService try { - var response = await _sh.Url.Insert(new() { LongUrl = url }).ExecuteAsync(); + var response = await _sh.Url.Insert(new() + { + LongUrl = url + }) + .ExecuteAsync(); return response.Id; } catch (GoogleApiException ex) when (ex.HttpStatusCode == HttpStatusCode.Forbidden) @@ -322,7 +331,8 @@ public class GoogleApiService : IGoogleApiService, INService q.Id = string.Join(",", videoIdsList.Take(toGet)); videoIdsList = videoIdsList.Skip(toGet).ToList(); var items = (await q.ExecuteAsync()).Items; - foreach (var i in items) toReturn.Add(i.Id, XmlConvert.ToTimeSpan(i.ContentDetails.Duration)); + foreach (var i in items) + toReturn.Add(i.Id, XmlConvert.ToTimeSpan(i.ContentDetails.Duration)); } while (remaining > 0); return toReturn; diff --git a/src/NadekoBot/Services/Impl/Localization.cs b/src/NadekoBot/Services/Impl/Localization.cs index 1d365dfa3..d1ef3044e 100644 --- a/src/NadekoBot/Services/Impl/Localization.cs +++ b/src/NadekoBot/Services/Impl/Localization.cs @@ -103,7 +103,12 @@ public class Localization : ILocalization, INService _commandData.TryGetValue(key, out var toReturn); if (toReturn is null) - return new() { Cmd = key, Desc = key, Usage = new[] { key } }; + return new() + { + Cmd = key, + Desc = key, + Usage = new[] { key } + }; return toReturn; } diff --git a/src/NadekoBot/Services/Impl/RedisCache.cs b/src/NadekoBot/Services/Impl/RedisCache.cs index 869323154..10aa9f847 100644 --- a/src/NadekoBot/Services/Impl/RedisCache.cs +++ b/src/NadekoBot/Services/Impl/RedisCache.cs @@ -157,7 +157,8 @@ public class RedisCache : IDataCache { var db = Redis.GetDatabase(); data = db.StringGet($"{_redisKey}_economy"); - if (data is not null) return true; + if (data is not null) + return true; return false; } diff --git a/src/NadekoBot/Services/Impl/RedisImagesCache.cs b/src/NadekoBot/Services/Impl/RedisImagesCache.cs index 3ccdda1c6..5762e0048 100644 --- a/src/NadekoBot/Services/Impl/RedisImagesCache.cs +++ b/src/NadekoBot/Services/Impl/RedisImagesCache.cs @@ -127,9 +127,14 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor Rategirl = new() { - Dot = oldData.Rategirl.Dot.ToNewCdn(), Matrix = oldData.Rategirl.Matrix.ToNewCdn() + Dot = oldData.Rategirl.Dot.ToNewCdn(), + Matrix = oldData.Rategirl.Matrix.ToNewCdn() }, - Rip = new() { Bg = oldData.Rip.Bg.ToNewCdn(), Overlay = oldData.Rip.Overlay.ToNewCdn() }, + Rip = new() + { + Bg = oldData.Rip.Bg.ToNewCdn(), + Overlay = oldData.Rip.Overlay.ToNewCdn() + }, Slots = new() { Bg = new("https://cdn.nadeko.bot/slots/slots_bg.png"), @@ -140,7 +145,10 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor "https://cdn.nadeko.bot/slots/4.png", "https://cdn.nadeko.bot/slots/5.png" }.Map(x => new Uri(x)) }, - Xp = new() { Bg = oldData.Xp.Bg.ToNewCdn() }, + Xp = new() + { + Bg = oldData.Xp.Bg.ToNewCdn() + }, Version = 2 }; @@ -162,6 +170,7 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor { ImageUrls = Yaml.Deserializer.Deserialize(await File.ReadAllTextAsync(_imagesPath)); foreach (var key in GetAllKeys()) + { switch (key) { case ImageKeys.CoinHeads: @@ -200,6 +209,7 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor default: throw new ArgumentOutOfRangeException(); } + } } private async Task Load(ImageKeys key, Uri uri) diff --git a/src/NadekoBot/Services/Impl/RemoteGrpcCoordinator.cs b/src/NadekoBot/Services/Impl/RemoteGrpcCoordinator.cs index 5b0df026a..6b12ef0c1 100644 --- a/src/NadekoBot/Services/Impl/RemoteGrpcCoordinator.cs +++ b/src/NadekoBot/Services/Impl/RemoteGrpcCoordinator.cs @@ -28,11 +28,17 @@ public class RemoteGrpcCoordinator : ICoordinator, IReadyExecutor } public void Die(bool graceful) - => _coordClient.Die(new() { Graceful = graceful }); + => _coordClient.Die(new() + { + Graceful = graceful + }); public bool RestartShard(int shardId) { - _coordClient.RestartShard(new() { ShardId = shardId }); + _coordClient.RestartShard(new() + { + ShardId = shardId + }); return true; } diff --git a/src/NadekoBot/Services/Impl/StatsService.cs b/src/NadekoBot/Services/Impl/StatsService.cs index 9f50e89ce..d89acc9d5 100644 --- a/src/NadekoBot/Services/Impl/StatsService.cs +++ b/src/NadekoBot/Services/Impl/StatsService.cs @@ -58,7 +58,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl _client.ChannelCreated += c => { - _= Task.Run(() => + _ = Task.Run(() => { if (c is ITextChannel) Interlocked.Increment(ref textChannels); @@ -71,7 +71,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl _client.ChannelDestroyed += c => { - _= Task.Run(() => + _ = Task.Run(() => { if (c is ITextChannel) Interlocked.Decrement(ref textChannels); @@ -84,7 +84,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl _client.GuildAvailable += g => { - _= Task.Run(() => + _ = Task.Run(() => { var tc = g.Channels.Count(cx => cx is ITextChannel); var vc = g.Channels.Count - tc; @@ -96,7 +96,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl _client.JoinedGuild += g => { - _= Task.Run(() => + _ = Task.Run(() => { var tc = g.Channels.Count(cx => cx is ITextChannel); var vc = g.Channels.Count - tc; @@ -108,7 +108,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl _client.GuildUnavailable += g => { - _= Task.Run(() => + _ = Task.Run(() => { var tc = g.Channels.Count(cx => cx is ITextChannel); var vc = g.Channels.Count - tc; @@ -121,7 +121,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl _client.LeftGuild += g => { - _= Task.Run(() => + _ = Task.Run(() => { var tc = g.Channels.Count(cx => cx is ITextChannel); var vc = g.Channels.Count - tc; @@ -138,7 +138,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl var guilds = _client.Guilds; textChannels = guilds.Sum(g => g.Channels.Count(cx => cx is ITextChannel)); voiceChannels = guilds.Sum(g => g.Channels.Count(cx => cx is IVoiceChannel)); - + var timer = new PeriodicTimer(TimeSpan.FromHours(1)); do { @@ -167,7 +167,7 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl Log.Error(ex, "Error in botlist post"); } } while (await timer.WaitForNextTickAsync()); - } + } public TimeSpan GetUptime() => DateTime.UtcNow - _started; diff --git a/src/NadekoBot/Services/Settings/BotConfigService.cs b/src/NadekoBot/Services/Settings/BotConfigService.cs index d77f20775..bd794aaa8 100644 --- a/src/NadekoBot/Services/Settings/BotConfigService.cs +++ b/src/NadekoBot/Services/Settings/BotConfigService.cs @@ -30,10 +30,10 @@ public sealed class BotConfigService : ConfigServiceBase private void Migrate() { - if (data.Version < 2) ModifyConfig(c => c.Version = 2); + if (data.Version < 2) + ModifyConfig(c => c.Version = 2); if (data.Version < 3) - { ModifyConfig(c => { c.Version = 3; @@ -46,6 +46,5 @@ public sealed class BotConfigService : ConfigServiceBase .Distinct() .ToHashSet(); }); - } } } \ No newline at end of file diff --git a/src/NadekoBot/Services/strings/impl/BotStrings.cs b/src/NadekoBot/Services/strings/impl/BotStrings.cs index 2b832d495..dd4a64cc2 100644 --- a/src/NadekoBot/Services/strings/impl/BotStrings.cs +++ b/src/NadekoBot/Services/strings/impl/BotStrings.cs @@ -78,7 +78,11 @@ public class BotStrings : IBotStrings Log.Warning("'{CommandName}' doesn't exist in 'en-US' command strings. Please report this", commandName); - return new() { Args = new[] { "" }, Desc = "?" }; + return new() + { + Args = new[] { "" }, + Desc = "?" + }; } // Log.Warning(@"'{CommandName}' command strings don't exist in '{LanguageName}' culture. diff --git a/src/NadekoBot/Services/strings/impl/LocalFileStringsSource.cs b/src/NadekoBot/Services/strings/impl/LocalFileStringsSource.cs index 80c3914af..109fc553f 100644 --- a/src/NadekoBot/Services/strings/impl/LocalFileStringsSource.cs +++ b/src/NadekoBot/Services/strings/impl/LocalFileStringsSource.cs @@ -24,6 +24,7 @@ public class LocalFileStringsSource : IStringsSource { var outputDict = new Dictionary>(); foreach (var file in Directory.GetFiles(_responsesPath)) + { try { var langDict = JsonConvert.DeserializeObject>(File.ReadAllText(file)); @@ -34,6 +35,7 @@ public class LocalFileStringsSource : IStringsSource { Log.Error(ex, "Error loading {FileName} response strings: {ErrorMessage}", file, ex.Message); } + } return outputDict; } @@ -44,6 +46,7 @@ public class LocalFileStringsSource : IStringsSource var outputDict = new Dictionary>(); foreach (var file in Directory.GetFiles(_commandsPath)) + { try { var text = File.ReadAllText(file); @@ -55,6 +58,7 @@ public class LocalFileStringsSource : IStringsSource { Log.Error(ex, "Error loading {FileName} command strings: {ErrorMessage}", file, ex.Message); } + } return outputDict; } diff --git a/src/NadekoBot/Services/strings/impl/RedisBotStringsProvider.cs b/src/NadekoBot/Services/strings/impl/RedisBotStringsProvider.cs index a420f1d65..990bb545d 100644 --- a/src/NadekoBot/Services/strings/impl/RedisBotStringsProvider.cs +++ b/src/NadekoBot/Services/strings/impl/RedisBotStringsProvider.cs @@ -47,7 +47,11 @@ public class RedisBotStringsProvider : IBotStringsProvider return null; var args = Array.ConvertAll(argsStr.Split('&'), HttpUtility.UrlDecode); - return new() { Args = args, Desc = descStr }; + return new() + { + Args = args, + Desc = descStr + }; } public void Reload() diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index 46b3a5b1c..2812b3ca2 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -13,7 +13,7 @@ public static class Extensions public static IEmbedBuilder WithAuthor(this IEmbedBuilder eb, IUser author) => eb.WithAuthor(author.ToString(), author.RealAvatarUrl().ToString()); - + public static Task EditAsync(this IUserMessage msg, SmartText text) => text switch { @@ -58,7 +58,6 @@ public static class Extensions public static IEmote ToIEmote(this string emojiStr) => Emote.TryParse(emojiStr, out var maybeEmote) ? maybeEmote : new Emoji(emojiStr); - /// /// First 10 characters of teh bot token. @@ -115,11 +114,11 @@ public static class Extensions var wrap = new ReactionEventWrapper(client, msg); wrap.OnReactionAdded += r => { - _= Task.Run(() => reactionAdded(r)); + _ = Task.Run(() => reactionAdded(r)); }; wrap.OnReactionRemoved += r => { - _= Task.Run(() => reactionRemoved(r)); + _ = Task.Run(() => reactionRemoved(r)); }; return wrap; } @@ -143,7 +142,8 @@ public static class Extensions Task.Run(async () => { await Task.Delay(seconds * 1000); - if (logService is not null) logService.AddDeleteIgnore(msg.Id); + if (logService is not null) + logService.AddDeleteIgnore(msg.Id); try { await msg.DeleteAsync(); } catch { } @@ -153,7 +153,8 @@ public static class Extensions public static ModuleInfo GetTopLevelModule(this ModuleInfo module) { - while (module.Parent is not null) module = module.Parent; + while (module.Parent is not null) + module = module.Parent; return module; } @@ -183,14 +184,16 @@ public static class Extensions public static bool IsImage(this HttpResponseMessage msg, out string? mimeType) { mimeType = msg.Content.Headers.ContentType?.MediaType; - if (mimeType is "image/png" or "image/jpeg" or "image/gif") return true; + if (mimeType is "image/png" or "image/jpeg" or "image/gif") + return true; return false; } public static long? GetImageSize(this HttpResponseMessage msg) { - if (msg.Content.Headers.ContentLength is null) return null; + if (msg.Content.Headers.ContentLength is null) + return null; return msg.Content.Headers.ContentLength.Value / 1.Mb(); } diff --git a/src/NadekoBot/_Extensions/IMessageChannelExtensions.cs b/src/NadekoBot/_Extensions/IMessageChannelExtensions.cs index 900c8b44f..d99318cd9 100644 --- a/src/NadekoBot/_Extensions/IMessageChannelExtensions.cs +++ b/src/NadekoBot/_Extensions/IMessageChannelExtensions.cs @@ -6,7 +6,12 @@ public static class MessageChannelExtensions private static readonly IEmote _arrowRight = new Emoji("➡"); public static Task EmbedAsync(this IMessageChannel ch, IEmbedBuilder embed, string msg = "") - => ch.SendMessageAsync(msg, embed: embed.Build(), options: new() { RetryMode = RetryMode.AlwaysRetry }); + => ch.SendMessageAsync(msg, + embed: embed.Build(), + options: new() + { + RetryMode = RetryMode.AlwaysRetry + }); public static Task SendAsync( this IMessageChannel channel, diff --git a/src/NadekoBot/_Extensions/ImagesharpExtensions.cs b/src/NadekoBot/_Extensions/ImagesharpExtensions.cs index 6aa2edcce..db4af6a51 100644 --- a/src/NadekoBot/_Extensions/ImagesharpExtensions.cs +++ b/src/NadekoBot/_Extensions/ImagesharpExtensions.cs @@ -20,7 +20,8 @@ public static class ImagesharpExtensions /// The same to allow chaining public static TextOptions WithFallbackFonts(this TextOptions opts, List fallback) { - foreach (var ff in fallback) opts.FallbackFonts.Add(ff); + foreach (var ff in fallback) + opts.FallbackFonts.Add(ff); return opts; } @@ -36,7 +37,7 @@ public static class ImagesharpExtensions opts.TextOptions.WithFallbackFonts(fallback); return opts; } - + // https://github.com/SixLabors/Samples/blob/master/ImageSharp/AvatarWithRoundedCorner/Program.cs public static IImageProcessingContext ApplyRoundedCorners(this IImageProcessingContext ctx, float cornerRadius) { @@ -50,7 +51,8 @@ public static class ImagesharpExtensions AlphaCompositionMode = PixelAlphaCompositionMode.DestOut }); - foreach (var c in corners) ctx = ctx.Fill(SixLabors.ImageSharp.Color.Red, c); + foreach (var c in corners) + ctx = ctx.Fill(SixLabors.ImageSharp.Color.Red, c); return ctx; } @@ -76,7 +78,7 @@ public static class ImagesharpExtensions return new PathCollection(cornerTopLeft, cornerBottomLeft, cornerTopRight, cornerBottomRight); } - + public static Color ToDiscordColor(this Rgba32 color) => new(color.R, color.G, color.B); @@ -89,7 +91,8 @@ public static class ImagesharpExtensions img.SaveAsPng(imageStream, new() { - ColorType = PngColorType.RgbWithAlpha, CompressionLevel = PngCompressionLevel.BestCompression + ColorType = PngColorType.RgbWithAlpha, + CompressionLevel = PngCompressionLevel.BestCompression }); imageStream.Position = 0; diff --git a/src/NadekoBot/_Extensions/ProcessExtensions.cs b/src/NadekoBot/_Extensions/ProcessExtensions.cs index 90ba03cb0..940fd419a 100644 --- a/src/NadekoBot/_Extensions/ProcessExtensions.cs +++ b/src/NadekoBot/_Extensions/ProcessExtensions.cs @@ -25,7 +25,8 @@ public static class ProcessExtensions { var children = new HashSet(); GetAllChildIdsUnix(process.Id, children, timeout); - foreach (var childId in children) KillProcessUnix(childId, timeout); + foreach (var childId in children) + KillProcessUnix(childId, timeout); KillProcessUnix(process.Id, timeout); } @@ -41,7 +42,8 @@ public static class ProcessExtensions while (true) { var text = reader.ReadLine(); - if (text is null) return; + if (text is null) + return; if (int.TryParse(text, out var id)) { @@ -66,7 +68,10 @@ public static class ProcessExtensions var startInfo = new ProcessStartInfo { - FileName = fileName, Arguments = arguments, RedirectStandardOutput = true, UseShellExecute = false + FileName = fileName, + Arguments = arguments, + RedirectStandardOutput = true, + UseShellExecute = false }; var process = Process.Start(startInfo); diff --git a/src/NadekoBot/_Extensions/ServiceCollectionExtensions.cs b/src/NadekoBot/_Extensions/ServiceCollectionExtensions.cs index f44b15891..dca5c2b8f 100644 --- a/src/NadekoBot/_Extensions/ServiceCollectionExtensions.cs +++ b/src/NadekoBot/_Extensions/ServiceCollectionExtensions.cs @@ -23,11 +23,13 @@ public static class ServiceCollectionExtensions var baseType = typeof(ConfigServiceBase<>); foreach (var type in Assembly.GetCallingAssembly().ExportedTypes.Where(x => x.IsSealed)) + { if (type.BaseType?.IsGenericType == true && type.BaseType.GetGenericTypeDefinition() == baseType) { services.AddSingleton(type); services.AddSingleton(x => (IConfigService)x.GetRequiredService(type)); } + } return services; } @@ -53,7 +55,8 @@ public static class ServiceCollectionExtensions var subTypes = Assembly.GetCallingAssembly() .ExportedTypes.Where(type => type.IsSealed && baseType.IsAssignableFrom(type)); - foreach (var subType in subTypes) services.AddSingleton(baseType, subType); + foreach (var subType in subTypes) + services.AddSingleton(baseType, subType); return services; } diff --git a/src/NadekoBot/_Extensions/StringExtensions.cs b/src/NadekoBot/_Extensions/StringExtensions.cs index 80a717a26..c59ebb1a0 100644 --- a/src/NadekoBot/_Extensions/StringExtensions.cs +++ b/src/NadekoBot/_Extensions/StringExtensions.cs @@ -55,9 +55,11 @@ public static class StringExtensions var d = new int[n + 1, m + 1]; // Step 1 - if (n == 0) return m; + if (n == 0) + return m; - if (m == 0) return n; + if (m == 0) + return n; // Step 2 for (var i = 0; i <= n; d[i, 0] = i++) diff --git a/src/NadekoBot/data/strings/commands/commands.en-US.yml b/src/NadekoBot/data/strings/commands/commands.en-US.yml index a642a79eb..7164fd54f 100644 --- a/src/NadekoBot/data/strings/commands/commands.en-US.yml +++ b/src/NadekoBot/data/strings/commands/commands.en-US.yml @@ -44,7 +44,7 @@ bye: args: - "" byemsg: - desc: |- + desc: |- Sets a new leave announcement message. Type `%user.mention%` if you want to show the name the user who left. Full list of placeholders can be found here @@ -197,7 +197,7 @@ expradd: args: - "\"hello\" Hi there %user.mention%" exprlist: - desc: |- + desc: |- Lists global or server custom reactions (20 commands per page). Running the command in DM will list global custom reactions, while running it in a server will list server custom reactions. Shows enabled settings, followed by id, followed by the trigger. @@ -1828,8 +1828,8 @@ xprewsreset: - "" xprolereward: desc: |- - Add or remove a role from the user who reaches the specified level. - Provide no action and role name in order to remove the role reward. + Add or remove a role from the user who reaches the specified level. + Provide no action and role name in order to remove the role reward. args: - "1 rm Newbie" - "3 add Social" @@ -2131,7 +2131,7 @@ purgeuser: args: - "@Oblivion" imageonlychannel: - desc: |- + desc: |- Toggles whether the channel only allows images. Users who send more than a few non-image messages will be banned from using the channel. args: @@ -2139,7 +2139,7 @@ imageonlychannel: coordreload: desc: "Reloads coordinator config" args: - - "" + - "" showembed: desc: "Prints the json equivalent of the embed of the message specified by its Id." args: