From d5fd6aae8eb461b6c315c552e12f947d9cce3c02 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 26 Dec 2021 17:28:39 +0100 Subject: [PATCH] - More code cleanup and codestyle updates - Fixed some possible nullref exceptions - Methods signatures now have up to 3 parameters before breakaing down each parameter in a separate line - Method invocations have the same rule, except the first parameter will be in the same line as the invocation to prevent some ugliness when passing lambas as arguments - Applied many more codestyles - Extensions folder fully reformatted --- .editorconfig | 13 +- src/NadekoBot/.editorconfig | 40 +-- src/NadekoBot/Bot.cs | 4 +- src/NadekoBot/Common/AsyncLazy.cs | 3 +- .../Common/Attributes/NadekoCommand.cs | 4 +- .../Common/Attributes/NadekoOptions.cs | 4 +- .../Common/Collections/ConcurrentHashSet.cs | 94 +++++-- .../Common/Collections/IndexedCollection.cs | 8 +- .../Common/JsonConverters/Rbga32Converter.cs | 16 +- src/NadekoBot/Common/Kwum.cs | 4 +- src/NadekoBot/Common/LoginErrorHandler.cs | 6 +- src/NadekoBot/Common/NadekoModule.cs | 6 +- src/NadekoBot/Common/NadekoRandom.cs | 8 +- src/NadekoBot/Common/PubSub/TypedKey.cs | 4 +- .../Common/Replacements/ReplacementBuilder.cs | 12 +- src/NadekoBot/Common/ShmartNumber.cs | 36 +-- .../Common/SmartText/SmartPlainText.cs | 8 +- .../TypeReaders/BotCommandTypeReader.cs | 2 +- .../TypeReaders/GuildDateTimeTypeReader.cs | 6 +- .../Common/TypeReaders/GuildTypeReader.cs | 4 +- .../Common/TypeReaders/KwumTypeReader.cs | 4 +- .../TypeReaders/Models/PermissionAction.cs | 4 +- .../Common/TypeReaders/ModuleTypeReader.cs | 8 +- src/NadekoBot/Common/Yml/CommentAttribute.cs | 4 +- .../Yml/CommentGatheringTypeInspector.cs | 30 +-- .../Common/Yml/CommentsObjectDescriptor.cs | 15 +- src/NadekoBot/Common/Yml/Rgba32Converter.cs | 8 +- src/NadekoBot/Common/Yml/UriConverter.cs | 4 +- src/NadekoBot/Common/Yml/YamlHelper.cs | 11 +- src/NadekoBot/Db/Extensions/ClubExtensions.cs | 4 +- .../CurrencyTransactionExtensions.cs | 4 +- .../Extensions/CustomReactionsExtensions.cs | 12 +- .../Db/Extensions/DiscordUserExtensions.cs | 28 +-- .../Db/Extensions/GuildConfigExtensions.cs | 37 ++- src/NadekoBot/Db/Extensions/PollExtensions.cs | 4 +- .../Db/Extensions/QuoteExtensions.cs | 11 +- .../Db/Extensions/UserXpExtensions.cs | 21 +- .../Db/Extensions/WaifuExtensions.cs | 10 +- .../Db/Extensions/WarningExtensions.cs | 8 +- src/NadekoBot/Db/Models/AntiProtection.cs | 4 +- src/NadekoBot/Db/Models/ClubInfo.cs | 4 +- src/NadekoBot/Db/Models/CustomReaction.cs | 2 +- src/NadekoBot/Db/Models/DelMsgOnCmdChannel.cs | 10 +- src/NadekoBot/Db/Models/DiscordUser.cs | 8 +- src/NadekoBot/Db/Models/FeedSub.cs | 12 +- src/NadekoBot/Db/Models/FollowedStream.cs | 12 +- src/NadekoBot/Db/Models/GCChannelId.cs | 4 +- src/NadekoBot/Db/Models/MutedUserId.cs | 8 +- src/NadekoBot/Db/Models/PollVote.cs | 8 +- .../Db/Models/SlowmodeIgnoredRole.cs | 4 +- .../Db/Models/SlowmodeIgnoredUser.cs | 4 +- src/NadekoBot/Db/Models/StreamRoleSettings.cs | 12 +- src/NadekoBot/Db/Models/UnbanTimer.cs | 4 +- src/NadekoBot/Db/Models/UnmuteTimer.cs | 4 +- src/NadekoBot/Db/Models/UnroleTimer.cs | 4 +- src/NadekoBot/Db/Models/XpSettings.cs | 24 +- src/NadekoBot/Db/NadekoContext.cs | 5 +- .../Modules/Administration/Administration.cs | 10 +- .../Administration/AutoAssignRoleCommands.cs | 2 +- .../Administration/Common/ProtectionStats.cs | 9 +- .../Administration/LocalizationCommands.cs | 8 +- .../Modules/Administration/PrefixCommands.cs | 4 +- .../Administration/ProtectionCommands.cs | 10 +- .../Modules/Administration/PruneCommands.cs | 6 +- .../Modules/Administration/RoleCommands.cs | 8 +- .../Modules/Administration/SelfCommands.cs | 12 +- .../Administration/ServerGreetCommands.cs | 4 +- .../Services/AdministrationService.cs | 1 - .../Services/AutoAssignRoleService.cs | 4 +- .../Services/DangerousCommandsService.cs | 4 +- .../Services/GameVoiceChannelService.cs | 3 +- .../Services/ImageOnlyChannelService.cs | 1 - .../Services/LogCommandService.cs | 23 +- .../Administration/Services/MuteService.cs | 1 - .../Services/ProtectionService.cs | 6 +- .../Administration/Services/PruneService.cs | 15 +- .../Services/RoleCommandsService.cs | 4 +- .../Services/SelfAssignedRolesService.cs | 4 +- .../Administration/Services/SelfService.cs | 8 +- .../Services/UserPunishService.cs | 6 +- .../Administration/TimeZoneCommands.cs | 6 +- .../Administration/UserPunishCommands.cs | 2 +- .../CustomReactions/CustomReactions.cs | 2 +- .../Extensions/CustomReactionExtensions.cs | 10 +- .../Services/CustomReactionsService.cs | 2 +- .../Modules/Gambling/BlackJackCommands.cs | 4 +- .../Common/AnimalRacing/AnimalRacingUser.cs | 8 +- .../Common/AnimalRacing/RaceOptions.cs | 2 +- .../Gambling/Common/Blackjack/Blackjack.cs | 4 +- .../Gambling/Common/Blackjack/Player.cs | 4 +- .../Gambling/Common/CurrencyRaffleGame.cs | 12 +- src/NadekoBot/Modules/Gambling/Common/Deck.cs | 10 +- .../Gambling/Common/Events/GameStatusEvent.cs | 7 +- .../Gambling/Common/Events/ReactionEvent.cs | 7 +- .../Modules/Gambling/Common/GamblingConfig.cs | 12 +- .../Gambling/Common/GamblingTopLevelModule.cs | 4 +- .../Modules/Gambling/Connect4/Connect4.cs | 18 +- .../Modules/Gambling/Connect4Commands.cs | 8 +- .../Gambling/CurrencyEventsCommands.cs | 4 +- .../Modules/Gambling/DiceRollCommands.cs | 24 +- .../Modules/Gambling/DrawCommands.cs | 6 +- .../Modules/Gambling/FlipCoinCommands.cs | 2 +- src/NadekoBot/Modules/Gambling/Gambling.cs | 4 +- .../Modules/Gambling/PlantAndPickCommands.cs | 4 +- .../Gambling/Services/GamblingService.cs | 6 +- .../Gambling/Services/Impl/ShopService.cs | 4 +- .../Gambling/Services/PlantPickService.cs | 1 - .../Modules/Gambling/TestGamblingService.cs | 4 +- .../Modules/Gambling/WaifuClaimCommands.cs | 28 ++- .../Modules/Games/AcropobiaCommands.cs | 8 +- .../Modules/Games/CleverBotCommands.cs | 4 +- .../Games/Common/Acrophobia/Acrophobia.cs | 4 +- .../Games/Common/Acrophobia/AcrophobiaUser.cs | 8 +- .../Games/Common/Hangman/HangmanService.cs | 3 +- .../Modules/Games/Common/Nunchi/Nunchi.cs | 4 +- .../Modules/Games/Common/PollRunner.cs | 4 +- .../Modules/Games/Common/TicTacToe.cs | 4 +- .../Modules/Games/Common/Trivia/TriviaGame.cs | 6 +- .../Games/Common/Trivia/TriviaOptions.cs | 4 +- .../Games/Common/Trivia/TriviaQuestion.cs | 2 +- .../Modules/Games/Common/TypingGame.cs | 6 +- src/NadekoBot/Modules/Games/Games.cs | 8 +- .../Modules/Games/HangmanCommands.cs | 16 +- src/NadekoBot/Modules/Games/NunchiCommands.cs | 16 +- src/NadekoBot/Modules/Games/PollCommands.cs | 4 +- .../Games/Services/ChatterbotService.cs | 4 +- .../Modules/Games/Services/GamesService.cs | 4 +- .../Modules/Games/TicTacToeCommands.cs | 4 +- src/NadekoBot/Modules/Help/Help.cs | 9 +- .../Modules/Help/Services/HelpService.cs | 8 +- .../Music/Common/Impl/MultimediaTimer.cs | 4 +- .../Modules/Music/Common/Impl/MusicPlayer.cs | 22 +- .../Music/Common/Impl/RedisTrackCacher.cs | 6 +- .../Modules/Music/Common/Impl/VoiceProxy.cs | 20 +- src/NadekoBot/Modules/Music/Music.cs | 12 +- .../Music/Services/AyuVoiceStateService.cs | 4 +- .../Modules/Music/Services/MusicService.cs | 6 +- .../Music/Services/extractor/YtLoader.cs | 8 +- src/NadekoBot/Modules/Nsfw/Common/DapiTag.cs | 4 +- .../Common/Downloaders/DapiImageDownloader.cs | 4 +- .../Downloaders/KonachanImageDownloader.cs | 4 +- .../Downloaders/YandereImageDownloader.cs | 5 +- .../Modules/Nsfw/Common/ImageData.cs | 4 +- .../Modules/Nsfw/Common/Rule34Object.cs | 4 +- src/NadekoBot/Modules/Nsfw/Nsfw.cs | 5 +- .../Modules/Nsfw/SearchImageCacher.cs | 1 + .../Modules/Nsfw/SearchImagesService.cs | 4 +- .../Modules/Permissions/BlacklistCommands.cs | 8 +- .../Modules/Permissions/CmdCdsCommands.cs | 3 +- .../Modules/Permissions/FilterCommands.cs | 5 +- .../Modules/Permissions/Permissions.cs | 6 +- .../Permissions/Services/CmdCdService.cs | 7 +- .../Permissions/Services/FilterService.cs | 3 +- .../Services/GlobalPermissionService.cs | 4 +- .../Services/PermissionsService.cs | 4 +- .../Modules/Searches/Common/AnimeResult.cs | 2 +- .../Searches/Common/ImageCacherObject.cs | 8 +- .../Modules/Searches/Common/MangaResult.cs | 2 +- .../StreamNotifications/NotifChecker.cs | 4 +- .../Providers/PicartoProvider.cs | 8 +- .../Providers/TwitchProvider.cs | 8 +- .../Modules/Searches/JokeCommands.cs | 8 +- .../Modules/Searches/MemegenCommands.cs | 4 +- .../Modules/Searches/PathOfExileCommands.cs | 4 +- .../Modules/Searches/PlaceCommands.cs | 8 +- .../Modules/Searches/PokemonSearchCommands.cs | 4 +- .../Modules/Searches/Services/FeedsService.cs | 4 +- .../Searches/Services/SearchesService.cs | 13 +- .../Services/StreamNotificationService.cs | 5 +- .../Searches/StreamNotificationCommands.cs | 4 +- .../Modules/Searches/TranslatorCommands.cs | 5 +- .../Modules/Searches/XkcdCommands.cs | 4 +- .../Modules/Utility/ConfigCommands.cs | 8 +- .../Modules/Utility/InviteCommands.cs | 2 +- .../Modules/Utility/QuoteCommands.cs | 4 +- .../Modules/Utility/RepeatCommands.cs | 4 +- .../Modules/Utility/Services/RemindService.cs | 2 +- .../Utility/Services/RepeaterService.cs | 5 +- .../Utility/Services/RunningRepeater.cs | 14 +- .../Utility/Services/StreamRoleService.cs | 10 +- .../Utility/Services/VerboseErrorsService.cs | 3 +- src/NadekoBot/Modules/Utility/Utility.cs | 14 +- src/NadekoBot/Modules/Xp/Club.cs | 4 +- src/NadekoBot/Modules/Xp/Common/XpTemplate.cs | 8 +- .../Modules/Xp/Services/UserCacheItem.cs | 8 +- .../Modules/Xp/Services/XpService.cs | 17 +- src/NadekoBot/Modules/Xp/Xp.cs | 2 +- src/NadekoBot/NadekoBot.csproj | 2 +- src/NadekoBot/Services/CommandHandler.cs | 5 +- src/NadekoBot/Services/Common/GreetGrouper.cs | 4 +- .../Services/GreetSettingsService.cs | 16 +- .../Services/IEmbedBuilderService.cs | 6 +- .../Services/Impl/BehaviorExecutor.cs | 4 +- .../Services/Impl/CurrencyService.cs | 12 +- src/NadekoBot/Services/Impl/Localization.cs | 4 +- .../Services/Impl/RedisImagesCache.cs | 5 +- .../Services/Impl/RedisLocalDataCache.cs | 8 +- .../Services/Impl/RemoteGrpcCoordinator.cs | 8 +- .../Services/Impl/SingleProcessCoordinator.cs | 20 +- .../Services/Impl/SoundCloudApiService.cs | 4 +- .../Impl/StartingGuildsListService.cs | 4 +- src/NadekoBot/Services/Impl/YtdlOperation.cs | 4 +- .../Services/Settings/ConfigServiceBase.cs | 6 +- src/NadekoBot/Services/StandardConversions.cs | 4 +- .../Services/strings/impl/BotStrings.cs | 4 +- src/NadekoBot/_Extensions/ArrayExtensions.cs | 12 +- .../_Extensions/EnumerableExtensions.cs | 85 +++++++ src/NadekoBot/_Extensions/Extensions.cs | 235 ++++++++---------- .../_Extensions/IEnumerableExtensions.cs | 73 ------ .../_Extensions/IMessageChannelExtensions.cs | 170 +++++++------ src/NadekoBot/_Extensions/IUserExtensions.cs | 83 ------- src/NadekoBot/_Extensions/MusicExtensions.cs | 7 - src/NadekoBot/_Extensions/NumberExtensions.cs | 54 ++-- .../_Extensions/ProcessExtensions.cs | 45 ++-- src/NadekoBot/_Extensions/Rgba32Extensions.cs | 15 +- src/NadekoBot/_Extensions/StringExtensions.cs | 81 +++--- src/NadekoBot/_Extensions/UserExtensions.cs | 40 +++ 217 files changed, 1017 insertions(+), 1494 deletions(-) create mode 100644 src/NadekoBot/_Extensions/EnumerableExtensions.cs delete mode 100644 src/NadekoBot/_Extensions/IEnumerableExtensions.cs delete mode 100644 src/NadekoBot/_Extensions/IUserExtensions.cs delete mode 100644 src/NadekoBot/_Extensions/MusicExtensions.cs create mode 100644 src/NadekoBot/_Extensions/UserExtensions.cs diff --git a/.editorconfig b/.editorconfig index 830147454..3f356f43b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,4 +1,4 @@ - + [*] charset = utf-8-bom end_of_line = crlf @@ -109,3 +109,14 @@ resharper_unused_method_return_value_local_highlighting = suggestion resharper_web_config_module_not_resolved_highlighting = warning resharper_web_config_type_not_resolved_highlighting = warning resharper_web_config_wrong_module_highlighting = warning +resharper_convert_to_using_declaration_highlighting = warning + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:warning +csharp_style_expression_bodied_constructors = true:warning +csharp_style_expression_bodied_indexers = true:warning +csharp_style_expression_bodied_lambdas = true:warning +csharp_style_expression_bodied_local_functions = true:warning +csharp_style_expression_bodied_methods = true:warning +csharp_style_expression_bodied_operators = when_on_single_line:suggestion +csharp_style_expression_bodied_properties = true:warning \ No newline at end of file diff --git a/src/NadekoBot/.editorconfig b/src/NadekoBot/.editorconfig index d2a8ed9c5..2b69e7dfd 100644 --- a/src/NadekoBot/.editorconfig +++ b/src/NadekoBot/.editorconfig @@ -1,5 +1,5 @@ -# Remove the line below if you want to inherit .editorconfig settings from higher directories root = true +# Remove the line below if you want to inherit .editorconfig settings from higher directories # C# files [*.cs] @@ -20,7 +20,6 @@ insert_final_newline = false # Organize usings dotnet_separate_import_directive_groups = false dotnet_sort_system_directives_first = false -file_header_template = unset # this. and Me. preferences dotnet_style_qualification_for_event = false @@ -51,8 +50,8 @@ dotnet_style_object_initializer = true dotnet_style_operator_placement_when_wrapping = beginning_of_line dotnet_style_prefer_auto_properties = true:warning dotnet_style_prefer_compound_assignment = true -dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = false:suggestion +dotnet_style_prefer_conditional_expression_over_return = false:suggestion dotnet_style_prefer_inferred_anonymous_type_member_names = true dotnet_style_prefer_inferred_tuple_names = true dotnet_style_prefer_is_null_check_over_reference_equality_method = true:error @@ -65,13 +64,6 @@ dotnet_style_readonly_field = true:suggestion # Parameter preferences dotnet_code_quality_unused_parameters = all:warning -# Suppression preferences -dotnet_remove_unnecessary_suppression_exclusions = none - -# New line preferences -dotnet_style_allow_multiple_blank_lines_experimental = false -dotnet_style_allow_statement_immediately_after_block_experimental = false - #### C# Coding Conventions #### # var preferences @@ -85,8 +77,8 @@ csharp_style_expression_bodied_constructors = when_on_single_line:suggestion csharp_style_expression_bodied_indexers = true:suggestion csharp_style_expression_bodied_lambdas = true:suggestion csharp_style_expression_bodied_local_functions = true:suggestion -csharp_style_expression_bodied_methods = when_on_single_line:suggestion -csharp_style_expression_bodied_operators = when_on_single_line:suggestion +csharp_style_expression_bodied_methods = when_on_single_line:warning +csharp_style_expression_bodied_operators = when_on_single_line:warning csharp_style_expression_bodied_properties = true:suggestion # Pattern matching preferences @@ -123,7 +115,7 @@ csharp_style_unused_value_expression_statement_preference = discard_variable csharp_using_directive_placement = outside_namespace:error # Enforce file-scoped namespaces -csharp_style_namespace_declarations=file_scoped:error +csharp_style_namespace_declarations = file_scoped:error # New line preferences csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true @@ -236,6 +228,7 @@ dotnet_naming_rule.public_anything_should_be_pascal_case.style = pascal_case # Symbol specifications dotnet_naming_symbols.const_fields.required_modifiers = const +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 @@ -316,13 +309,24 @@ dotnet_naming_style.camel_case.word_separator = dotnet_naming_style.camel_case.capitalization = camel_case # CA1822: Mark members as static -dotnet_diagnostic.CA1822.severity = suggestion +dotnet_diagnostic.ca1822.severity = suggestion # IDE0004: Cast is redundant -dotnet_diagnostic.IDE0004.severity = error +dotnet_diagnostic.ide0004.severity = error # IDE0058: Expression value is never used -dotnet_diagnostic.IDE0058.severity = none +dotnet_diagnostic.ide0058.severity = none # IDE0011: Add braces to 'if'/'else' statement -dotnet_diagnostic.IDE0011.severity = none \ No newline at end of file +dotnet_diagnostic.ide0011.severity = none + +resharper_wrap_after_invocation_lpar = false +resharper_wrap_before_invocation_rpar = false + +# ReSharper properties +resharper_csharp_wrap_after_declaration_lpar = true +resharper_csharp_wrap_before_invocation_rpar = true +resharper_csharp_wrap_parameters_style = chop_if_long +resharper_force_chop_compound_if_expression = true +resharper_keep_existing_linebreaks = false +resharper_max_formal_parameters_on_line = 3 diff --git a/src/NadekoBot/Bot.cs b/src/NadekoBot/Bot.cs index 8a90eb1b5..4bf0d1cc3 100644 --- a/src/NadekoBot/Bot.cs +++ b/src/NadekoBot/Bot.cs @@ -70,9 +70,7 @@ public sealed class Bot } public List GetCurrentGuildIds() - { - return Client.Guilds.Select(x => x.Id).ToList(); - } + => Client.Guilds.Select(x => x.Id).ToList(); private void AddServices() { diff --git a/src/NadekoBot/Common/AsyncLazy.cs b/src/NadekoBot/Common/AsyncLazy.cs index 4687ef1ce..3b867e974 100644 --- a/src/NadekoBot/Common/AsyncLazy.cs +++ b/src/NadekoBot/Common/AsyncLazy.cs @@ -12,5 +12,6 @@ public class AsyncLazy : Lazy> base(() => Task.Run(taskFactory)) { } - public TaskAwaiter GetAwaiter() { return Value.GetAwaiter(); } + public TaskAwaiter GetAwaiter() + => Value.GetAwaiter(); } \ No newline at end of file diff --git a/src/NadekoBot/Common/Attributes/NadekoCommand.cs b/src/NadekoBot/Common/Attributes/NadekoCommand.cs index 7e15fa8b5..1c83a6a9f 100644 --- a/src/NadekoBot/Common/Attributes/NadekoCommand.cs +++ b/src/NadekoBot/Common/Attributes/NadekoCommand.cs @@ -7,9 +7,7 @@ public sealed class NadekoCommandAttribute : CommandAttribute { public NadekoCommandAttribute([CallerMemberName] string memberName="") : base(CommandNameLoadHelper.GetCommandNameFor(memberName)) - { - this.MethodName = memberName.ToLowerInvariant(); - } + => this.MethodName = memberName.ToLowerInvariant(); public string MethodName { get; } } \ No newline at end of file diff --git a/src/NadekoBot/Common/Attributes/NadekoOptions.cs b/src/NadekoBot/Common/Attributes/NadekoOptions.cs index ce221b409..5dd506cf3 100644 --- a/src/NadekoBot/Common/Attributes/NadekoOptions.cs +++ b/src/NadekoBot/Common/Attributes/NadekoOptions.cs @@ -6,7 +6,5 @@ public sealed class NadekoOptionsAttribute : Attribute public Type OptionType { get; set; } public NadekoOptionsAttribute(Type t) - { - this.OptionType = t; - } + => this.OptionType = t; } \ No newline at end of file diff --git a/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs b/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs index 2643862ed..8beb73355 100644 --- a/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs +++ b/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs @@ -1,10 +1,9 @@ // License MIT // Source: https://github.com/i3arnon/ConcurrentHashSet -using System.Collections; using System.Diagnostics; -namespace NadekoBot.Common.Collections; +namespace System.Collections.Generic; /// /// Represents a thread-safe hash-based unique collection. @@ -26,7 +25,8 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection PlatformHelper.ProcessorCount; + private static int DefaultConcurrencyLevel + => PlatformHelper.ProcessorCount; /// /// Gets the number of items contained in the : IReadOnlyCollection, ICollection public ConcurrentHashSet() - : this(DefaultConcurrencyLevel, DefaultCapacity, true, EqualityComparer.Default) + : this(DefaultConcurrencyLevel, + DefaultCapacity, + true, + EqualityComparer.Default) { } @@ -119,7 +122,10 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection is less than /// 0. public ConcurrentHashSet(int concurrencyLevel, int capacity) - : this(concurrencyLevel, capacity, false, EqualityComparer.Default) + : this(concurrencyLevel, + capacity, + false, + EqualityComparer.Default) { } @@ -148,7 +154,10 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection /// is a null reference. public ConcurrentHashSet(IEqualityComparer comparer) - : this(DefaultConcurrencyLevel, DefaultCapacity, true, comparer) + : this(DefaultConcurrencyLevel, + DefaultCapacity, + true, + comparer) { } @@ -199,7 +208,10 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection is less than 1. /// public ConcurrentHashSet(int concurrencyLevel, IEnumerable collection, IEqualityComparer comparer) - : this(concurrencyLevel, DefaultCapacity, false, comparer) + : this(concurrencyLevel, + DefaultCapacity, + false, + comparer) { if (collection is null) throw new ArgumentNullException(nameof(collection)); if (comparer is null) throw new ArgumentNullException(nameof(comparer)); @@ -225,7 +237,10 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection /// is a null reference. public ConcurrentHashSet(int concurrencyLevel, int capacity, IEqualityComparer comparer) - : this(concurrencyLevel, capacity, false, comparer) + : this(concurrencyLevel, + capacity, + false, + comparer) { } @@ -264,8 +279,8 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection /// The /// contains too many items. - public bool Add(T item) => - AddInternal(item, _comparer.GetHashCode(item), true); + public bool Add(T item) + => AddInternal(item, _comparer.GetHashCode(item), true); /// /// Removes all items from the . @@ -308,10 +323,12 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() + => GetEnumerator(); /// Returns an enumerator that iterates through the . @@ -396,9 +420,11 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection.Add(T item) => Add(item); + void ICollection.Add(T item) + => Add(item); - bool ICollection.IsReadOnly => false; + bool ICollection.IsReadOnly + => false; void ICollection.CopyTo(T[] array, int arrayIndex) { @@ -417,9 +443,11 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection.Remove(T item) => TryRemove(item); + bool ICollection.Remove(T item) + => TryRemove(item); private void InitializeFromCollection(IEnumerable collection) { @@ -450,7 +479,11 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IList where T : class, IIndexed public int IndexOf(T item) => item.Index; public IndexedCollection() - { - Source = new(); - } - + => Source = new(); + public IndexedCollection(IEnumerable source) { lock (_locker) @@ -125,7 +123,7 @@ public class IndexedCollection : IList where T : class, IIndexed public virtual T this[int index] { - get { return Source[index]; } + get => Source[index]; set { lock (_locker) diff --git a/src/NadekoBot/Common/JsonConverters/Rbga32Converter.cs b/src/NadekoBot/Common/JsonConverters/Rbga32Converter.cs index 86aab413f..9a6b54e89 100644 --- a/src/NadekoBot/Common/JsonConverters/Rbga32Converter.cs +++ b/src/NadekoBot/Common/JsonConverters/Rbga32Converter.cs @@ -8,25 +8,17 @@ namespace NadekoBot.Common.JsonConverters; public class Rgba32Converter : JsonConverter { public override Rgba32 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return Rgba32.ParseHex(reader.GetString()); - } + => Rgba32.ParseHex(reader.GetString()); public override void Write(Utf8JsonWriter writer, Rgba32 value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToHex()); - } + => writer.WriteStringValue(value.ToHex()); } public class CultureInfoConverter : JsonConverter { public override CultureInfo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return new(reader.GetString()); - } + => new(reader.GetString()); public override void Write(Utf8JsonWriter writer, CultureInfo value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.Name); - } + => writer.WriteStringValue(value.Name); } \ No newline at end of file diff --git a/src/NadekoBot/Common/Kwum.cs b/src/NadekoBot/Common/Kwum.cs index fd5cba307..d381d6f43 100644 --- a/src/NadekoBot/Common/Kwum.cs +++ b/src/NadekoBot/Common/Kwum.cs @@ -90,7 +90,5 @@ public readonly struct kwum : IEquatable => other == this; public override int GetHashCode() - { - return _value.GetHashCode(); - } + => _value.GetHashCode(); } \ No newline at end of file diff --git a/src/NadekoBot/Common/LoginErrorHandler.cs b/src/NadekoBot/Common/LoginErrorHandler.cs index b380a378a..7cdaa1d59 100644 --- a/src/NadekoBot/Common/LoginErrorHandler.cs +++ b/src/NadekoBot/Common/LoginErrorHandler.cs @@ -7,10 +7,8 @@ public class LoginErrorHandler { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Handle(Exception ex) - { - Log.Fatal(ex, "A fatal error has occurred while attempting to connect to Discord"); - } - + => Log.Fatal(ex, "A fatal error has occurred while attempting to connect to Discord"); + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Handle(HttpException ex) { diff --git a/src/NadekoBot/Common/NadekoModule.cs b/src/NadekoBot/Common/NadekoModule.cs index ca09a8bf8..fbf6617d7 100644 --- a/src/NadekoBot/Common/NadekoModule.cs +++ b/src/NadekoBot/Common/NadekoModule.cs @@ -22,10 +22,8 @@ public abstract class NadekoModule : ModuleBase } protected override void BeforeExecute(CommandInfo cmd) - { - _cultureInfo = Localization.GetCultureInfo(ctx.Guild?.Id); - } - + => _cultureInfo = Localization.GetCultureInfo(ctx.Guild?.Id); + protected string GetText(in LocStr data) => Strings.GetText(data, _cultureInfo); diff --git a/src/NadekoBot/Common/NadekoRandom.cs b/src/NadekoBot/Common/NadekoRandom.cs index d3234157c..73e3034a2 100644 --- a/src/NadekoBot/Common/NadekoRandom.cs +++ b/src/NadekoBot/Common/NadekoRandom.cs @@ -7,9 +7,7 @@ public class NadekoRandom : Random private readonly RandomNumberGenerator _rng; public NadekoRandom() : base() - { - _rng = RandomNumberGenerator.Create(); - } + => _rng = RandomNumberGenerator.Create(); public override int Next() { @@ -52,9 +50,7 @@ public class NadekoRandom : Random } public override void NextBytes(byte[] buffer) - { - _rng.GetBytes(buffer); - } + => _rng.GetBytes(buffer); protected override double Sample() { diff --git a/src/NadekoBot/Common/PubSub/TypedKey.cs b/src/NadekoBot/Common/PubSub/TypedKey.cs index f1b7fd0aa..3349bdd1c 100644 --- a/src/NadekoBot/Common/PubSub/TypedKey.cs +++ b/src/NadekoBot/Common/PubSub/TypedKey.cs @@ -5,9 +5,7 @@ public readonly struct TypedKey public readonly string Key; public TypedKey(in string key) - { - Key = key; - } + => Key = key; public static implicit operator TypedKey(in string input) => new(input); diff --git a/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs b/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs index 73b801c13..fb82932b8 100644 --- a/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs +++ b/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs @@ -10,17 +10,13 @@ public class ReplacementBuilder private readonly ConcurrentDictionary> _regex = new(); public ReplacementBuilder() - { - WithRngRegex(); - } + => WithRngRegex(); public ReplacementBuilder WithDefault(IUser usr, IMessageChannel ch, SocketGuild g, DiscordSocketClient client) - { - return this.WithUser(usr) + => this.WithUser(usr) .WithChannel(ch) .WithServer(client, g) .WithClient(client); - } public ReplacementBuilder WithDefault(ICommandContext ctx) => WithDefault(ctx.User, ctx.Channel, ctx.Guild as SocketGuild, (DiscordSocketClient)ctx.Client); @@ -139,9 +135,7 @@ public class ReplacementBuilder } public Replacer Build() - { - return new(_reps.Select(x => (x.Key, x.Value)).ToArray(), _regex.Select(x => (x.Key, x.Value)).ToArray()); - } + => new(_reps.Select(x => (x.Key, x.Value)).ToArray(), _regex.Select(x => (x.Key, x.Value)).ToArray()); public ReplacementBuilder WithProviders(IEnumerable phProviders) { diff --git a/src/NadekoBot/Common/ShmartNumber.cs b/src/NadekoBot/Common/ShmartNumber.cs index b3b0e57f8..297bfadbd 100644 --- a/src/NadekoBot/Common/ShmartNumber.cs +++ b/src/NadekoBot/Common/ShmartNumber.cs @@ -12,49 +12,31 @@ public struct ShmartNumber : IEquatable } public static implicit operator ShmartNumber(long num) - { - return new(num); - } + => new(num); public static implicit operator long(ShmartNumber num) - { - return num.Value; - } + => num.Value; public static implicit operator ShmartNumber(int num) - { - return new(num); - } + => new(num); public override string ToString() - { - return Value.ToString(); - } + => Value.ToString(); public override bool Equals(object obj) - { - return obj is ShmartNumber sn + => obj is ShmartNumber sn ? Equals(sn) : false; - } public bool Equals(ShmartNumber other) - { - return other.Value == Value; - } + => other.Value == Value; public override int GetHashCode() - { - return Value.GetHashCode() ^ Input.GetHashCode(StringComparison.InvariantCulture); - } + => Value.GetHashCode() ^ Input.GetHashCode(StringComparison.InvariantCulture); public static bool operator ==(ShmartNumber left, ShmartNumber right) - { - return left.Equals(right); - } + => left.Equals(right); public static bool operator !=(ShmartNumber left, ShmartNumber right) - { - return !(left == right); - } + => !(left == right); } \ No newline at end of file diff --git a/src/NadekoBot/Common/SmartText/SmartPlainText.cs b/src/NadekoBot/Common/SmartText/SmartPlainText.cs index 2d67df1e2..95c7f2fdc 100644 --- a/src/NadekoBot/Common/SmartText/SmartPlainText.cs +++ b/src/NadekoBot/Common/SmartText/SmartPlainText.cs @@ -5,9 +5,7 @@ public sealed record SmartPlainText : SmartText public string Text { get; init; } public SmartPlainText(string text) - { - Text = text; - } + => Text = text; public static implicit operator SmartPlainText(string input) => new(input); @@ -16,7 +14,5 @@ public sealed record SmartPlainText : SmartText => input.Text; public override string ToString() - { - return Text; - } + => Text; } \ No newline at end of file diff --git a/src/NadekoBot/Common/TypeReaders/BotCommandTypeReader.cs b/src/NadekoBot/Common/TypeReaders/BotCommandTypeReader.cs index e469701b2..8bb7eddec 100644 --- a/src/NadekoBot/Common/TypeReaders/BotCommandTypeReader.cs +++ b/src/NadekoBot/Common/TypeReaders/BotCommandTypeReader.cs @@ -20,7 +20,7 @@ public sealed class CommandTypeReader : NadekoTypeReader if (!input.StartsWith(prefix.ToUpperInvariant(), StringComparison.InvariantCulture)) return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No such command found.")); - input = input.Substring(prefix.Length); + input = input[prefix.Length..]; var cmd = _cmds.Commands.FirstOrDefault(c => c.Aliases.Select(a => a.ToUpperInvariant()).Contains(input)); if (cmd is null) diff --git a/src/NadekoBot/Common/TypeReaders/GuildDateTimeTypeReader.cs b/src/NadekoBot/Common/TypeReaders/GuildDateTimeTypeReader.cs index d7eed9908..62ece22b9 100644 --- a/src/NadekoBot/Common/TypeReaders/GuildDateTimeTypeReader.cs +++ b/src/NadekoBot/Common/TypeReaders/GuildDateTimeTypeReader.cs @@ -7,10 +7,8 @@ public sealed class GuildDateTimeTypeReader : NadekoTypeReader private readonly GuildTimezoneService _gts; public GuildDateTimeTypeReader(GuildTimezoneService gts) - { - _gts = gts; - } - + => _gts = gts; + public override Task ReadAsync(ICommandContext context, string input) { var gdt = Parse(context.Guild.Id, input); diff --git a/src/NadekoBot/Common/TypeReaders/GuildTypeReader.cs b/src/NadekoBot/Common/TypeReaders/GuildTypeReader.cs index 13e10247c..710ea5139 100644 --- a/src/NadekoBot/Common/TypeReaders/GuildTypeReader.cs +++ b/src/NadekoBot/Common/TypeReaders/GuildTypeReader.cs @@ -5,9 +5,7 @@ public sealed class GuildTypeReader : NadekoTypeReader private readonly DiscordSocketClient _client; public GuildTypeReader(DiscordSocketClient client) - { - _client = client; - } + => _client = client; public override Task ReadAsync(ICommandContext context, string input) { diff --git a/src/NadekoBot/Common/TypeReaders/KwumTypeReader.cs b/src/NadekoBot/Common/TypeReaders/KwumTypeReader.cs index 689552668..bbdd046b0 100644 --- a/src/NadekoBot/Common/TypeReaders/KwumTypeReader.cs +++ b/src/NadekoBot/Common/TypeReaders/KwumTypeReader.cs @@ -14,7 +14,5 @@ public sealed class KwumTypeReader : NadekoTypeReader public sealed class SmartTextTypeReader : NadekoTypeReader { public override Task ReadAsync(ICommandContext ctx, string input) - { - return Task.FromResult(TypeReaderResult.FromSuccess(SmartText.CreateFrom(input))); - } + => Task.FromResult(TypeReaderResult.FromSuccess(SmartText.CreateFrom(input))); } \ No newline at end of file diff --git a/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs b/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs index 066bdebc5..c9e5e355a 100644 --- a/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs +++ b/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs @@ -8,9 +8,7 @@ public class PermissionAction public bool Value { get; } public PermissionAction(bool value) - { - this.Value = value; - } + => this.Value = value; public override bool Equals(object obj) { diff --git a/src/NadekoBot/Common/TypeReaders/ModuleTypeReader.cs b/src/NadekoBot/Common/TypeReaders/ModuleTypeReader.cs index 90ef3ab7d..44882b2cd 100644 --- a/src/NadekoBot/Common/TypeReaders/ModuleTypeReader.cs +++ b/src/NadekoBot/Common/TypeReaders/ModuleTypeReader.cs @@ -5,9 +5,7 @@ public sealed class ModuleTypeReader : NadekoTypeReader private readonly CommandService _cmds; public ModuleTypeReader(CommandService cmds) - { - _cmds = cmds; - } + => _cmds = cmds; public override Task ReadAsync(ICommandContext context, string input) { @@ -25,9 +23,7 @@ public sealed class ModuleOrCrTypeReader : NadekoTypeReader private readonly CommandService _cmds; public ModuleOrCrTypeReader(CommandService cmds) - { - _cmds = cmds; - } + => _cmds = cmds; public override Task ReadAsync(ICommandContext context, string input) { diff --git a/src/NadekoBot/Common/Yml/CommentAttribute.cs b/src/NadekoBot/Common/Yml/CommentAttribute.cs index 0be600ffc..e2a3978d1 100644 --- a/src/NadekoBot/Common/Yml/CommentAttribute.cs +++ b/src/NadekoBot/Common/Yml/CommentAttribute.cs @@ -5,7 +5,5 @@ public class CommentAttribute : Attribute public string Comment { get; } public CommentAttribute(string comment) - { - Comment = comment; - } + => Comment = comment; } \ No newline at end of file diff --git a/src/NadekoBot/Common/Yml/CommentGatheringTypeInspector.cs b/src/NadekoBot/Common/Yml/CommentGatheringTypeInspector.cs index cfb47d3be..22795112d 100644 --- a/src/NadekoBot/Common/Yml/CommentGatheringTypeInspector.cs +++ b/src/NadekoBot/Common/Yml/CommentGatheringTypeInspector.cs @@ -9,16 +9,12 @@ public class CommentGatheringTypeInspector : TypeInspectorSkeleton private readonly ITypeInspector innerTypeDescriptor; public CommentGatheringTypeInspector(ITypeInspector innerTypeDescriptor) - { - this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); - } + => this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); public override IEnumerable GetProperties(Type type, object container) - { - return innerTypeDescriptor + => innerTypeDescriptor .GetProperties(type, container) .Select(d => new CommentsPropertyDescriptor(d)); - } private sealed class CommentsPropertyDescriptor : IPropertyDescriptor { @@ -32,31 +28,29 @@ public class CommentGatheringTypeInspector : TypeInspectorSkeleton public string Name { get; set; } - public Type Type { get { return baseDescriptor.Type; } } + public Type Type + => baseDescriptor.Type; public Type TypeOverride { - get { return baseDescriptor.TypeOverride; } - set { baseDescriptor.TypeOverride = value; } + get => baseDescriptor.TypeOverride; + set => baseDescriptor.TypeOverride = value; } public int Order { get; set; } public ScalarStyle ScalarStyle { - get { return baseDescriptor.ScalarStyle; } - set { baseDescriptor.ScalarStyle = value; } + get => baseDescriptor.ScalarStyle; + set => baseDescriptor.ScalarStyle = value; } - public bool CanWrite { get { return baseDescriptor.CanWrite; } } + public bool CanWrite + => baseDescriptor.CanWrite; public void Write(object target, object value) - { - baseDescriptor.Write(target, value); - } + => baseDescriptor.Write(target, value); public T GetCustomAttribute() where T : Attribute - { - return baseDescriptor.GetCustomAttribute(); - } + => baseDescriptor.GetCustomAttribute(); public IObjectDescriptor Read(object target) { diff --git a/src/NadekoBot/Common/Yml/CommentsObjectDescriptor.cs b/src/NadekoBot/Common/Yml/CommentsObjectDescriptor.cs index f5600ee9e..672404b47 100644 --- a/src/NadekoBot/Common/Yml/CommentsObjectDescriptor.cs +++ b/src/NadekoBot/Common/Yml/CommentsObjectDescriptor.cs @@ -15,8 +15,15 @@ public sealed class CommentsObjectDescriptor : IObjectDescriptor public string Comment { get; private set; } - public object Value { get { return innerDescriptor.Value; } } - public Type Type { get { return innerDescriptor.Type; } } - public Type StaticType { get { return innerDescriptor.StaticType; } } - public ScalarStyle ScalarStyle { get { return innerDescriptor.ScalarStyle; } } + public object Value + => innerDescriptor.Value; + + public Type Type + => innerDescriptor.Type; + + public Type StaticType + => innerDescriptor.StaticType; + + public ScalarStyle ScalarStyle + => innerDescriptor.ScalarStyle; } \ No newline at end of file diff --git a/src/NadekoBot/Common/Yml/Rgba32Converter.cs b/src/NadekoBot/Common/Yml/Rgba32Converter.cs index fb46192ef..173d4acc0 100644 --- a/src/NadekoBot/Common/Yml/Rgba32Converter.cs +++ b/src/NadekoBot/Common/Yml/Rgba32Converter.cs @@ -9,9 +9,7 @@ namespace NadekoBot.Common.Yml; public class Rgba32Converter : IYamlTypeConverter { public bool Accepts(Type type) - { - return type == typeof(Rgba32); - } + => type == typeof(Rgba32); public object ReadYaml(IParser parser, Type type) { @@ -31,9 +29,7 @@ public class Rgba32Converter : IYamlTypeConverter public class CultureInfoConverter : IYamlTypeConverter { public bool Accepts(Type type) - { - return type == typeof(CultureInfo); - } + => type == typeof(CultureInfo); public object ReadYaml(IParser parser, Type type) { diff --git a/src/NadekoBot/Common/Yml/UriConverter.cs b/src/NadekoBot/Common/Yml/UriConverter.cs index f02990c97..a2c36282a 100644 --- a/src/NadekoBot/Common/Yml/UriConverter.cs +++ b/src/NadekoBot/Common/Yml/UriConverter.cs @@ -7,9 +7,7 @@ namespace NadekoBot.Common.Yml; public class UriConverter : IYamlTypeConverter { public bool Accepts(Type type) - { - return type == typeof(Uri); - } + => type == typeof(Uri); public object ReadYaml(IParser parser, Type type) { diff --git a/src/NadekoBot/Common/Yml/YamlHelper.cs b/src/NadekoBot/Common/Yml/YamlHelper.cs index 89993117b..684f82f98 100644 --- a/src/NadekoBot/Common/Yml/YamlHelper.cs +++ b/src/NadekoBot/Common/Yml/YamlHelper.cs @@ -26,7 +26,7 @@ public class YamlHelper // Check the value and write the character. - if (character is >= 0xD800 and <= 0xDFFF || character > 0x10FFFF) + if (character is >= 0xD800 and <= 0xDFFF or > 0x10FFFF) { return point; } @@ -35,13 +35,8 @@ public class YamlHelper } public static bool IsHex(char c) - { - return - c is >= '0' and <= '9' || - c is >= 'A' and <= 'F' || - c is >= 'a' and <= 'f'; - } - + => c is >= '0' and <= '9' or >= 'A' and <= 'F' or >= 'a' and <= 'f'; + public static int AsHex(char c) { if (c <= '9') diff --git a/src/NadekoBot/Db/Extensions/ClubExtensions.cs b/src/NadekoBot/Db/Extensions/ClubExtensions.cs index f3c8fdc96..a5f5e6325 100644 --- a/src/NadekoBot/Db/Extensions/ClubExtensions.cs +++ b/src/NadekoBot/Db/Extensions/ClubExtensions.cs @@ -34,12 +34,10 @@ public static class ClubExtensions .Max() + 1; public static List GetClubLeaderboardPage(this DbSet clubs, int page) - { - return clubs + => clubs .AsNoTracking() .OrderByDescending(x => x.Xp) .Skip(page * 9) .Take(9) .ToList(); - } } \ No newline at end of file diff --git a/src/NadekoBot/Db/Extensions/CurrencyTransactionExtensions.cs b/src/NadekoBot/Db/Extensions/CurrencyTransactionExtensions.cs index 080bf4ec8..9bf9ad5a4 100644 --- a/src/NadekoBot/Db/Extensions/CurrencyTransactionExtensions.cs +++ b/src/NadekoBot/Db/Extensions/CurrencyTransactionExtensions.cs @@ -6,13 +6,11 @@ namespace NadekoBot.Db; public static class CurrencyTransactionExtensions { public static List GetPageFor(this DbSet set, ulong userId, int page) - { - return set.AsQueryable() + => set.AsQueryable() .AsNoTracking() .Where(x => x.UserId == userId) .OrderByDescending(x => x.DateAdded) .Skip(15 * page) .Take(15) .ToList(); - } } \ No newline at end of file diff --git a/src/NadekoBot/Db/Extensions/CustomReactionsExtensions.cs b/src/NadekoBot/Db/Extensions/CustomReactionsExtensions.cs index 30718dad3..a56459e26 100644 --- a/src/NadekoBot/Db/Extensions/CustomReactionsExtensions.cs +++ b/src/NadekoBot/Db/Extensions/CustomReactionsExtensions.cs @@ -7,21 +7,15 @@ namespace NadekoBot.Db; public static class CustomReactionsExtensions { public static int ClearFromGuild(this DbSet crs, ulong guildId) - { - return crs.Delete(x => x.GuildId == guildId); - } + => crs.Delete(x => x.GuildId == guildId); public static IEnumerable ForId(this DbSet crs, ulong id) - { - return crs + => crs .AsNoTracking() .AsQueryable() .Where(x => x.GuildId == id) .ToArray(); - } public static CustomReaction GetByGuildIdAndInput(this DbSet crs, ulong? guildId, string input) - { - return crs.FirstOrDefault(x => x.GuildId == guildId && x.Trigger.ToUpper() == input); - } + => crs.FirstOrDefault(x => x.GuildId == guildId && x.Trigger.ToUpper() == input); } \ No newline at end of file diff --git a/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs b/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs index 3db4ffadf..99d2673e8 100644 --- a/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs +++ b/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs @@ -9,8 +9,7 @@ namespace NadekoBot.Db; public static class DiscordUserExtensions { public static void EnsureUserCreated(this NadekoContext ctx, ulong userId, string username, string discrim, string avatarId) - { - ctx.DiscordUser + => ctx.DiscordUser .ToLinqToDBTable() .InsertOrUpdate(() => new() { @@ -30,7 +29,6 @@ public static class DiscordUserExtensions { UserId = userId }); - } //temp is only used in updatecurrencystate, so that i don't overwrite real usernames/discrims with Unknown public static DiscordUser GetOrCreateUser(this NadekoContext ctx, ulong userId, string username, string discrim, string avatarId) @@ -45,44 +43,36 @@ public static class DiscordUserExtensions => ctx.GetOrCreateUser(original.Id, original.Username, original.Discriminator, original.AvatarId); public static int GetUserGlobalRank(this DbSet users, ulong id) - { - return users.AsQueryable() + => users.AsQueryable() .Where(x => x.TotalXp > users .AsQueryable() .Where(y => y.UserId == id) .Select(y => y.TotalXp) .FirstOrDefault()) .Count() + 1; - } public static DiscordUser[] GetUsersXpLeaderboardFor(this DbSet users, int page) - { - return users.AsQueryable() + => users.AsQueryable() .OrderByDescending(x => x.TotalXp) .Skip(page * 9) .Take(9) .AsEnumerable() .ToArray(); - } public static List GetTopRichest(this DbSet users, ulong botId, int count, int page = 0) - { - return users.AsQueryable() + => users.AsQueryable() .Where(c => c.CurrencyAmount > 0 && botId != c.UserId) .OrderByDescending(c => c.CurrencyAmount) .Skip(page * 9) .Take(count) .ToList(); - } public static List GetTopRichest(this DbSet users, ulong botId, int count) - { - return users.AsQueryable() + => users.AsQueryable() .Where(c => c.CurrencyAmount > 0 && botId != c.UserId) .OrderByDescending(c => c.CurrencyAmount) .Take(count) .ToList(); - } public static long GetUserCurrency(this DbSet users, ulong userId) => users.AsNoTracking() @@ -163,17 +153,13 @@ VALUES ({userId}, {name}, {discrim}, {avatarId}, {amount}, 0); } public static decimal GetTotalCurrency(this DbSet users) - { - return users + => users .Sum((Func)(x => x.CurrencyAmount)); - } public static decimal GetTopOnePercentCurrency(this DbSet users, ulong botId) - { - return users.AsQueryable() + => users.AsQueryable() .Where(x => x.UserId != botId) .OrderByDescending(x => x.CurrencyAmount) .Take(users.Count() / 100 == 0 ? 1 : users.Count() / 100) .Sum(x => x.CurrencyAmount); - } } \ No newline at end of file diff --git a/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs b/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs index 649a08222..e35cd38a7 100644 --- a/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs +++ b/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs @@ -44,20 +44,17 @@ public static class GuildConfigExtensions }; private static IQueryable IncludeEverything(this DbSet configs) - { - return configs - .AsQueryable() - .AsSplitQuery() - .Include(gc => gc.CommandCooldowns) - .Include(gc => gc.FollowedStreams) - .Include(gc => gc.StreamRole) - .Include(gc => gc.XpSettings) - .ThenInclude(x => x.ExclusionList) - .Include(gc => gc.DelMsgOnCmdChannels) - .Include(gc => gc.ReactionRoleMessages) - .ThenInclude(x => x.ReactionRoles) - ; - } + => configs + .AsQueryable() + .AsSplitQuery() + .Include(gc => gc.CommandCooldowns) + .Include(gc => gc.FollowedStreams) + .Include(gc => gc.StreamRole) + .Include(gc => gc.XpSettings) + .ThenInclude(x => x.ExclusionList) + .Include(gc => gc.DelMsgOnCmdChannels) + .Include(gc => gc.ReactionRoleMessages) + .ThenInclude(x => x.ReactionRoles); public static IEnumerable GetAllGuildConfigs(this DbSet configs, List availableGuilds) => configs @@ -168,22 +165,18 @@ public static class GuildConfigExtensions } public static IEnumerable GetFollowedStreams(this DbSet configs) - { - return configs + => configs .AsQueryable() .Include(x => x.FollowedStreams) .SelectMany(gc => gc.FollowedStreams) .ToArray(); - } public static IEnumerable GetFollowedStreams(this DbSet configs, List included) - { - return configs.AsQueryable() + => configs.AsQueryable() .Where(gc => included.Contains(gc.GuildId)) .Include(gc => gc.FollowedStreams) .SelectMany(gc => gc.FollowedStreams) .ToList(); - } public static void SetCleverbotEnabled(this DbSet configs, ulong id, bool cleverbotEnabled) { @@ -212,8 +205,7 @@ public static class GuildConfigExtensions } public static IEnumerable GetGeneratingChannels(this DbSet configs) - { - return configs + => configs .AsQueryable() .Include(x => x.GenerateCurrencyChannelIds) .Where(x => x.GenerateCurrencyChannelIds.Any()) @@ -224,5 +216,4 @@ public static class GuildConfigExtensions GuildId = x.GuildConfig.GuildId }) .ToArray(); - } } \ No newline at end of file diff --git a/src/NadekoBot/Db/Extensions/PollExtensions.cs b/src/NadekoBot/Db/Extensions/PollExtensions.cs index c719333ab..45a431c31 100644 --- a/src/NadekoBot/Db/Extensions/PollExtensions.cs +++ b/src/NadekoBot/Db/Extensions/PollExtensions.cs @@ -7,11 +7,9 @@ namespace NadekoBot.Db; public static class PollExtensions { public static IEnumerable GetAllPolls(this DbSet polls) - { - return polls.Include(x => x.Answers) + => polls.Include(x => x.Answers) .Include(x => x.Votes) .ToArray(); - } public static void RemovePoll(this NadekoContext ctx, int id) { diff --git a/src/NadekoBot/Db/Extensions/QuoteExtensions.cs b/src/NadekoBot/Db/Extensions/QuoteExtensions.cs index 91be224e7..0800056d2 100644 --- a/src/NadekoBot/Db/Extensions/QuoteExtensions.cs +++ b/src/NadekoBot/Db/Extensions/QuoteExtensions.cs @@ -6,10 +6,8 @@ namespace NadekoBot.Db; public static class QuoteExtensions { public static IEnumerable GetForGuild(this DbSet quotes, ulong guildId) - { - return quotes.AsQueryable().Where(x => x.GuildId == guildId); - } - + => quotes.AsQueryable().Where(x => x.GuildId == guildId); + public static IEnumerable GetGroup(this DbSet quotes, ulong guildId, int page, OrderType order) { var q = quotes.AsQueryable().Where(x => x.GuildId == guildId); @@ -46,8 +44,5 @@ public static class QuoteExtensions } public static void RemoveAllByKeyword(this DbSet quotes, ulong guildId, string keyword) - { - quotes.RemoveRange(quotes.AsQueryable().Where(x => x.GuildId == guildId && x.Keyword.ToUpper() == keyword)); - } - + => quotes.RemoveRange(quotes.AsQueryable().Where(x => x.GuildId == guildId && x.Keyword.ToUpper() == keyword)); } \ No newline at end of file diff --git a/src/NadekoBot/Db/Extensions/UserXpExtensions.cs b/src/NadekoBot/Db/Extensions/UserXpExtensions.cs index c04d44c16..d2c87b63f 100644 --- a/src/NadekoBot/Db/Extensions/UserXpExtensions.cs +++ b/src/NadekoBot/Db/Extensions/UserXpExtensions.cs @@ -26,8 +26,7 @@ public static class UserXpExtensions } public static List GetUsersFor(this DbSet xps, ulong guildId, int page) - { - return xps + => xps .AsQueryable() .AsNoTracking() .Where(x => x.GuildId == guildId) @@ -35,29 +34,24 @@ public static class UserXpExtensions .Skip(page * 9) .Take(9) .ToList(); - } public static List GetTopUserXps(this DbSet xps, ulong guildId, int count) - { - return xps + => xps .AsQueryable() .AsNoTracking() .Where(x => x.GuildId == guildId) .OrderByDescending(x => x.Xp + x.AwardedXp) .Take(count) .ToList(); - } public static int GetUserGuildRanking(this DbSet xps, ulong userId, ulong guildId) - { // @"SELECT COUNT(*) + 1 //FROM UserXpStats //WHERE GuildId = @p1 AND ((Xp + AwardedXp) > (SELECT Xp + AwardedXp // FROM UserXpStats // WHERE UserId = @p2 AND GuildId = @p1 // LIMIT 1));"; - - return xps + => xps .AsQueryable() .AsNoTracking() .Where(x => x.GuildId == guildId && x.Xp + x.AwardedXp > @@ -66,15 +60,10 @@ public static class UserXpExtensions .Select(y => y.Xp + y.AwardedXp) .FirstOrDefault()) .Count() + 1; - } public static void ResetGuildUserXp(this DbSet xps, ulong userId, ulong guildId) - { - xps.Delete(x => x.UserId == userId && x.GuildId == guildId); - } + => xps.Delete(x => x.UserId == userId && x.GuildId == guildId); public static void ResetGuildXp(this DbSet xps, ulong guildId) - { - xps.Delete(x => x.GuildId == guildId); - } + => xps.Delete(x => x.GuildId == guildId); } \ No newline at end of file diff --git a/src/NadekoBot/Db/Extensions/WaifuExtensions.cs b/src/NadekoBot/Db/Extensions/WaifuExtensions.cs index 7b7a409b7..6efbd9a16 100644 --- a/src/NadekoBot/Db/Extensions/WaifuExtensions.cs +++ b/src/NadekoBot/Db/Extensions/WaifuExtensions.cs @@ -65,24 +65,20 @@ public static class WaifuExtensions } public static decimal GetTotalValue(this DbSet waifus) - { - return waifus + => waifus .AsQueryable() .Where(x => x.ClaimerId != null) .Sum(x => x.Price); - } public static ulong GetWaifuUserId(this DbSet waifus, ulong ownerId, string name) - { - return waifus + => waifus .AsQueryable() .AsNoTracking() .Where(x => x.Claimer.UserId == ownerId && x.Waifu.Username + "#" + x.Waifu.Discriminator == name) .Select(x => x.Waifu.UserId) .FirstOrDefault(); - } - + public static WaifuInfoStats GetWaifuInfo(this NadekoContext ctx, ulong userId) { ctx.Database.ExecuteSqlInterpolated($@" diff --git a/src/NadekoBot/Db/Extensions/WarningExtensions.cs b/src/NadekoBot/Db/Extensions/WarningExtensions.cs index c2a1ebdb7..3ef9c34ef 100644 --- a/src/NadekoBot/Db/Extensions/WarningExtensions.cs +++ b/src/NadekoBot/Db/Extensions/WarningExtensions.cs @@ -33,8 +33,7 @@ public static class WarningExtensions } public static async Task ForgiveAll(this DbSet warnings, ulong guildId, ulong userId, string mod) - { - await warnings.AsQueryable().Where(x => x.GuildId == guildId && x.UserId == userId) + => await warnings.AsQueryable().Where(x => x.GuildId == guildId && x.UserId == userId) .ForEachAsync(x => { if (x.Forgiven != true) @@ -43,10 +42,7 @@ public static class WarningExtensions x.ForgivenBy = mod; } }); - } public static Warning[] GetForGuild(this DbSet warnings, ulong id) - { - return warnings.AsQueryable().Where(x => x.GuildId == id).ToArray(); - } + => warnings.AsQueryable().Where(x => x.GuildId == id).ToArray(); } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/AntiProtection.cs b/src/NadekoBot/Db/Models/AntiProtection.cs index 7aaed51d8..2aaeb422b 100644 --- a/src/NadekoBot/Db/Models/AntiProtection.cs +++ b/src/NadekoBot/Db/Models/AntiProtection.cs @@ -57,9 +57,7 @@ public class AntiSpamIgnore : DbEntity public override int GetHashCode() => ChannelId.GetHashCode(); public override bool Equals(object obj) - { - return obj is AntiSpamIgnore inst + => obj is AntiSpamIgnore inst ? inst.ChannelId == ChannelId : false; - } } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/ClubInfo.cs b/src/NadekoBot/Db/Models/ClubInfo.cs index 60ffe4ce4..0e3144212 100644 --- a/src/NadekoBot/Db/Models/ClubInfo.cs +++ b/src/NadekoBot/Db/Models/ClubInfo.cs @@ -23,9 +23,7 @@ public class ClubInfo : DbEntity public string Description { get; set; } public override string ToString() - { - return Name + "#" + Discrim; - } + => Name + "#" + Discrim; } public class ClubApplicants diff --git a/src/NadekoBot/Db/Models/CustomReaction.cs b/src/NadekoBot/Db/Models/CustomReaction.cs index eb72526f4..7c63f0782 100644 --- a/src/NadekoBot/Db/Models/CustomReaction.cs +++ b/src/NadekoBot/Db/Models/CustomReaction.cs @@ -17,7 +17,7 @@ public class CustomReaction : DbEntity ? Array.Empty() : Reactions.Split("@@@"); - public bool IsGlobal() => GuildId is null || GuildId == 0; + public bool IsGlobal() => GuildId is null or 0; } public class ReactionResponse : DbEntity diff --git a/src/NadekoBot/Db/Models/DelMsgOnCmdChannel.cs b/src/NadekoBot/Db/Models/DelMsgOnCmdChannel.cs index a7b8c28c0..8378f9251 100644 --- a/src/NadekoBot/Db/Models/DelMsgOnCmdChannel.cs +++ b/src/NadekoBot/Db/Models/DelMsgOnCmdChannel.cs @@ -6,13 +6,9 @@ public class DelMsgOnCmdChannel : DbEntity public bool State { get; set; } public override int GetHashCode() - { - return ChannelId.GetHashCode(); - } + => ChannelId.GetHashCode(); public override bool Equals(object obj) - { - return obj is DelMsgOnCmdChannel x - && x.ChannelId == ChannelId; - } + => obj is DelMsgOnCmdChannel x + && x.ChannelId == ChannelId; } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/DiscordUser.cs b/src/NadekoBot/Db/Models/DiscordUser.cs index 60b3db891..33cf66df9 100644 --- a/src/NadekoBot/Db/Models/DiscordUser.cs +++ b/src/NadekoBot/Db/Models/DiscordUser.cs @@ -20,16 +20,12 @@ public class DiscordUser : DbEntity public long CurrencyAmount { get; set; } public override bool Equals(object obj) - { - return obj is DiscordUser du + => obj is DiscordUser du ? du.UserId == UserId : false; - } public override int GetHashCode() - { - return UserId.GetHashCode(); - } + => UserId.GetHashCode(); public override string ToString() => Username + "#" + Discriminator; diff --git a/src/NadekoBot/Db/Models/FeedSub.cs b/src/NadekoBot/Db/Models/FeedSub.cs index d21a04e15..55f83c1d0 100644 --- a/src/NadekoBot/Db/Models/FeedSub.cs +++ b/src/NadekoBot/Db/Models/FeedSub.cs @@ -9,14 +9,10 @@ public class FeedSub : DbEntity public string Url { get; set; } public override int GetHashCode() - { - return Url.GetHashCode(StringComparison.InvariantCulture) ^ GuildConfigId.GetHashCode(); - } + => Url.GetHashCode(StringComparison.InvariantCulture) ^ GuildConfigId.GetHashCode(); public override bool Equals(object obj) - { - return obj is FeedSub s - && s.Url.ToLower() == Url.ToLower() - && s.GuildConfigId == GuildConfigId; - } + => obj is FeedSub s + && s.Url.ToLower() == Url.ToLower() + && s.GuildConfigId == GuildConfigId; } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/FollowedStream.cs b/src/NadekoBot/Db/Models/FollowedStream.cs index 8c02989d3..b197422f3 100644 --- a/src/NadekoBot/Db/Models/FollowedStream.cs +++ b/src/NadekoBot/Db/Models/FollowedStream.cs @@ -20,16 +20,12 @@ public class FollowedStream : DbEntity } protected bool Equals(FollowedStream other) - { - return ChannelId == other.ChannelId - && Username.Trim().ToUpperInvariant() == other.Username.Trim().ToUpperInvariant() - && Type == other.Type; - } + => ChannelId == other.ChannelId + && Username.Trim().ToUpperInvariant() == other.Username.Trim().ToUpperInvariant() + && Type == other.Type; public override int GetHashCode() - { - return HashCode.Combine(ChannelId, Username, (int) Type); - } + => HashCode.Combine(ChannelId, Username, (int) Type); public override bool Equals(object obj) => obj is FollowedStream fs && Equals(fs); diff --git a/src/NadekoBot/Db/Models/GCChannelId.cs b/src/NadekoBot/Db/Models/GCChannelId.cs index 34edd8a6d..8c3ebc017 100644 --- a/src/NadekoBot/Db/Models/GCChannelId.cs +++ b/src/NadekoBot/Db/Models/GCChannelId.cs @@ -6,11 +6,9 @@ public class GCChannelId : DbEntity public ulong ChannelId { get; set; } public override bool Equals(object obj) - { - return obj is GCChannelId gc + => obj is GCChannelId gc ? gc.ChannelId == ChannelId : false; - } public override int GetHashCode() => this.ChannelId.GetHashCode(); diff --git a/src/NadekoBot/Db/Models/MutedUserId.cs b/src/NadekoBot/Db/Models/MutedUserId.cs index 812efd25a..026788967 100644 --- a/src/NadekoBot/Db/Models/MutedUserId.cs +++ b/src/NadekoBot/Db/Models/MutedUserId.cs @@ -5,14 +5,10 @@ public class MutedUserId : DbEntity public ulong UserId { get; set; } public override int GetHashCode() - { - return UserId.GetHashCode(); - } + => UserId.GetHashCode(); public override bool Equals(object obj) - { - return obj is MutedUserId mui + => obj is MutedUserId mui ? mui.UserId == UserId : false; - } } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/PollVote.cs b/src/NadekoBot/Db/Models/PollVote.cs index 3d5c12ed6..4523bde5b 100644 --- a/src/NadekoBot/Db/Models/PollVote.cs +++ b/src/NadekoBot/Db/Models/PollVote.cs @@ -6,14 +6,10 @@ public class PollVote : DbEntity public int VoteIndex { get; set; } public override int GetHashCode() - { - return UserId.GetHashCode(); - } + => UserId.GetHashCode(); public override bool Equals(object obj) - { - return obj is PollVote p + => obj is PollVote p ? p.UserId == UserId : false; - } } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/SlowmodeIgnoredRole.cs b/src/NadekoBot/Db/Models/SlowmodeIgnoredRole.cs index 8e2ccc902..66c592af0 100644 --- a/src/NadekoBot/Db/Models/SlowmodeIgnoredRole.cs +++ b/src/NadekoBot/Db/Models/SlowmodeIgnoredRole.cs @@ -17,7 +17,5 @@ public class SlowmodeIgnoredRole : DbEntity // override object.GetHashCode public override int GetHashCode() - { - return RoleId.GetHashCode(); - } + => RoleId.GetHashCode(); } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/SlowmodeIgnoredUser.cs b/src/NadekoBot/Db/Models/SlowmodeIgnoredUser.cs index cca19bd76..1485c9b27 100644 --- a/src/NadekoBot/Db/Models/SlowmodeIgnoredUser.cs +++ b/src/NadekoBot/Db/Models/SlowmodeIgnoredUser.cs @@ -17,7 +17,5 @@ public class SlowmodeIgnoredUser : DbEntity // override object.GetHashCode public override int GetHashCode() - { - return UserId.GetHashCode(); - } + => UserId.GetHashCode(); } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/StreamRoleSettings.cs b/src/NadekoBot/Db/Models/StreamRoleSettings.cs index 28a6fc98b..2af01625b 100644 --- a/src/NadekoBot/Db/Models/StreamRoleSettings.cs +++ b/src/NadekoBot/Db/Models/StreamRoleSettings.cs @@ -51,9 +51,7 @@ public class StreamRoleBlacklistedUser : DbEntity } public override int GetHashCode() - { - return UserId.GetHashCode(); - } + => UserId.GetHashCode(); } public class StreamRoleWhitelistedUser : DbEntity @@ -62,14 +60,10 @@ public class StreamRoleWhitelistedUser : DbEntity public string Username { get; set; } public override bool Equals(object obj) - { - return obj is StreamRoleWhitelistedUser x + => obj is StreamRoleWhitelistedUser x ? x.UserId == UserId : false; - } public override int GetHashCode() - { - return UserId.GetHashCode(); - } + => UserId.GetHashCode(); } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/UnbanTimer.cs b/src/NadekoBot/Db/Models/UnbanTimer.cs index 99b171b5c..af2f58118 100644 --- a/src/NadekoBot/Db/Models/UnbanTimer.cs +++ b/src/NadekoBot/Db/Models/UnbanTimer.cs @@ -9,9 +9,7 @@ public class UnbanTimer : DbEntity UserId.GetHashCode(); public override bool Equals(object obj) - { - return obj is UnbanTimer ut + => obj is UnbanTimer ut ? ut.UserId == UserId : false; - } } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/UnmuteTimer.cs b/src/NadekoBot/Db/Models/UnmuteTimer.cs index 29c4dd5f1..d679759e4 100644 --- a/src/NadekoBot/Db/Models/UnmuteTimer.cs +++ b/src/NadekoBot/Db/Models/UnmuteTimer.cs @@ -9,9 +9,7 @@ public class UnmuteTimer : DbEntity UserId.GetHashCode(); public override bool Equals(object obj) - { - return obj is UnmuteTimer ut + => obj is UnmuteTimer ut ? ut.UserId == UserId : false; - } } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/UnroleTimer.cs b/src/NadekoBot/Db/Models/UnroleTimer.cs index 1a16a5c6b..1586cf88b 100644 --- a/src/NadekoBot/Db/Models/UnroleTimer.cs +++ b/src/NadekoBot/Db/Models/UnroleTimer.cs @@ -10,9 +10,7 @@ public class UnroleTimer : DbEntity UserId.GetHashCode() ^ RoleId.GetHashCode(); public override bool Equals(object obj) - { - return obj is UnroleTimer ut + => obj is UnroleTimer ut ? ut.UserId == UserId && ut.RoleId == RoleId : false; - } } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/XpSettings.cs b/src/NadekoBot/Db/Models/XpSettings.cs index 88d28de57..532538125 100644 --- a/src/NadekoBot/Db/Models/XpSettings.cs +++ b/src/NadekoBot/Db/Models/XpSettings.cs @@ -27,14 +27,10 @@ public class XpRoleReward : DbEntity public bool Remove { get; set; } public override int GetHashCode() - { - return Level.GetHashCode() ^ XpSettingsId.GetHashCode(); - } + => Level.GetHashCode() ^ XpSettingsId.GetHashCode(); public override bool Equals(object obj) - { - return obj is XpRoleReward xrr && xrr.Level == Level && xrr.XpSettingsId == XpSettingsId; - } + => obj is XpRoleReward xrr && xrr.Level == Level && xrr.XpSettingsId == XpSettingsId; } public class XpCurrencyReward : DbEntity @@ -46,14 +42,10 @@ public class XpCurrencyReward : DbEntity public int Amount { get; set; } public override int GetHashCode() - { - return Level.GetHashCode() ^ XpSettingsId.GetHashCode(); - } + => Level.GetHashCode() ^ XpSettingsId.GetHashCode(); public override bool Equals(object obj) - { - return obj is XpCurrencyReward xrr && xrr.Level == Level && xrr.XpSettingsId == XpSettingsId; - } + => obj is XpCurrencyReward xrr && xrr.Level == Level && xrr.XpSettingsId == XpSettingsId; } public class ExcludedItem : DbEntity @@ -62,12 +54,8 @@ public class ExcludedItem : DbEntity public ExcludedItemType ItemType { get; set; } public override int GetHashCode() - { - return ItemId.GetHashCode() ^ ItemType.GetHashCode(); - } + => ItemId.GetHashCode() ^ ItemType.GetHashCode(); public override bool Equals(object obj) - { - return obj is ExcludedItem ei && ei.ItemId == ItemId && ei.ItemType == ItemType; - } + => obj is ExcludedItem ei && ei.ItemId == ItemId && ei.ItemType == ItemType; } \ No newline at end of file diff --git a/src/NadekoBot/Db/NadekoContext.cs b/src/NadekoBot/Db/NadekoContext.cs index d2619e9ba..c1c3a0df3 100644 --- a/src/NadekoBot/Db/NadekoContext.cs +++ b/src/NadekoBot/Db/NadekoContext.cs @@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore.Design; using NadekoBot.Services.Database.Models; using Microsoft.Extensions.Logging; using NadekoBot.Db.Models; +// ReSharper disable UnusedAutoPropertyAccessor.Global namespace NadekoBot.Services.Database; @@ -68,9 +69,7 @@ public class NadekoContext : DbContext private static readonly ILoggerFactory _debugLoggerFactory = LoggerFactory.Create(x => x.AddConsole()); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseLoggerFactory(_debugLoggerFactory); - } + => optionsBuilder.UseLoggerFactory(_debugLoggerFactory); #endif protected override void OnModelCreating(ModelBuilder modelBuilder) diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index ab95158c3..db5dc4f81 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -8,10 +8,8 @@ public partial class Administration : NadekoModule private readonly ImageOnlyChannelService _imageOnly; public Administration(ImageOnlyChannelService imageOnly) - { - _imageOnly = imageOnly; - } - + => _imageOnly = imageOnly; + public enum List { List = 0, @@ -292,9 +290,7 @@ public partial class Administration : NadekoModule [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] public async Task Delete(ITextChannel channel, ulong messageId, StoopidTime time = null) - { - await InternalMessageAction(channel, messageId, time, msg => msg.DeleteAsync()); - } + => await InternalMessageAction(channel, messageId, time, msg => msg.DeleteAsync()); private async Task InternalMessageAction(ITextChannel channel, ulong messageId, StoopidTime time, Func func) diff --git a/src/NadekoBot/Modules/Administration/AutoAssignRoleCommands.cs b/src/NadekoBot/Modules/Administration/AutoAssignRoleCommands.cs index 44271638b..d0e55a05a 100644 --- a/src/NadekoBot/Modules/Administration/AutoAssignRoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/AutoAssignRoleCommands.cs @@ -61,7 +61,7 @@ public partial class Administration await ReplyConfirmLocalizedAsync(strs.aar_roles( '\n' + existing.Select(x => Format.Bold(x.ToString())) - .JoinWith(",\n"))); + .Join(",\n"))); } } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Administration/Common/ProtectionStats.cs b/src/NadekoBot/Modules/Administration/Common/ProtectionStats.cs index f7655e063..16838b974 100644 --- a/src/NadekoBot/Modules/Administration/Common/ProtectionStats.cs +++ b/src/NadekoBot/Modules/Administration/Common/ProtectionStats.cs @@ -1,5 +1,4 @@ -using NadekoBot.Common.Collections; -using NadekoBot.Services.Database.Models; +using NadekoBot.Services.Database.Models; namespace NadekoBot.Modules.Administration.Common; @@ -35,10 +34,8 @@ public class AntiAltStats public int Counter => _counter; public AntiAltStats(AntiAltSetting setting) - { - _setting = setting; - } - + => _setting = setting; + public void Increment() => Interlocked.Increment(ref _counter); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Administration/LocalizationCommands.cs b/src/NadekoBot/Modules/Administration/LocalizationCommands.cs index 85de159cc..b7c4d21ba 100644 --- a/src/NadekoBot/Modules/Administration/LocalizationCommands.cs +++ b/src/NadekoBot/Modules/Administration/LocalizationCommands.cs @@ -42,11 +42,9 @@ public partial class Administration [RequireContext(ContextType.Guild)] [Priority(0)] public async Task LanguageSet() - { - await ReplyConfirmLocalizedAsync(strs.lang_set_show( + => await ReplyConfirmLocalizedAsync(strs.lang_set_show( Format.Bold(_cultureInfo.ToString()), Format.Bold(_cultureInfo.NativeName))); - } [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] @@ -113,12 +111,10 @@ public partial class Administration [NadekoCommand, Aliases] public async Task LanguagesList() - { - await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor() + => await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor() .WithTitle(GetText(strs.lang_list)) .WithDescription(string.Join("\n", supportedLocales.Select(x => $"{Format.Code(x.Key),-10} => {x.Value}")))).ConfigureAwait(false); - } } } /* list of language codes for reference. diff --git a/src/NadekoBot/Modules/Administration/PrefixCommands.cs b/src/NadekoBot/Modules/Administration/PrefixCommands.cs index 72def941b..8ed0611c5 100644 --- a/src/NadekoBot/Modules/Administration/PrefixCommands.cs +++ b/src/NadekoBot/Modules/Administration/PrefixCommands.cs @@ -8,9 +8,7 @@ public partial class Administration [NadekoCommand, Aliases] [Priority(1)] public async Task PrefixCommand() - { - await ReplyConfirmLocalizedAsync(strs.prefix_current(Format.Code(CmdHandler.GetPrefix(ctx.Guild)))).ConfigureAwait(false); - } + => await ReplyConfirmLocalizedAsync(strs.prefix_current(Format.Code(CmdHandler.GetPrefix(ctx.Guild)))).ConfigureAwait(false); public enum Set { diff --git a/src/NadekoBot/Modules/Administration/ProtectionCommands.cs b/src/NadekoBot/Modules/Administration/ProtectionCommands.cs index 4ebf8d929..91aaf8cc4 100644 --- a/src/NadekoBot/Modules/Administration/ProtectionCommands.cs +++ b/src/NadekoBot/Modules/Administration/ProtectionCommands.cs @@ -94,13 +94,13 @@ public partial class Administration return; } - if (userThreshold < 2 || userThreshold > 30) + if (userThreshold is < 2 or > 30) { await ReplyErrorLocalizedAsync(strs.raid_cnt(2, 30)); return; } - if (seconds < 2 || seconds > 300) + if (seconds is < 2 or > 300) { await ReplyErrorLocalizedAsync(strs.raid_time(2, 300)); return; @@ -115,7 +115,7 @@ public partial class Administration } var time = (int?) punishTime?.Time.TotalMinutes ?? 0; - if (time < 0 || time > 60 * 24) + if (time is < 0 or > 60 * 24) return; var stats = await _service.StartAntiRaidAsync(ctx.Guild.Id, userThreshold, seconds, @@ -175,7 +175,7 @@ public partial class Administration public async Task InternalAntiSpam(int messageCount, PunishmentAction action, StoopidTime timeData = null, IRole role = null) { - if (messageCount < 2 || messageCount > 10) + if (messageCount is < 2 or > 10) return; if (timeData is not null) @@ -187,7 +187,7 @@ public partial class Administration } var time = (int?) timeData?.Time.TotalMinutes ?? 0; - if (time < 0 || time > 60 * 24) + if (time is < 0 or > 60 * 24) return; var stats = await _service.StartAntiSpamAsync(ctx.Guild.Id, messageCount, action, time, role?.Id).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Administration/PruneCommands.cs b/src/NadekoBot/Modules/Administration/PruneCommands.cs index b9de5d717..b6de14866 100644 --- a/src/NadekoBot/Modules/Administration/PruneCommands.cs +++ b/src/NadekoBot/Modules/Administration/PruneCommands.cs @@ -17,7 +17,7 @@ public partial class Administration { var user = await ctx.Guild.GetCurrentUserAsync().ConfigureAwait(false); - if (parameter == "-s" || parameter == "--safe") + if (parameter is "-s" or "--safe") await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id && !x.IsPinned).ConfigureAwait(false); else await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id).ConfigureAwait(false); @@ -37,7 +37,7 @@ public partial class Administration if (count > 1000) count = 1000; - if (parameter == "-s" || parameter == "--safe") + if (parameter is "-s" or "--safe") await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => !x.IsPinned).ConfigureAwait(false); else await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => true).ConfigureAwait(false); @@ -69,7 +69,7 @@ public partial class Administration if (count > 1000) count = 1000; - if (parameter == "-s" || parameter == "--safe") + if (parameter is "-s" or "--safe") await _service.PruneWhere((ITextChannel)ctx.Channel, count, m => m.Author.Id == userId && DateTime.UtcNow - m.CreatedAt < twoWeeks && !m.IsPinned).ConfigureAwait(false); else await _service.PruneWhere((ITextChannel)ctx.Channel, count, m => m.Author.Id == userId && DateTime.UtcNow - m.CreatedAt < twoWeeks).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Administration/RoleCommands.cs b/src/NadekoBot/Modules/Administration/RoleCommands.cs index cecfd6945..d0dec0669 100644 --- a/src/NadekoBot/Modules/Administration/RoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/RoleCommands.cs @@ -13,9 +13,7 @@ public partial class Administration public enum Exclude { Excl } public RoleCommands(IServiceProvider services) - { - _services = services; - } + => _services = services; public async Task InternalReactionRoles(bool exclusive, ulong? messageId, params string[] input) { @@ -326,9 +324,7 @@ public partial class Administration [RequireContext(ContextType.Guild)] [Priority(1)] public async Task RoleColor([Leftover] IRole role) - { - await SendConfirmAsync("Role Color", role.Color.RawValue.ToString("x6")).ConfigureAwait(false); - } + => await SendConfirmAsync("Role Color", role.Color.RawValue.ToString("x6")).ConfigureAwait(false); [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Administration/SelfCommands.cs b/src/NadekoBot/Modules/Administration/SelfCommands.cs index 925b2b5af..605759edf 100644 --- a/src/NadekoBot/Modules/Administration/SelfCommands.cs +++ b/src/NadekoBot/Modules/Administration/SelfCommands.cs @@ -145,9 +145,7 @@ public partial class Administration } private string GetIntervalText(int interval) - { - return $"[{GetText(strs.interval)}]: {interval}"; - } + => $"[{GetText(strs.interval)}]: {interval}"; [NadekoCommand, Aliases] [OwnerOnly] @@ -298,9 +296,7 @@ public partial class Administration [NadekoCommand, Aliases] [OwnerOnly] public Task Leave([Leftover] string guildStr) - { - return _service.LeaveGuild(guildStr); - } + => _service.LeaveGuild(guildStr); [NadekoCommand, Aliases] @@ -450,7 +446,7 @@ public partial class Administration if (ids[1].ToUpperInvariant().StartsWith("C:", StringComparison.InvariantCulture)) { - var cid = ulong.Parse(ids[1].Substring(2)); + var cid = ulong.Parse(ids[1][2..]); var ch = server.TextChannels.FirstOrDefault(c => c.Id == cid); if (ch is null) return; @@ -460,7 +456,7 @@ public partial class Administration } else if (ids[1].ToUpperInvariant().StartsWith("U:", StringComparison.InvariantCulture)) { - var uid = ulong.Parse(ids[1].Substring(2)); + var uid = ulong.Parse(ids[1][2..]); var user = server.Users.FirstOrDefault(u => u.Id == uid); if (user is null) return; diff --git a/src/NadekoBot/Modules/Administration/ServerGreetCommands.cs b/src/NadekoBot/Modules/Administration/ServerGreetCommands.cs index 9eb7df04f..0877295d3 100644 --- a/src/NadekoBot/Modules/Administration/ServerGreetCommands.cs +++ b/src/NadekoBot/Modules/Administration/ServerGreetCommands.cs @@ -23,7 +23,7 @@ public partial class Administration [UserPerm(GuildPerm.ManageGuild)] public async Task BoostDel(int timer = 30) { - if (timer < 0 || timer > 600) + if (timer is < 0 or > 600) return; await _service.SetBoostDel(ctx.Guild.Id, timer); @@ -66,7 +66,7 @@ public partial class Administration [UserPerm(GuildPerm.ManageGuild)] public async Task GreetDel(int timer = 30) { - if (timer < 0 || timer > 600) + if (timer is < 0 or > 600) return; await _service.SetGreetDel(ctx.Guild.Id, timer).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Administration/Services/AdministrationService.cs b/src/NadekoBot/Modules/Administration/Services/AdministrationService.cs index 78d3a3766..711eab08e 100644 --- a/src/NadekoBot/Modules/Administration/Services/AdministrationService.cs +++ b/src/NadekoBot/Modules/Administration/Services/AdministrationService.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore; -using NadekoBot.Common.Collections; using NadekoBot.Services.Database.Models; using NadekoBot.Db; diff --git a/src/NadekoBot/Modules/Administration/Services/AutoAssignRoleService.cs b/src/NadekoBot/Modules/Administration/Services/AutoAssignRoleService.cs index ded9a4838..bfaa64853 100644 --- a/src/NadekoBot/Modules/Administration/Services/AutoAssignRoleService.cs +++ b/src/NadekoBot/Modules/Administration/Services/AutoAssignRoleService.cs @@ -155,7 +155,5 @@ public static class GuildConfigExtensions } public static void SetAutoAssignableRoles(this GuildConfig gc, IEnumerable roles) - { - gc.AutoAssignRoleIds = roles.JoinWith(','); - } + => gc.AutoAssignRoleIds = roles.Join(','); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Administration/Services/DangerousCommandsService.cs b/src/NadekoBot/Modules/Administration/Services/DangerousCommandsService.cs index e995621d5..6820d8707 100644 --- a/src/NadekoBot/Modules/Administration/Services/DangerousCommandsService.cs +++ b/src/NadekoBot/Modules/Administration/Services/DangerousCommandsService.cs @@ -33,9 +33,7 @@ DELETE FROM Clubs;"; private readonly DbService _db; public DangerousCommandsService(DbService db) - { - _db = db; - } + => _db = db; public async Task ExecuteSql(string sql) { diff --git a/src/NadekoBot/Modules/Administration/Services/GameVoiceChannelService.cs b/src/NadekoBot/Modules/Administration/Services/GameVoiceChannelService.cs index 51a36166e..f0235b703 100644 --- a/src/NadekoBot/Modules/Administration/Services/GameVoiceChannelService.cs +++ b/src/NadekoBot/Modules/Administration/Services/GameVoiceChannelService.cs @@ -1,5 +1,4 @@ -using NadekoBot.Common.Collections; -using NadekoBot.Db; +using NadekoBot.Db; namespace NadekoBot.Modules.Administration.Services; diff --git a/src/NadekoBot/Modules/Administration/Services/ImageOnlyChannelService.cs b/src/NadekoBot/Modules/Administration/Services/ImageOnlyChannelService.cs index f8f4b14ce..40cd75ded 100644 --- a/src/NadekoBot/Modules/Administration/Services/ImageOnlyChannelService.cs +++ b/src/NadekoBot/Modules/Administration/Services/ImageOnlyChannelService.cs @@ -2,7 +2,6 @@ using System.Threading.Channels; using LinqToDB; using Microsoft.Extensions.Caching.Memory; -using NadekoBot.Common.Collections; using NadekoBot.Common.ModuleBehaviors; namespace NadekoBot.Modules.Administration.Services; diff --git a/src/NadekoBot/Modules/Administration/Services/LogCommandService.cs b/src/NadekoBot/Modules/Administration/Services/LogCommandService.cs index 3344fd20f..2c65a10a8 100644 --- a/src/NadekoBot/Modules/Administration/Services/LogCommandService.cs +++ b/src/NadekoBot/Modules/Administration/Services/LogCommandService.cs @@ -1,6 +1,5 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; -using NadekoBot.Common.Collections; using NadekoBot.Services.Database.Models; using NadekoBot.Db; using NadekoBot.Modules.Administration.Common; @@ -23,24 +22,16 @@ public sealed class DummyLogCommandService : ILogCommandService } public Task LogServer(ulong guildId, ulong channelId, bool actionValue) - { - return Task.CompletedTask; - } + => Task.CompletedTask; public bool LogIgnore(ulong guildId, ulong itemId, IgnoredItemType itemType) - { - return false; - } + => false; public LogSetting GetGuildLogSettings(ulong guildId) - { - return default; - } + => default; public bool Log(ulong guildId, ulong? channelId, LogType type) - { - return false; - } + => false; } public sealed class LogCommandService : ILogCommandService @@ -150,9 +141,7 @@ public sealed class LogCommandService : ILogCommandService } public void AddDeleteIgnore(ulong messageId) - { - _ignoreMessageIds.Add(messageId); - } + => _ignoreMessageIds.Add(messageId); public bool LogIgnore(ulong gid, ulong itemId, IgnoredItemType itemType) { @@ -1172,7 +1161,7 @@ public sealed class LogCommandService : ILogCommandService break; } - if (!id.HasValue || id == 0) + if (id is null or 0) { UnsetLogSetting(guild.Id, logChannelType); return null; diff --git a/src/NadekoBot/Modules/Administration/Services/MuteService.cs b/src/NadekoBot/Modules/Administration/Services/MuteService.cs index bde54721c..7b52508e8 100644 --- a/src/NadekoBot/Modules/Administration/Services/MuteService.cs +++ b/src/NadekoBot/Modules/Administration/Services/MuteService.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore; -using NadekoBot.Common.Collections; using NadekoBot.Services.Database.Models; using NadekoBot.Db; diff --git a/src/NadekoBot/Modules/Administration/Services/ProtectionService.cs b/src/NadekoBot/Modules/Administration/Services/ProtectionService.cs index e1dfd898e..f48cb7ef1 100644 --- a/src/NadekoBot/Modules/Administration/Services/ProtectionService.cs +++ b/src/NadekoBot/Modules/Administration/Services/ProtectionService.cs @@ -317,7 +317,11 @@ public class ProtectionService : INService { if (_antiSpamGuilds.TryRemove(guildId, out var removed)) { - removed.UserStats.ForEach(x => x.Value.Dispose()); + foreach (var (_, val) in removed.UserStats) + { + val.Dispose(); + } + using var uow = _db.GetDbContext(); var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting) .ThenInclude(x => x.IgnoredChannels)); diff --git a/src/NadekoBot/Modules/Administration/Services/PruneService.cs b/src/NadekoBot/Modules/Administration/Services/PruneService.cs index b3bdfd3c3..b95840baa 100644 --- a/src/NadekoBot/Modules/Administration/Services/PruneService.cs +++ b/src/NadekoBot/Modules/Administration/Services/PruneService.cs @@ -1,22 +1,19 @@ -using NadekoBot.Common.Collections; - -namespace NadekoBot.Modules.Administration.Services; +namespace NadekoBot.Modules.Administration.Services; public class PruneService : INService { //channelids where prunes are currently occuring private readonly ConcurrentHashSet _pruningGuilds = new(); - private readonly TimeSpan twoWeeks = TimeSpan.FromDays(14); + private readonly TimeSpan _twoWeeks = TimeSpan.FromDays(14); private readonly ILogCommandService _logService; public PruneService(ILogCommandService logService) - { - this._logService = logService; - } + => this._logService = logService; public async Task PruneWhere(ITextChannel channel, int amount, Func predicate) { - channel.ThrowIfNull(nameof(channel)); + ArgumentNullException.ThrowIfNull(channel, nameof(channel)); + if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount)); @@ -38,7 +35,7 @@ public class PruneService : INService { _logService.AddDeleteIgnore(x.Id); - if (DateTime.UtcNow - x.CreatedAt < twoWeeks) + if (DateTime.UtcNow - x.CreatedAt < _twoWeeks) bulkDeletable.Add(x); else singleDeletable.Add(x); diff --git a/src/NadekoBot/Modules/Administration/Services/RoleCommandsService.cs b/src/NadekoBot/Modules/Administration/Services/RoleCommandsService.cs index dae7923a4..cf010cccb 100644 --- a/src/NadekoBot/Modules/Administration/Services/RoleCommandsService.cs +++ b/src/NadekoBot/Modules/Administration/Services/RoleCommandsService.cs @@ -135,9 +135,7 @@ public class RoleCommandsService : INService } public bool Get(ulong id, out IndexedCollection rrs) - { - return _models.TryGetValue(id, out rrs); - } + => _models.TryGetValue(id, out rrs); public bool Add(ulong id, ReactionRoleMessage rrm) { diff --git a/src/NadekoBot/Modules/Administration/Services/SelfAssignedRolesService.cs b/src/NadekoBot/Modules/Administration/Services/SelfAssignedRolesService.cs index 182e45f0f..eb5763690 100644 --- a/src/NadekoBot/Modules/Administration/Services/SelfAssignedRolesService.cs +++ b/src/NadekoBot/Modules/Administration/Services/SelfAssignedRolesService.cs @@ -27,9 +27,7 @@ public class SelfAssignedRolesService : INService } public SelfAssignedRolesService(DbService db) - { - _db = db; - } + => _db = db; public bool AddNew(ulong guildId, IRole role, int group) { diff --git a/src/NadekoBot/Modules/Administration/Services/SelfService.cs b/src/NadekoBot/Modules/Administration/Services/SelfService.cs index 61e81cfb1..8b631c52e 100644 --- a/src/NadekoBot/Modules/Administration/Services/SelfService.cs +++ b/src/NadekoBot/Modules/Administration/Services/SelfService.cs @@ -123,12 +123,10 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService } private Timer TimerFromAutoCommand(AutoCommand x) - { - return new(async obj => await ExecuteCommand((AutoCommand) obj).ConfigureAwait(false), + => new(async obj => await ExecuteCommand((AutoCommand) obj).ConfigureAwait(false), x, x.Interval * 1000, x.Interval * 1000); - } private async Task ExecuteCommand(AutoCommand cmd) { @@ -366,8 +364,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService } private void HandleStatusChanges() - { - _pubSub.Sub(_activitySetKey, async data => + => _pubSub.Sub(_activitySetKey, async data => { try { @@ -378,7 +375,6 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService Log.Warning(ex, "Error setting activity"); } }); - } public Task SetGameAsync(string game, ActivityType type) => _pubSub.Pub(_activitySetKey, new() {Name = game, Link = null, Type = type}); diff --git a/src/NadekoBot/Modules/Administration/Services/UserPunishService.cs b/src/NadekoBot/Modules/Administration/Services/UserPunishService.cs index 5ea9d3eb4..f21096f87 100644 --- a/src/NadekoBot/Modules/Administration/Services/UserPunishService.cs +++ b/src/NadekoBot/Modules/Administration/Services/UserPunishService.cs @@ -300,7 +300,7 @@ WHERE GuildId={guildId} public bool WarnPunish(ulong guildId, int number, PunishmentAction punish, StoopidTime time, IRole role = null) { // these 3 don't make sense with time - if ((punish == PunishmentAction.Softban || punish == PunishmentAction.Kick || punish == PunishmentAction.RemoveRoles) && time != null) + if (punish is PunishmentAction.Softban or PunishmentAction.Kick or PunishmentAction.RemoveRoles && time != null) return false; if (number <= 0 || (time != null && time.Time > TimeSpan.FromDays(49))) return false; @@ -427,8 +427,7 @@ WHERE GuildId={guildId} public SmartText GetBanUserDmEmbed(ICommandContext context, IGuildUser target, string defaultMessage, string banReason, TimeSpan? duration) - { - return GetBanUserDmEmbed( + => GetBanUserDmEmbed( (DiscordSocketClient) context.Client, (SocketGuild) context.Guild, (IGuildUser) context.User, @@ -436,7 +435,6 @@ WHERE GuildId={guildId} defaultMessage, banReason, duration); - } public SmartText GetBanUserDmEmbed(DiscordSocketClient client, SocketGuild guild, IGuildUser moderator, IGuildUser target, string defaultMessage, string banReason, TimeSpan? duration) diff --git a/src/NadekoBot/Modules/Administration/TimeZoneCommands.cs b/src/NadekoBot/Modules/Administration/TimeZoneCommands.cs index 4db67bc4f..418db08bf 100644 --- a/src/NadekoBot/Modules/Administration/TimeZoneCommands.cs +++ b/src/NadekoBot/Modules/Administration/TimeZoneCommands.cs @@ -13,7 +13,7 @@ public partial class Administration { page--; - if (page < 0 || page > 20) + if (page is < 0 or > 20) return; var timezones = TimeZoneInfo.GetSystemTimeZones() @@ -56,9 +56,7 @@ public partial class Administration [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] public async Task Timezone() - { - await ReplyConfirmLocalizedAsync(strs.timezone_guild(_service.GetTimeZoneOrUtc(ctx.Guild.Id))).ConfigureAwait(false); - } + => await ReplyConfirmLocalizedAsync(strs.timezone_guild(_service.GetTimeZoneOrUtc(ctx.Guild.Id))).ConfigureAwait(false); [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Administration/UserPunishCommands.cs b/src/NadekoBot/Modules/Administration/UserPunishCommands.cs index 6d228e71f..4fe7616d8 100644 --- a/src/NadekoBot/Modules/Administration/UserPunishCommands.cs +++ b/src/NadekoBot/Modules/Administration/UserPunishCommands.cs @@ -144,7 +144,7 @@ public partial class Administration [Priority(2)] public async Task WarnExpire(int days, params string[] args) { - if (days < 0 || days > 366) + if (days is < 0 or > 366) return; var opts = OptionsParser.ParseFrom(args); diff --git a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs index 1ed7dea2a..048525af9 100644 --- a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs @@ -95,7 +95,7 @@ public class CustomReactions : NadekoModule + (string.IsNullOrWhiteSpace(cr.Reactions) ? string.Empty : " // " + string.Join(" ", cr.GetReactions()))) - .JoinWith('\n'); + .Join('\n'); return _eb.Create().WithOkColor() .WithTitle(GetText(strs.custom_reactions)) diff --git a/src/NadekoBot/Modules/CustomReactions/Extensions/CustomReactionExtensions.cs b/src/NadekoBot/Modules/CustomReactions/Extensions/CustomReactionExtensions.cs index a05af5177..9cb3fa652 100644 --- a/src/NadekoBot/Modules/CustomReactions/Extensions/CustomReactionExtensions.cs +++ b/src/NadekoBot/Modules/CustomReactions/Extensions/CustomReactionExtensions.cs @@ -33,8 +33,8 @@ public static class CustomReactionExtensions var rep = new ReplacementBuilder() .WithDefault(ctx.Author, ctx.Channel, (ctx.Channel as ITextChannel)?.Guild as SocketGuild, client) .WithOverride("%target%", () => canMentionEveryone - ? ctx.Content.Substring(substringIndex).Trim() - : ctx.Content.Substring(substringIndex).Trim().SanitizeMentions(true)) + ? ctx.Content[substringIndex..].Trim() + : ctx.Content[substringIndex..].Trim().SanitizeMentions(true)) .Build(); var text = SmartText.CreateFrom(cr.Response); @@ -69,11 +69,7 @@ public static class CustomReactionExtensions private static bool isValidWordDivider(this in ReadOnlySpan str, int index) { var ch = str[index]; - if (ch is >= 'a' and <= 'z') - return false; - if (ch is >= 'A' and <= 'Z') - return false; - if (ch is >= '1' and <= '9') + if (ch is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or >= '1' and <= '9') return false; return true; diff --git a/src/NadekoBot/Modules/CustomReactions/Services/CustomReactionsService.cs b/src/NadekoBot/Modules/CustomReactions/Services/CustomReactionsService.cs index 60981066f..d30fbc8cf 100644 --- a/src/NadekoBot/Modules/CustomReactions/Services/CustomReactionsService.cs +++ b/src/NadekoBot/Modules/CustomReactions/Services/CustomReactionsService.cs @@ -713,7 +713,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor { GuildId = guildId, Response = cr.Res, - Reactions = cr.React?.JoinWith("@@@"), + Reactions = cr.React?.Join("@@@"), Trigger = trigger, AllowTarget = cr.At, ContainsAnywhere = cr.Ca, diff --git a/src/NadekoBot/Modules/Gambling/BlackJackCommands.cs b/src/NadekoBot/Modules/Gambling/BlackJackCommands.cs index 94c90c715..9ad802308 100644 --- a/src/NadekoBot/Modules/Gambling/BlackJackCommands.cs +++ b/src/NadekoBot/Modules/Gambling/BlackJackCommands.cs @@ -89,7 +89,7 @@ public partial class Gambling dealerIcon = "🏁 "; } - var cStr = string.Concat(c.Select(x => x.Substring(0, x.Length - 1) + " ")); + var cStr = string.Concat(c.Select(x => x[..^1] + " ")); cStr += "\n" + string.Concat(c.Select(x => x.Last() + " ")); var embed = _eb.Create() .WithOkColor() @@ -104,7 +104,7 @@ public partial class Gambling foreach (var p in bj.Players) { c = p.Cards.Select(x => x.GetEmojiString()); - cStr = "-\t" + string.Concat(c.Select(x => x.Substring(0, x.Length - 1) + " ")); + cStr = "-\t" + string.Concat(c.Select(x => x[..^1] + " ")); cStr += "\n-\t" + string.Concat(c.Select(x => x.Last() + " ")); var full = $"{p.DiscordUser.ToString().TrimTo(20)} | Bet: {p.Bet} | Value: {p.GetHandValue()}"; if (bj.State == Blackjack.GameState.Ended) diff --git a/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/AnimalRacingUser.cs b/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/AnimalRacingUser.cs index e15447ca7..8c4c9c6f1 100644 --- a/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/AnimalRacingUser.cs +++ b/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/AnimalRacingUser.cs @@ -18,14 +18,10 @@ public class AnimalRacingUser } public override bool Equals(object obj) - { - return obj is AnimalRacingUser x + => obj is AnimalRacingUser x ? x.UserId == this.UserId : false; - } public override int GetHashCode() - { - return this.UserId.GetHashCode(); - } + => this.UserId.GetHashCode(); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/RaceOptions.cs b/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/RaceOptions.cs index c5d660b62..ec9aefb6f 100644 --- a/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/RaceOptions.cs +++ b/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/RaceOptions.cs @@ -9,7 +9,7 @@ public class RaceOptions : INadekoCommandOptions public void NormalizeOptions() { - if (this.StartTime < 10 || this.StartTime > 120) + if (this.StartTime is < 10 or > 120) this.StartTime = 20; } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Gambling/Common/Blackjack/Blackjack.cs b/src/NadekoBot/Modules/Gambling/Common/Blackjack/Blackjack.cs index 865940206..bad4ef035 100644 --- a/src/NadekoBot/Modules/Gambling/Common/Blackjack/Blackjack.cs +++ b/src/NadekoBot/Modules/Gambling/Common/Blackjack/Blackjack.cs @@ -203,7 +203,7 @@ public class Blackjack { foreach (var usr in Players) { - if (usr.State == User.UserState.Stand || usr.State == User.UserState.Blackjack) + if (usr.State is User.UserState.Stand or User.UserState.Blackjack) usr.State = User.UserState.Won; else usr.State = User.UserState.Lost; @@ -226,7 +226,7 @@ public class Blackjack foreach (var usr in Players) { - if (usr.State == User.UserState.Won || usr.State == User.UserState.Blackjack) + if (usr.State is User.UserState.Won or User.UserState.Blackjack) { await _cs.AddAsync(usr.DiscordUser.Id, "BlackJack-win", usr.Bet * 2, gamble: true).ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Gambling/Common/Blackjack/Player.cs b/src/NadekoBot/Modules/Gambling/Common/Blackjack/Player.cs index d75bd546d..3ab0e7efc 100644 --- a/src/NadekoBot/Modules/Gambling/Common/Blackjack/Player.cs +++ b/src/NadekoBot/Modules/Gambling/Common/Blackjack/Player.cs @@ -20,9 +20,7 @@ public abstract class Player } public int GetRawHandValue() - { - return Cards.Sum(x => x.Number == 1 ? 11 : x.Number >= 10 ? 10 : x.Number); - } + => Cards.Sum(x => x.Number == 1 ? 11 : x.Number >= 10 ? 10 : x.Number); } public class Dealer : Player diff --git a/src/NadekoBot/Modules/Gambling/Common/CurrencyRaffleGame.cs b/src/NadekoBot/Modules/Gambling/Common/CurrencyRaffleGame.cs index 823c5772c..b1019e919 100644 --- a/src/NadekoBot/Modules/Gambling/Common/CurrencyRaffleGame.cs +++ b/src/NadekoBot/Modules/Gambling/Common/CurrencyRaffleGame.cs @@ -13,16 +13,12 @@ public class CurrencyRaffleGame public long Amount { get; set; } public override int GetHashCode() - { - return DiscordUser.GetHashCode(); - } + => DiscordUser.GetHashCode(); public override bool Equals(object obj) - { - return obj is User u + => obj is User u ? u.DiscordUser == DiscordUser : false; - } } private readonly HashSet _users = new(); @@ -30,9 +26,7 @@ public class CurrencyRaffleGame public Type GameType { get; } public CurrencyRaffleGame(Type type) - { - GameType = type; - } + => GameType = type; public bool AddUser(IUser usr, long amount) { diff --git a/src/NadekoBot/Modules/Gambling/Common/Deck.cs b/src/NadekoBot/Modules/Gambling/Common/Deck.cs index ee31e52b2..72fe5ccfe 100644 --- a/src/NadekoBot/Modules/Gambling/Common/Deck.cs +++ b/src/NadekoBot/Modules/Gambling/Common/Deck.cs @@ -166,13 +166,11 @@ public class Deck /// Creates a new instance of the BlackJackGame, this allows you to create multiple games running at one time. /// public Deck() - { - RefillPool(); - } + => RefillPool(); + static Deck() - { - InitHandValues(); - } + => InitHandValues(); + /// /// Restart the game of blackjack. It will only refill the pool for now. Probably wont be used, unless you want to have only 1 bjg running at one time, /// then you will restart the same game every time. diff --git a/src/NadekoBot/Modules/Gambling/Common/Events/GameStatusEvent.cs b/src/NadekoBot/Modules/Gambling/Common/Events/GameStatusEvent.cs index 473f8c623..7d472251d 100644 --- a/src/NadekoBot/Modules/Gambling/Common/Events/GameStatusEvent.cs +++ b/src/NadekoBot/Modules/Gambling/Common/Events/GameStatusEvent.cs @@ -1,5 +1,4 @@ -using NadekoBot.Common.Collections; -using NadekoBot.Services.Database.Models; +using NadekoBot.Services.Database.Models; namespace NadekoBot.Modules.Gambling.Common.Events; @@ -115,9 +114,7 @@ public class GameStatusEvent : ICurrencyEvent } private IEmbedBuilder GetEmbed(long pot) - { - return _embedFunc(CurrencyEvent.Type.GameStatus, _opts, pot); - } + => _embedFunc(CurrencyEvent.Type.GameStatus, _opts, pot); private async Task OnMessageDeleted(Cacheable msg, Cacheable cacheable) { diff --git a/src/NadekoBot/Modules/Gambling/Common/Events/ReactionEvent.cs b/src/NadekoBot/Modules/Gambling/Common/Events/ReactionEvent.cs index e7ae08bae..a55e0cc05 100644 --- a/src/NadekoBot/Modules/Gambling/Common/Events/ReactionEvent.cs +++ b/src/NadekoBot/Modules/Gambling/Common/Events/ReactionEvent.cs @@ -1,5 +1,4 @@ -using NadekoBot.Common.Collections; -using NadekoBot.Services.Database.Models; +using NadekoBot.Services.Database.Models; namespace NadekoBot.Modules.Gambling.Common.Events; @@ -118,9 +117,7 @@ public class ReactionEvent : ICurrencyEvent } private IEmbedBuilder GetEmbed(long pot) - { - return _embedFunc(CurrencyEvent.Type.Reaction, _opts, pot); - } + => _embedFunc(CurrencyEvent.Type.Reaction, _opts, pot); private async Task OnMessageDeleted(Cacheable msg, Cacheable cacheable) { diff --git a/src/NadekoBot/Modules/Gambling/Common/GamblingConfig.cs b/src/NadekoBot/Modules/Gambling/Common/GamblingConfig.cs index 04de1c666..09baf11c9 100644 --- a/src/NadekoBot/Modules/Gambling/Common/GamblingConfig.cs +++ b/src/NadekoBot/Modules/Gambling/Common/GamblingConfig.cs @@ -105,14 +105,12 @@ Doesn't have to be ordered.")] public BetRollPair[] Pairs { get; set; } = Array.Empty(); public BetRollConfig() - { - Pairs = new BetRollPair[] + => Pairs = new BetRollPair[] { new() { WhenAbove = 99, MultiplyBy = 10 }, new() { WhenAbove = 90, MultiplyBy = 4 }, new() { WhenAbove = 66, MultiplyBy = 2 } }; - } } [Cloneable] @@ -163,8 +161,7 @@ public partial class WheelOfFortuneSettings public decimal[] Multipliers { get; set; } public WheelOfFortuneSettings() - { - Multipliers = new decimal[] + => Multipliers = new decimal[] { 1.7M, 1.5M, @@ -175,7 +172,6 @@ public partial class WheelOfFortuneSettings 1.2M, 2.4M, }; - } } [Cloneable] @@ -191,8 +187,7 @@ If negative is true, gift will instead reduce waifu value.")] public List Items { get; set; } = new(); public WaifuConfig() - { - Items = new() + => Items = new() { new("🥔", 5, "Potato"), new("🍪", 10, "Cookie"), @@ -231,7 +226,6 @@ If negative is true, gift will instead reduce waifu value.")] new("🚀", 30000, "Spaceship"), new("🌕", 50000, "Moon") }; - } } [Cloneable] diff --git a/src/NadekoBot/Modules/Gambling/Common/GamblingTopLevelModule.cs b/src/NadekoBot/Modules/Gambling/Common/GamblingTopLevelModule.cs index 73e268085..e58f07838 100644 --- a/src/NadekoBot/Modules/Gambling/Common/GamblingTopLevelModule.cs +++ b/src/NadekoBot/Modules/Gambling/Common/GamblingTopLevelModule.cs @@ -10,9 +10,7 @@ public abstract class GamblingModule : NadekoModule protected string CurrencyName => _config.Currency.Name; protected GamblingModule(GamblingConfigService gambService) - { - _lazyConfig = new(() => gambService.Data); - } + => _lazyConfig = new(() => gambService.Data); private async Task InternalCheckBet(long amount) { diff --git a/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs b/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs index 104c781cc..36952704d 100644 --- a/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs +++ b/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs @@ -151,14 +151,14 @@ public sealed class Connect4Game : IDisposable try { inputCol -= 1; - if (CurrentPhase == Phase.Ended || CurrentPhase == Phase.Joining) + if (CurrentPhase is Phase.Ended or Phase.Joining) return false; if (!((_players[0].Value.UserId == userId && CurrentPhase == Phase.P1Move) || (_players[1].Value.UserId == userId && CurrentPhase == Phase.P2Move))) return false; - if (inputCol < 0 || inputCol > NumberOfColumns) //invalid input + if (inputCol is < 0 or > NumberOfColumns) //invalid input return false; if (IsColumnFull(inputCol)) //can't play there event? @@ -259,9 +259,9 @@ public sealed class Connect4Game : IDisposable var curCol = col - i; //check if current values are in range - if (curRow >= NumberOfRows || curRow < 0) + if (curRow is >= NumberOfRows or < 0) break; - if (curCol < 0 || curCol >= NumberOfColumns) + if (curCol is < 0 or >= NumberOfColumns) break; var cur = _gameState[curRow + (curCol * NumberOfRows)]; @@ -286,9 +286,9 @@ public sealed class Connect4Game : IDisposable var curCol = col + i; //check if current values are in range - if (curRow >= NumberOfRows || curRow < 0) + if (curRow is >= NumberOfRows or < 0) break; - if (curCol < 0 || curCol >= NumberOfColumns) + if (curCol is < 0 or >= NumberOfColumns) break; var cur = _gameState[curRow + (curCol * NumberOfRows)]; @@ -328,9 +328,7 @@ public sealed class Connect4Game : IDisposable } private void ResetTimer() - { - _playerTimeoutTimer.Change(TimeSpan.FromSeconds(_options.TurnTimer), TimeSpan.FromSeconds(_options.TurnTimer)); - } + => _playerTimeoutTimer.Change(TimeSpan.FromSeconds(_options.TurnTimer), TimeSpan.FromSeconds(_options.TurnTimer)); private void EndGame(Result result, ulong? winId) { @@ -378,7 +376,7 @@ public sealed class Connect4Game : IDisposable { public void NormalizeOptions() { - if (TurnTimer < 5 || TurnTimer > 60) + if (TurnTimer is < 5 or > 60) TurnTimer = 15; if (Bet < 0) diff --git a/src/NadekoBot/Modules/Gambling/Connect4Commands.cs b/src/NadekoBot/Modules/Gambling/Connect4Commands.cs index 515e7df4a..dcc84995a 100644 --- a/src/NadekoBot/Modules/Gambling/Connect4Commands.cs +++ b/src/NadekoBot/Modules/Gambling/Connect4Commands.cs @@ -86,8 +86,7 @@ public partial class Gambling try { await arg.DeleteAsync().ConfigureAwait(false); } catch { } else { - if (game.CurrentPhase == Connect4Game.Phase.Joining - || game.CurrentPhase == Connect4Game.Phase.Ended) + if (game.CurrentPhase is Connect4Game.Phase.Joining or Connect4Game.Phase.Ended) { return; } @@ -145,7 +144,7 @@ public partial class Gambling get => _repostCounter; set { - if (value < 0 || value > 7) + if (value is < 0 or > 7) _repostCounter = 0; else _repostCounter = value; } @@ -169,8 +168,7 @@ public partial class Gambling { var sb = new StringBuilder(); - if (game.CurrentPhase == Connect4Game.Phase.P1Move || - game.CurrentPhase == Connect4Game.Phase.P2Move) + if (game.CurrentPhase is Connect4Game.Phase.P1Move or Connect4Game.Phase.P2Move) sb.AppendLine(GetText(strs.connect4_player_to_move(Format.Bold(game.CurrentPlayer.Username)))); for (var i = Connect4Game.NumberOfRows; i > 0; i--) diff --git a/src/NadekoBot/Modules/Gambling/CurrencyEventsCommands.cs b/src/NadekoBot/Modules/Gambling/CurrencyEventsCommands.cs index 7bbfb519d..eaeb58c4c 100644 --- a/src/NadekoBot/Modules/Gambling/CurrencyEventsCommands.cs +++ b/src/NadekoBot/Modules/Gambling/CurrencyEventsCommands.cs @@ -32,8 +32,7 @@ public partial class Gambling } private IEmbedBuilder GetEmbed(CurrencyEvent.Type type, EventOptions opts, long currentPot) - { - return type switch + => type switch { CurrencyEvent.Type.Reaction => _eb.Create() .WithOkColor() @@ -47,7 +46,6 @@ public partial class Gambling .WithFooter(GetText(strs.event_duration_footer(opts.Hours))), _ => throw new ArgumentOutOfRangeException(nameof(type)) }; - } private string GetReactionDescription(long amount, long potSize) { diff --git a/src/NadekoBot/Modules/Gambling/DiceRollCommands.cs b/src/NadekoBot/Modules/Gambling/DiceRollCommands.cs index b36b9b642..27500dc8c 100644 --- a/src/NadekoBot/Modules/Gambling/DiceRollCommands.cs +++ b/src/NadekoBot/Modules/Gambling/DiceRollCommands.cs @@ -17,9 +17,7 @@ public partial class Gambling private readonly IImageCache _images; public DiceRollCommands(IDataCache data) - { - _images = data.LocalImages; - } + => _images = data.LocalImages; [NadekoCommand, Aliases] public async Task Roll() @@ -42,35 +40,27 @@ public partial class Gambling [NadekoCommand, Aliases] [Priority(1)] public async Task Roll(int num) - { - await InternalRoll(num, true).ConfigureAwait(false); - } + => await InternalRoll(num, true).ConfigureAwait(false); [NadekoCommand, Aliases] [Priority(1)] public async Task Rolluo(int num = 1) - { - await InternalRoll(num, false).ConfigureAwait(false); - } + => await InternalRoll(num, false).ConfigureAwait(false); [NadekoCommand, Aliases] [Priority(0)] public async Task Roll(string arg) - { - await InternallDndRoll(arg, true).ConfigureAwait(false); - } + => await InternallDndRoll(arg, true).ConfigureAwait(false); [NadekoCommand, Aliases] [Priority(0)] public async Task Rolluo(string arg) - { - await InternallDndRoll(arg, false).ConfigureAwait(false); - } + => await InternallDndRoll(arg, false).ConfigureAwait(false); private async Task InternalRoll(int num, bool ordered) { - if (num < 1 || num > 30) + if (num is < 1 or > 30) { await ReplyErrorLocalizedAsync(strs.dice_invalid_number(1, 30)); return; @@ -201,7 +191,7 @@ public partial class Gambling private Image GetDice(int num) { - if (num < 0 || num > 10) + if (num is < 0 or > 10) throw new ArgumentOutOfRangeException(nameof(num)); if (num == 10) diff --git a/src/NadekoBot/Modules/Gambling/DrawCommands.cs b/src/NadekoBot/Modules/Gambling/DrawCommands.cs index 51b995ab8..f6327fae3 100644 --- a/src/NadekoBot/Modules/Gambling/DrawCommands.cs +++ b/src/NadekoBot/Modules/Gambling/DrawCommands.cs @@ -14,13 +14,11 @@ public partial class Gambling private readonly IImageCache _images; public DrawCommands(IDataCache data) - { - _images = data.LocalImages; - } + => _images = data.LocalImages; private async Task<(Stream ImageStream, string ToSend)> InternalDraw(int num, ulong? guildId = null) { - if (num < 1 || num > 10) + if (num is < 1 or > 10) throw new ArgumentOutOfRangeException(nameof(num)); var cards = guildId is null ? new() : _allDecks.GetOrAdd(ctx.Guild, s => new()); diff --git a/src/NadekoBot/Modules/Gambling/FlipCoinCommands.cs b/src/NadekoBot/Modules/Gambling/FlipCoinCommands.cs index 191cbb701..55cde6689 100644 --- a/src/NadekoBot/Modules/Gambling/FlipCoinCommands.cs +++ b/src/NadekoBot/Modules/Gambling/FlipCoinCommands.cs @@ -24,7 +24,7 @@ public partial class Gambling [NadekoCommand, Aliases] public async Task Flip(int count = 1) { - if (count > 10 || count < 1) + if (count is > 10 or < 1) { await ReplyErrorLocalizedAsync(strs.flip_invalid(10)); return; diff --git a/src/NadekoBot/Modules/Gambling/Gambling.cs b/src/NadekoBot/Modules/Gambling/Gambling.cs index 1805be940..c1c0ff410 100644 --- a/src/NadekoBot/Modules/Gambling/Gambling.cs +++ b/src/NadekoBot/Modules/Gambling/Gambling.cs @@ -201,9 +201,7 @@ public partial class Gambling : GamblingModule [NadekoCommand, Aliases] [Priority(0)] public async Task Cash(ulong userId) - { - await ReplyConfirmLocalizedAsync(strs.has(Format.Code(userId.ToString()), $"{GetCurrency(userId)}")); - } + => await ReplyConfirmLocalizedAsync(strs.has(Format.Code(userId.ToString()), $"{GetCurrency(userId)}")); [NadekoCommand, Aliases] [Priority(1)] diff --git a/src/NadekoBot/Modules/Gambling/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Gambling/PlantAndPickCommands.cs index 7b108c527..dc8c33ddd 100644 --- a/src/NadekoBot/Modules/Gambling/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Gambling/PlantAndPickCommands.cs @@ -12,9 +12,7 @@ public partial class Gambling private readonly ILogCommandService logService; public PlantPickCommands(ILogCommandService logService, GamblingConfigService gss) : base(gss) - { - this.logService = logService; - } + => this.logService = logService; [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Gambling/Services/GamblingService.cs b/src/NadekoBot/Modules/Gambling/Services/GamblingService.cs index e4145ec07..88bb27658 100644 --- a/src/NadekoBot/Modules/Gambling/Services/GamblingService.cs +++ b/src/NadekoBot/Modules/Gambling/Services/GamblingService.cs @@ -38,7 +38,7 @@ public class GamblingService : INService { var config = _gss.Data; var maxDecay = config.Decay.MaxDecay; - if (config.Decay.Percent <= 0 || config.Decay.Percent > 1 || maxDecay < 0) + if (config.Decay.Percent is <= 0 or > 1 || maxDecay < 0) return; using var uow = _db.GetDbContext(); @@ -156,7 +156,5 @@ WHERE CurrencyAmount > {config.Decay.MinThreshold} AND UserId!={_client.CurrentU } public Task WheelOfFortuneSpinAsync(ulong userId, long bet) - { - return new WheelOfFortuneGame(userId, bet, _gss.Data, _cs).SpinAsync(); - } + => new WheelOfFortuneGame(userId, bet, _gss.Data, _cs).SpinAsync(); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Gambling/Services/Impl/ShopService.cs b/src/NadekoBot/Modules/Gambling/Services/Impl/ShopService.cs index f068323ee..076150aa9 100644 --- a/src/NadekoBot/Modules/Gambling/Services/Impl/ShopService.cs +++ b/src/NadekoBot/Modules/Gambling/Services/Impl/ShopService.cs @@ -11,9 +11,7 @@ public class ShopService : IShopService, INService private readonly DbService _db; public ShopService(DbService db) - { - _db = db; - } + => _db = db; private IndexedCollection GetEntriesInternal(NadekoContext uow, ulong guildId) => uow.GuildConfigsForId( diff --git a/src/NadekoBot/Modules/Gambling/Services/PlantPickService.cs b/src/NadekoBot/Modules/Gambling/Services/PlantPickService.cs index 4932548d3..9afb2f49e 100644 --- a/src/NadekoBot/Modules/Gambling/Services/PlantPickService.cs +++ b/src/NadekoBot/Modules/Gambling/Services/PlantPickService.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore; -using NadekoBot.Common.Collections; using NadekoBot.Services.Database.Models; using SixLabors.Fonts; using SixLabors.ImageSharp; diff --git a/src/NadekoBot/Modules/Gambling/TestGamblingService.cs b/src/NadekoBot/Modules/Gambling/TestGamblingService.cs index 7e76aeb4f..f2d078fa3 100644 --- a/src/NadekoBot/Modules/Gambling/TestGamblingService.cs +++ b/src/NadekoBot/Modules/Gambling/TestGamblingService.cs @@ -6,7 +6,5 @@ public class TestGamblingService : InteractionModuleBase { [SlashCommand("test", "uwu")] public async Task Test(string input1, int input2) - { - await RespondAsync("Bravo " + input1 + input2); - } + => await RespondAsync("Bravo " + input1 + input2); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Gambling/WaifuClaimCommands.cs b/src/NadekoBot/Modules/Gambling/WaifuClaimCommands.cs index a1e961fea..0e4939b8d 100644 --- a/src/NadekoBot/Modules/Gambling/WaifuClaimCommands.cs +++ b/src/NadekoBot/Modules/Gambling/WaifuClaimCommands.cs @@ -257,20 +257,21 @@ public partial class Gambling var nobody = GetText(strs.nobody); var itemsStr = !wi.Items.Any() ? "-" - : string.Join("\n", wi.Items - .Where(x => waifuItems.TryGetValue(x.ItemEmoji, out _)) - .OrderBy(x => waifuItems[x.ItemEmoji].Price) - .GroupBy(x => x.ItemEmoji) - .Select(x => $"{x.Key} x{x.Count(),-3}") - .Chunk(2) - .Select(x => string.Join(" ", x))); + : string.Join("\n", + wi.Items.Where(x => waifuItems.TryGetValue(x.ItemEmoji, out _)) + .OrderBy(x => waifuItems[x.ItemEmoji].Price) + .GroupBy(x => x.ItemEmoji) + .Select(x => $"{x.Key} x{x.Count(),-3}") + .Chunk(2) + .Select(x => string.Join(" ", x)) + ); var fansStr = wi .Fans .Shuffle() .Take(30) .Select(x => wi.Claims.Contains(x) ? $"{x} 💞" : x) - .JoinWith('\n'); + .Join('\n'); if (string.IsNullOrWhiteSpace(fansStr)) fansStr = "-"; @@ -309,15 +310,16 @@ public partial class Gambling .WithTitle(GetText(strs.waifu_gift_shop)) .WithOkColor(); - waifuItems - .OrderBy(x => x.Negative) + waifuItems.OrderBy(x => x.Negative) .ThenBy(x => x.Price) .Skip(9 * cur) .Take(9) - .ForEach(x => embed - .AddField($"{(!x.Negative ? string.Empty : "\\💔")} {x.ItemEmoji} {x.Name}", + .ToList() + .ForEach(x => embed.AddField($"{(!x.Negative ? string.Empty : "\\💔")} {x.ItemEmoji} {x.Name}", Format.Bold(x.Price.ToString()) + _config.Currency.Sign, - true)); + true + ) + ); return embed; }, waifuItems.Count, 9); diff --git a/src/NadekoBot/Modules/Games/AcropobiaCommands.cs b/src/NadekoBot/Modules/Games/AcropobiaCommands.cs index 42c085a81..b2326da61 100644 --- a/src/NadekoBot/Modules/Games/AcropobiaCommands.cs +++ b/src/NadekoBot/Modules/Games/AcropobiaCommands.cs @@ -12,9 +12,7 @@ public partial class Games private readonly DiscordSocketClient _client; public AcropobiaCommands(DiscordSocketClient client) - { - _client = client; - } + => _client = client; [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] @@ -80,11 +78,9 @@ public partial class Games } private Task Game_OnUserVoted(string user) - { - return SendConfirmAsync( + => SendConfirmAsync( GetText(strs.acrophobia), GetText(strs.acro_vote_cast(Format.Bold(user)))); - } private async Task Game_OnVotingStarted(AcrophobiaGame game, ImmutableArray> submissions) { diff --git a/src/NadekoBot/Modules/Games/CleverBotCommands.cs b/src/NadekoBot/Modules/Games/CleverBotCommands.cs index 6d4db9627..69507e49c 100644 --- a/src/NadekoBot/Modules/Games/CleverBotCommands.cs +++ b/src/NadekoBot/Modules/Games/CleverBotCommands.cs @@ -11,9 +11,7 @@ public partial class Games private readonly DbService _db; public ChatterBotCommands(DbService db) - { - _db = db; - } + => _db = db; [NoPublicBot] [NadekoCommand, Aliases] diff --git a/src/NadekoBot/Modules/Games/Common/Acrophobia/Acrophobia.cs b/src/NadekoBot/Modules/Games/Common/Acrophobia/Acrophobia.cs index 32b2f2538..0ce426e7f 100644 --- a/src/NadekoBot/Modules/Games/Common/Acrophobia/Acrophobia.cs +++ b/src/NadekoBot/Modules/Games/Common/Acrophobia/Acrophobia.cs @@ -15,9 +15,9 @@ public sealed class AcrophobiaGame : IDisposable public void NormalizeOptions() { - if (SubmissionTime < 15 || SubmissionTime > 300) + if (SubmissionTime is < 15 or > 300) SubmissionTime = 60; - if (VoteTime < 15 || VoteTime > 120) + if (VoteTime is < 15 or > 120) VoteTime = 30; } } diff --git a/src/NadekoBot/Modules/Games/Common/Acrophobia/AcrophobiaUser.cs b/src/NadekoBot/Modules/Games/Common/Acrophobia/AcrophobiaUser.cs index a50613d6d..21defce28 100644 --- a/src/NadekoBot/Modules/Games/Common/Acrophobia/AcrophobiaUser.cs +++ b/src/NadekoBot/Modules/Games/Common/Acrophobia/AcrophobiaUser.cs @@ -14,14 +14,10 @@ public class AcrophobiaUser } public override int GetHashCode() - { - return UserId.GetHashCode(); - } + => UserId.GetHashCode(); public override bool Equals(object obj) - { - return obj is AcrophobiaUser x + => obj is AcrophobiaUser x ? x.UserId == this.UserId : false; - } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Games/Common/Hangman/HangmanService.cs b/src/NadekoBot/Modules/Games/Common/Hangman/HangmanService.cs index 3cc5e9e3d..ae006fdd3 100644 --- a/src/NadekoBot/Modules/Games/Common/Hangman/HangmanService.cs +++ b/src/NadekoBot/Modules/Games/Common/Hangman/HangmanService.cs @@ -88,8 +88,7 @@ public sealed class HangmanService : IHangmanService, ILateExecutor if (state.GuessResult == HangmanGame.GuessResult.NoAction) return; - if (state.GuessResult == HangmanGame.GuessResult.Incorrect - || state.GuessResult == HangmanGame.GuessResult.AlreadyTried) + if (state.GuessResult is HangmanGame.GuessResult.Incorrect or HangmanGame.GuessResult.AlreadyTried) { _cdCache.Set(msg.Author.Id, string.Empty, new MemoryCacheEntryOptions() { diff --git a/src/NadekoBot/Modules/Games/Common/Nunchi/Nunchi.cs b/src/NadekoBot/Modules/Games/Common/Nunchi/Nunchi.cs index 1640198dd..685bc39db 100644 --- a/src/NadekoBot/Modules/Games/Common/Nunchi/Nunchi.cs +++ b/src/NadekoBot/Modules/Games/Common/Nunchi/Nunchi.cs @@ -34,9 +34,7 @@ public sealed class NunchiGame : IDisposable private Timer _killTimer; public NunchiGame(ulong creatorId, string creatorName) - { - _participants.Add((creatorId, creatorName)); - } + => _participants.Add((creatorId, creatorName)); public async Task Join(ulong userId, string userName) { diff --git a/src/NadekoBot/Modules/Games/Common/PollRunner.cs b/src/NadekoBot/Modules/Games/Common/PollRunner.cs index 544341375..d2c177078 100644 --- a/src/NadekoBot/Modules/Games/Common/PollRunner.cs +++ b/src/NadekoBot/Modules/Games/Common/PollRunner.cs @@ -59,7 +59,5 @@ public class PollRunner } public void End() - { - OnVoted = null; - } + => OnVoted = null; } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Games/Common/TicTacToe.cs b/src/NadekoBot/Modules/Games/Common/TicTacToe.cs index 6b6f4f73a..3fa41c788 100644 --- a/src/NadekoBot/Modules/Games/Common/TicTacToe.cs +++ b/src/NadekoBot/Modules/Games/Common/TicTacToe.cs @@ -9,7 +9,7 @@ public class TicTacToe { public void NormalizeOptions() { - if (TurnTimer < 5 || TurnTimer > 60) + if (TurnTimer is < 5 or > 60) TurnTimer = 15; } @@ -127,7 +127,7 @@ public class TicTacToe public async Task Start(IGuildUser user) { - if (_phase == Phase.Started || _phase == Phase.Ended) + if (_phase is Phase.Started or Phase.Ended) { await _channel.SendErrorAsync(_eb, user.Mention + GetText(strs.ttt_already_running)).ConfigureAwait(false); return; diff --git a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaGame.cs b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaGame.cs index abffc9671..0f783e0dc 100644 --- a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaGame.cs +++ b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaGame.cs @@ -86,9 +86,7 @@ public class TriviaGame questionMessage = await Channel.EmbedAsync(questionEmbed).ConfigureAwait(false); } - catch (HttpException ex) when (ex.HttpCode == System.Net.HttpStatusCode.NotFound || - ex.HttpCode == System.Net.HttpStatusCode.Forbidden || - ex.HttpCode == System.Net.HttpStatusCode.BadRequest) + catch (HttpException ex) when (ex.HttpCode is System.Net.HttpStatusCode.NotFound or System.Net.HttpStatusCode.Forbidden or System.Net.HttpStatusCode.BadRequest) { return; } @@ -116,7 +114,7 @@ public class TriviaGame await questionMessage.ModifyAsync(m => m.Embed = questionEmbed.WithFooter(CurrentQuestion.GetHint()).Build()) .ConfigureAwait(false); } - catch (HttpException ex) when (ex.HttpCode == System.Net.HttpStatusCode.NotFound || ex.HttpCode == System.Net.HttpStatusCode.Forbidden) + catch (HttpException ex) when (ex.HttpCode is System.Net.HttpStatusCode.NotFound or System.Net.HttpStatusCode.Forbidden) { break; } diff --git a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaOptions.cs b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaOptions.cs index 3f6faf785..2a1e6ebc9 100644 --- a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaOptions.cs +++ b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaOptions.cs @@ -19,9 +19,9 @@ public class TriviaOptions : INadekoCommandOptions { if (WinRequirement < 0) WinRequirement = 10; - if (QuestionTimer < 10 || QuestionTimer > 300) + if (QuestionTimer is < 10 or > 300) QuestionTimer = 30; - if (Timeout < 0 || Timeout > 20) + if (Timeout is < 0 or > 20) Timeout = 10; } diff --git a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestion.cs b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestion.cs index fb4554be9..247d058a8 100644 --- a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestion.cs +++ b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestion.cs @@ -78,7 +78,7 @@ public class TriviaQuestion str = Regex.Replace(str, "^\\s+", ""); str = Regex.Replace(str, "\\s+$", ""); //Trim the really long answers - str = str.Length <= maxStringLength ? str : str.Substring(0, maxStringLength); + str = str.Length <= maxStringLength ? str : str[..maxStringLength]; return str; } diff --git a/src/NadekoBot/Modules/Games/Common/TypingGame.cs b/src/NadekoBot/Modules/Games/Common/TypingGame.cs index 33f06e67a..37fa5dde3 100644 --- a/src/NadekoBot/Modules/Games/Common/TypingGame.cs +++ b/src/NadekoBot/Modules/Games/Common/TypingGame.cs @@ -13,7 +13,7 @@ public class TypingGame public void NormalizeOptions() { - if (StartTime < 3 || StartTime > 30) + if (StartTime is < 3 or > 30) StartTime = 5; } } @@ -123,9 +123,7 @@ public class TypingGame } private void HandleAnswers() - { - _client.MessageReceived += AnswerReceived; - } + => _client.MessageReceived += AnswerReceived; private Task AnswerReceived(SocketMessage imsg) { diff --git a/src/NadekoBot/Modules/Games/Games.cs b/src/NadekoBot/Modules/Games/Games.cs index 9c6fcaacc..28c323959 100644 --- a/src/NadekoBot/Modules/Games/Games.cs +++ b/src/NadekoBot/Modules/Games/Games.cs @@ -76,9 +76,7 @@ public partial class Games : NadekoModule } private double NextDouble(double x, double y) - { - return (_rng.NextDouble() * (y - x)) + x; - } + => (_rng.NextDouble() * (y - x)) + x; private GirlRating GetGirl(ulong uid) { @@ -139,13 +137,11 @@ public partial class Games : NadekoModule [NadekoCommand, Aliases] public async Task Linux(string guhnoo, string loonix) - { - await SendConfirmAsync( + => await SendConfirmAsync( $@"I'd just like to interject for moment. What you're refering to as {loonix}, is in fact, {guhnoo}/{loonix}, or as I've recently taken to calling it, {guhnoo} plus {loonix}. {loonix} is not an operating system unto itself, but rather another free component of a fully functioning {guhnoo} system made useful by the {guhnoo} corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. Many computer users run a modified version of the {guhnoo} system every day, without realizing it. Through a peculiar turn of events, the version of {guhnoo} which is widely used today is often called {loonix}, and many of its users are not aware that it is basically the {guhnoo} system, developed by the {guhnoo} Project. There really is a {loonix}, and these people are using it, but it is just a part of the system they use. {loonix} is the kernel: the program in the system that allocates the machine's resources to the other programs that you run. The kernel is an essential part of an operating system, but useless by itself; it can only function in the context of a complete operating system. {loonix} is normally used in combination with the {guhnoo} operating system: the whole system is basically {guhnoo} with {loonix} added, or {guhnoo}/{loonix}. All the so-called {loonix} distributions are really distributions of {guhnoo}/{loonix}." ).ConfigureAwait(false); - } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Games/HangmanCommands.cs b/src/NadekoBot/Modules/Games/HangmanCommands.cs index bd44f3789..1d68c7fd9 100644 --- a/src/NadekoBot/Modules/Games/HangmanCommands.cs +++ b/src/NadekoBot/Modules/Games/HangmanCommands.cs @@ -11,22 +11,18 @@ public partial class Games [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] public async Task Hangmanlist() - { - await SendConfirmAsync( + => await SendConfirmAsync( GetText(strs.hangman_types(Prefix)), - _service.GetHangmanTypes().JoinWith('\n')); - } + _service.GetHangmanTypes().Join('\n')); private static string Draw(HangmanGame.State state) - { - return $@". ┌─────┐ + => $@". ┌─────┐ .┃...............┋ .┃...............┋ .┃{(state.Errors > 0 ? ".............😲" : "")} .┃{(state.Errors > 1 ? "............./" : "")} {(state.Errors > 2 ? "|" : "")} {(state.Errors > 3 ? "\\" : "")} .┃{(state.Errors > 4 ? "............../" : "")} {(state.Errors > 5 ? "\\" : "")} /-\"; - } public static IEmbedBuilder GetEmbed(IEmbedBuilderService eb, HangmanGame.State state) { @@ -35,21 +31,21 @@ public partial class Games .WithOkColor() .AddField("Hangman", Draw(state)) .AddField("Guess", Format.Code(state.Word)) - .WithFooter(state.missedLetters.JoinWith(' ')); + .WithFooter(state.missedLetters.Join(' ')); if (state.Phase == HangmanGame.Phase.Ended && state.Failed) return eb.Create() .WithErrorColor() .AddField("Hangman", Draw(state)) .AddField("Guess", Format.Code(state.Word)) - .WithFooter(state.missedLetters.JoinWith(' ')); + .WithFooter(state.missedLetters.Join(' ')); else { return eb.Create() .WithOkColor() .AddField("Hangman", Draw(state)) .AddField("Guess", Format.Code(state.Word)) - .WithFooter(state.missedLetters.JoinWith(' ')); + .WithFooter(state.missedLetters.Join(' ')); } } diff --git a/src/NadekoBot/Modules/Games/NunchiCommands.cs b/src/NadekoBot/Modules/Games/NunchiCommands.cs index 596a6b138..d2916859c 100644 --- a/src/NadekoBot/Modules/Games/NunchiCommands.cs +++ b/src/NadekoBot/Modules/Games/NunchiCommands.cs @@ -11,9 +11,7 @@ public partial class Games private readonly DiscordSocketClient _client; public NunchiCommands(DiscordSocketClient client) - { - _client = client; - } + => _client = client; [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] @@ -91,16 +89,12 @@ public partial class Games } private Task Nunchi_OnRoundStarted(NunchiGame arg, int cur) - { - return ConfirmLocalizedAsync(strs.nunchi_round_started( + => ConfirmLocalizedAsync(strs.nunchi_round_started( Format.Bold(arg.ParticipantCount.ToString()), Format.Bold(cur.ToString()))); - } private Task Nunchi_OnUserGuessed(NunchiGame arg) - { - return ConfirmLocalizedAsync(strs.nunchi_next_number(Format.Bold(arg.CurrentNumber.ToString()))); - } + => ConfirmLocalizedAsync(strs.nunchi_next_number(Format.Bold(arg.CurrentNumber.ToString()))); private Task Nunchi_OnRoundEnded(NunchiGame arg1, (ulong Id, string Name)? arg2) { @@ -112,8 +106,6 @@ public partial class Games } private Task Nunchi_OnGameStarted(NunchiGame arg) - { - return ConfirmLocalizedAsync(strs.nunchi_started(Format.Bold(arg.ParticipantCount.ToString()))); - } + => ConfirmLocalizedAsync(strs.nunchi_started(Format.Bold(arg.ParticipantCount.ToString()))); } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Games/PollCommands.cs b/src/NadekoBot/Modules/Games/PollCommands.cs index 8fffb5528..33945317e 100644 --- a/src/NadekoBot/Modules/Games/PollCommands.cs +++ b/src/NadekoBot/Modules/Games/PollCommands.cs @@ -12,9 +12,7 @@ public partial class Games private readonly DiscordSocketClient _client; public PollCommands(DiscordSocketClient client) - { - _client = client; - } + => _client = client; [NadekoCommand, Aliases] [UserPerm(GuildPerm.ManageMessages)] diff --git a/src/NadekoBot/Modules/Games/Services/ChatterbotService.cs b/src/NadekoBot/Modules/Games/Services/ChatterbotService.cs index 18633a869..300be0eab 100644 --- a/src/NadekoBot/Modules/Games/Services/ChatterbotService.cs +++ b/src/NadekoBot/Modules/Games/Services/ChatterbotService.cs @@ -64,11 +64,11 @@ public class ChatterBotService : IEarlyBehavior string message; if (msg.Content.StartsWith(normalMention, StringComparison.InvariantCulture)) { - message = msg.Content.Substring(normalMention.Length).Trim(); + message = msg.Content[normalMention.Length..].Trim(); } else if (msg.Content.StartsWith(nickMention, StringComparison.InvariantCulture)) { - message = msg.Content.Substring(nickMention.Length).Trim(); + message = msg.Content[nickMention.Length..].Trim(); } else { diff --git a/src/NadekoBot/Modules/Games/Services/GamesService.cs b/src/NadekoBot/Modules/Games/Services/GamesService.cs index 6893a4b3e..9269b0e30 100644 --- a/src/NadekoBot/Modules/Games/Services/GamesService.cs +++ b/src/NadekoBot/Modules/Games/Services/GamesService.cs @@ -94,14 +94,12 @@ public class GamesService : INService } public string GetEightballResponse(ulong userId, string question) - { - return _8BallCache.GetOrCreate($"8ball:{userId}:{question}", e => + => _8BallCache.GetOrCreate($"8ball:{userId}:{question}", e => { e.Size = question.Length; e.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12); return EightBallResponses[_rng.Next(0, EightBallResponses.Count)];; }); - } public TypingArticle RemoveTypingArticle(int index) { diff --git a/src/NadekoBot/Modules/Games/TicTacToeCommands.cs b/src/NadekoBot/Modules/Games/TicTacToeCommands.cs index 485661104..57ecb2f9f 100644 --- a/src/NadekoBot/Modules/Games/TicTacToeCommands.cs +++ b/src/NadekoBot/Modules/Games/TicTacToeCommands.cs @@ -12,9 +12,7 @@ public partial class Games private readonly DiscordSocketClient _client; public TicTacToeCommands(DiscordSocketClient client) - { - _client = client; - } + => _client = client; [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Help/Help.cs b/src/NadekoBot/Modules/Help/Help.cs index fbbf9e79e..84ace90ac 100644 --- a/src/NadekoBot/Modules/Help/Help.cs +++ b/src/NadekoBot/Modules/Help/Help.cs @@ -82,6 +82,7 @@ public class Help : NadekoModule localModules .OrderBy(module => module.Name) + .ToList() .ForEach(module => embed.AddField($"{GetModuleEmoji(module.Name)} {module.Name}", GetText(GetModuleLocStr(module.Name)) + "\n" + Format.Code(GetText(strs.module_footer(Prefix, module.Name.ToLowerInvariant()))), @@ -406,17 +407,13 @@ public class Help : NadekoModule [NadekoCommand, Aliases] public async Task Guide() - { - await ConfirmLocalizedAsync(strs.guide( + => await ConfirmLocalizedAsync(strs.guide( "https://nadeko.bot/commands", "http://nadekobot.readthedocs.io/en/latest/")); - } [NadekoCommand, Aliases] public async Task Donate() - { - await ReplyConfirmLocalizedAsync(strs.donate(PatreonUrl, PaypalUrl)); - } + => await ReplyConfirmLocalizedAsync(strs.donate(PatreonUrl, PaypalUrl)); } internal class CommandJsonObject diff --git a/src/NadekoBot/Modules/Help/Services/HelpService.cs b/src/NadekoBot/Modules/Help/Services/HelpService.cs index 5c3394a80..556430710 100644 --- a/src/NadekoBot/Modules/Help/Services/HelpService.cs +++ b/src/NadekoBot/Modules/Help/Services/HelpService.cs @@ -154,16 +154,12 @@ public class HelpService : ILateExecutor, INService } public static string GetPreconditionString(ChannelPerm perm) - { - return (perm.ToString() + " Channel Permission") + => (perm.ToString() + " Channel Permission") .Replace("Guild", "Server", StringComparison.InvariantCulture); - } public static string GetPreconditionString(GuildPerm perm) - { - return (perm.ToString() + " Server Permission") + => (perm.ToString() + " Server Permission") .Replace("Guild", "Server", StringComparison.InvariantCulture); - } private string GetText(LocStr str, IGuild guild, params object[] replacements) => _strings.GetText(str, guild?.Id); diff --git a/src/NadekoBot/Modules/Music/Common/Impl/MultimediaTimer.cs b/src/NadekoBot/Modules/Music/Common/Impl/MultimediaTimer.cs index 83c5983cf..d43ffec83 100644 --- a/src/NadekoBot/Modules/Music/Common/Impl/MultimediaTimer.cs +++ b/src/NadekoBot/Modules/Music/Common/Impl/MultimediaTimer.cs @@ -77,9 +77,7 @@ public sealed class MultimediaTimer : IDisposable } private void CallbackInternal(uint uTimerId, uint uMsg, int dwUser, int dw1, int dw2) - { - _callback(_state); - } + => _callback(_state); public void Dispose() { diff --git a/src/NadekoBot/Modules/Music/Common/Impl/MusicPlayer.cs b/src/NadekoBot/Modules/Music/Common/Impl/MusicPlayer.cs index e321e582d..ec21ea499 100644 --- a/src/NadekoBot/Modules/Music/Common/Impl/MusicPlayer.cs +++ b/src/NadekoBot/Modules/Music/Common/Impl/MusicPlayer.cs @@ -424,29 +424,19 @@ public sealed class MusicPlayer : IMusicPlayer } public void EnqueueTrack(ITrackInfo track, string queuer) - { - _queue.Enqueue(track, queuer, out _); - } + => _queue.Enqueue(track, queuer, out _); public void EnqueueTracks(IEnumerable tracks, string queuer) - { - _queue.EnqueueMany(tracks, queuer); - } + => _queue.EnqueueMany(tracks, queuer); public void SetRepeat(PlayerRepeatType type) - { - Repeat = type; - } + => Repeat = type; public void ShuffleQueue() - { - _queue.Shuffle(_rng); - } + => _queue.Shuffle(_rng); public void Stop() - { - IsStopped = true; - } + => IsStopped = true; public void Clear() { @@ -484,7 +474,7 @@ public sealed class MusicPlayer : IMusicPlayer public void SetVolume(int newVolume) { var normalizedVolume = newVolume / 100f; - if (normalizedVolume < 0f || normalizedVolume > 1f) + if (normalizedVolume is < 0f or > 1f) throw new ArgumentOutOfRangeException(nameof(newVolume), "Volume must be in range 0-100"); _volume = normalizedVolume; diff --git a/src/NadekoBot/Modules/Music/Common/Impl/RedisTrackCacher.cs b/src/NadekoBot/Modules/Music/Common/Impl/RedisTrackCacher.cs index e06357c0d..33a54623d 100644 --- a/src/NadekoBot/Modules/Music/Common/Impl/RedisTrackCacher.cs +++ b/src/NadekoBot/Modules/Music/Common/Impl/RedisTrackCacher.cs @@ -10,10 +10,8 @@ public sealed class RedisTrackCacher : ITrackCacher private readonly ConnectionMultiplexer _multiplexer; public RedisTrackCacher(ConnectionMultiplexer multiplexer) - { - _multiplexer = multiplexer; - } - + => _multiplexer = multiplexer; + public async Task GetOrCreateStreamLink( string id, MusicPlatform platform, diff --git a/src/NadekoBot/Modules/Music/Common/Impl/VoiceProxy.cs b/src/NadekoBot/Modules/Music/Common/Impl/VoiceProxy.cs index 795e008ca..f497a3cad 100644 --- a/src/NadekoBot/Modules/Music/Common/Impl/VoiceProxy.cs +++ b/src/NadekoBot/Modules/Music/Common/Impl/VoiceProxy.cs @@ -27,9 +27,7 @@ public sealed class VoiceProxy : IVoiceProxy private VoiceGateway _gateway; public VoiceProxy(VoiceGateway initial) - { - _gateway = initial; - } + => _gateway = initial; public bool SendPcmFrame(VoiceClient vc, Span data, int length) { @@ -86,24 +84,16 @@ public sealed class VoiceProxy : IVoiceProxy } public void SetGateway(VoiceGateway gateway) - { - _gateway = gateway; - } + => _gateway = gateway; public Task StartSpeakingAsync() - { - return RunGatewayAction(gw => gw.SendSpeakingAsync(VoiceSpeaking.State.Microphone)); - } + => RunGatewayAction(gw => gw.SendSpeakingAsync(VoiceSpeaking.State.Microphone)); public Task StopSpeakingAsync() - { - return RunGatewayAction(gw => gw.SendSpeakingAsync(VoiceSpeaking.State.None)); - } + => RunGatewayAction(gw => gw.SendSpeakingAsync(VoiceSpeaking.State.None)); public async Task StartGateway() - { - await _gateway.Start(); - } + => await _gateway.Start(); public Task StopGateway() { diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index f8167d13e..a33f783e1 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -11,10 +11,8 @@ public sealed partial class Music : NadekoModule private readonly ILogCommandService _logService; public Music(ILogCommandService _logService) - { - this._logService = _logService; - } - + => this._logService = _logService; + private async Task ValidateAsync() { var user = (IGuildUser) ctx.User; @@ -209,7 +207,7 @@ public sealed partial class Music : NadekoModule [RequireContext(ContextType.Guild)] public async Task Volume(int vol) { - if (vol < 0 || vol > 100) + if (vol is < 0 or > 100) { await ReplyErrorLocalizedAsync(strs.volume_input_invalid); return; @@ -313,7 +311,7 @@ public sealed partial class Music : NadekoModule return $"`{index + 1}.` {v.PrettyFullName()}"; }) - .JoinWith('\n'); + .Join('\n'); if (!string.IsNullOrWhiteSpace(add)) desc = add + "\n" + desc; @@ -353,7 +351,7 @@ public sealed partial class Music : NadekoModule var resultsString = videos .Select((x, i) => $"`{i + 1}.`\n\t{Format.Bold(x.Title)}\n\t{x.Url}") - .JoinWith('\n'); + .Join('\n'); var msg = await SendConfirmAsync(resultsString); diff --git a/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs b/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs index 9f7dbfc0a..3beef1b75 100644 --- a/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs +++ b/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs @@ -44,10 +44,8 @@ public sealed class AyuVoiceStateService : INService } private Task InvokeSendVoiceStateUpdateAsync(ulong guildId, ulong? channelId = null, bool isDeafened = false, bool isMuted = false) - { // return _voiceStateUpdate(guildId, channelId, isDeafened, isMuted); - return (Task) _sendVoiceStateUpdateMethodInfo.Invoke(_dnetApiClient, new object[] {guildId, channelId, isMuted, isDeafened, null}); - } + => (Task) _sendVoiceStateUpdateMethodInfo.Invoke(_dnetApiClient, new object[] {guildId, channelId, isMuted, isDeafened, null}); private Task SendLeaveVoiceChannelInternalAsync(ulong guildId) => InvokeSendVoiceStateUpdateAsync(guildId); diff --git a/src/NadekoBot/Modules/Music/Services/MusicService.cs b/src/NadekoBot/Modules/Music/Services/MusicService.cs index 88b0c85ab..8bc56cf22 100644 --- a/src/NadekoBot/Modules/Music/Services/MusicService.cs +++ b/src/NadekoBot/Modules/Music/Services/MusicService.cs @@ -407,7 +407,7 @@ public sealed class MusicService : IMusicService public async Task SetVolumeAsync(ulong guildId, int value) { - if (value < 0 || value > 100) + if (value is < 0 or > 100) throw new ArgumentOutOfRangeException(nameof(value)); await ModifySettingsInternalAsync(guildId, (settings, newValue) => @@ -438,12 +438,10 @@ public sealed class MusicService : IMusicService } public Task SetMusicQualityAsync(ulong guildId, QualityPreset preset) - { - return ModifySettingsInternalAsync(guildId, (settings, _) => + => ModifySettingsInternalAsync(guildId, (settings, _) => { settings.QualityPreset = preset; }, preset); - } #endregion } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Music/Services/extractor/YtLoader.cs b/src/NadekoBot/Modules/Music/Services/extractor/YtLoader.cs index bc72f51d6..0f8913aa0 100644 --- a/src/NadekoBot/Modules/Music/Services/extractor/YtLoader.cs +++ b/src/NadekoBot/Modules/Music/Services/extractor/YtLoader.cs @@ -16,9 +16,7 @@ public sealed partial class YtLoader }; public YtLoader(IHttpClientFactory httpFactory) - { - _httpFactory = httpFactory; - } + => _httpFactory = httpFactory; // public async Task LoadTrackByIdAsync(string videoId) // { @@ -115,13 +113,13 @@ public sealed partial class YtLoader private Memory GetScriptResponseSpan(byte[] response) { - var responseSpan = response.AsSpan().Slice(140_000); + var responseSpan = response.AsSpan()[140_000..]; var startIndex = responseSpan.IndexOf(YT_RESULT_INITIAL_DATA); if (startIndex == -1) return null; // todo future try selecting html startIndex += YT_RESULT_INITIAL_DATA.Length; - var endIndex = 140_000 + startIndex + responseSpan.Slice(startIndex + 20_000).IndexOf(YT_RESULT_JSON_END) + 20_000; + var endIndex = 140_000 + startIndex + responseSpan[(startIndex + 20_000)..].IndexOf(YT_RESULT_JSON_END) + 20_000; startIndex += 140_000; return response.AsMemory( startIndex, diff --git a/src/NadekoBot/Modules/Nsfw/Common/DapiTag.cs b/src/NadekoBot/Modules/Nsfw/Common/DapiTag.cs index 964663e4f..2f044c1d3 100644 --- a/src/NadekoBot/Modules/Nsfw/Common/DapiTag.cs +++ b/src/NadekoBot/Modules/Nsfw/Common/DapiTag.cs @@ -8,7 +8,5 @@ public readonly struct DapiTag [JsonConstructor] public DapiTag(string name) - { - Name = name; - } + => Name = name; } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Nsfw/Common/Downloaders/DapiImageDownloader.cs b/src/NadekoBot/Modules/Nsfw/Common/Downloaders/DapiImageDownloader.cs index 99f07451c..382e048fd 100644 --- a/src/NadekoBot/Modules/Nsfw/Common/Downloaders/DapiImageDownloader.cs +++ b/src/NadekoBot/Modules/Nsfw/Common/Downloaders/DapiImageDownloader.cs @@ -7,9 +7,7 @@ public abstract class DapiImageDownloader : ImageDownloader protected readonly string _baseUrl; public DapiImageDownloader(Booru booru, HttpClient http, string baseUrl) : base(booru, http) - { - _baseUrl = baseUrl; - } + => _baseUrl = baseUrl; public abstract Task IsTagValid(string tag, CancellationToken cancel = default); protected async Task AllTagsValid(string[] tags, CancellationToken cancel = default) diff --git a/src/NadekoBot/Modules/Nsfw/Common/Downloaders/KonachanImageDownloader.cs b/src/NadekoBot/Modules/Nsfw/Common/Downloaders/KonachanImageDownloader.cs index ef54ea35a..f912a7c26 100644 --- a/src/NadekoBot/Modules/Nsfw/Common/Downloaders/KonachanImageDownloader.cs +++ b/src/NadekoBot/Modules/Nsfw/Common/Downloaders/KonachanImageDownloader.cs @@ -8,9 +8,7 @@ public sealed class KonachanImageDownloader : ImageDownloader public KonachanImageDownloader(HttpClient http) : base(Booru.Konachan, http) - { - _baseUrl = "https://konachan.com"; - } + => _baseUrl = "https://konachan.com"; public override async Task> DownloadImagesAsync(string[] tags, int page, bool isExplicit = false, CancellationToken cancel = default) { diff --git a/src/NadekoBot/Modules/Nsfw/Common/Downloaders/YandereImageDownloader.cs b/src/NadekoBot/Modules/Nsfw/Common/Downloaders/YandereImageDownloader.cs index ec610a24a..8fb347727 100644 --- a/src/NadekoBot/Modules/Nsfw/Common/Downloaders/YandereImageDownloader.cs +++ b/src/NadekoBot/Modules/Nsfw/Common/Downloaders/YandereImageDownloader.cs @@ -8,9 +8,8 @@ public sealed class YandereImageDownloader : ImageDownloader public YandereImageDownloader(HttpClient http) : base(Booru.Yandere, http) - { - _baseUrl = "https://yande.re"; - } + => _baseUrl = "https://yande.re"; + public override async Task> DownloadImagesAsync(string[] tags, int page, bool isExplicit = false, CancellationToken cancel = default) { var tagString = ImageDownloaderHelper.GetTagString(tags, isExplicit); diff --git a/src/NadekoBot/Modules/Nsfw/Common/ImageData.cs b/src/NadekoBot/Modules/Nsfw/Common/ImageData.cs index 7e61d37c2..6dad3942d 100644 --- a/src/NadekoBot/Modules/Nsfw/Common/ImageData.cs +++ b/src/NadekoBot/Modules/Nsfw/Common/ImageData.cs @@ -25,9 +25,7 @@ public class ImageData : IComparable } public override string ToString() - { - return FileUrl; - } + => FileUrl; public override int GetHashCode() => FileUrl.GetHashCode(); public override bool Equals(object obj) diff --git a/src/NadekoBot/Modules/Nsfw/Common/Rule34Object.cs b/src/NadekoBot/Modules/Nsfw/Common/Rule34Object.cs index 7fad41f35..0b05bbaf6 100644 --- a/src/NadekoBot/Modules/Nsfw/Common/Rule34Object.cs +++ b/src/NadekoBot/Modules/Nsfw/Common/Rule34Object.cs @@ -8,11 +8,9 @@ public class Rule34Object : IImageData public int Score { get; init; } public ImageData ToCachedImageData(Booru type) - { - return new( + => new( $"https://img.rule34.xxx//images/{Directory}/{Image}", Booru.Rule34, Tags.Split(' '), Score.ToString()); - } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Nsfw/Nsfw.cs b/src/NadekoBot/Modules/Nsfw/Nsfw.cs index 112e3db24..1577f96a9 100644 --- a/src/NadekoBot/Modules/Nsfw/Nsfw.cs +++ b/src/NadekoBot/Modules/Nsfw/Nsfw.cs @@ -1,5 +1,4 @@ -using NadekoBot.Common.Collections; -using NadekoBot.Modules.Searches.Common; +using NadekoBot.Modules.Searches.Common; using Newtonsoft.Json.Linq; namespace NadekoBot.Modules.Nsfw; @@ -377,7 +376,7 @@ public class NSFW : NadekoModule .Shuffle() .Select(tag => $"[{tag.Name}]({tag.Url})") .TakeWhile(tag => (count += tag.Length) < 1000) - .JoinWith(" "); + .Join(" "); var embed = _eb.Create() .WithTitle(g.Title) diff --git a/src/NadekoBot/Modules/Nsfw/SearchImageCacher.cs b/src/NadekoBot/Modules/Nsfw/SearchImageCacher.cs index 711d81417..809a42a0c 100644 --- a/src/NadekoBot/Modules/Nsfw/SearchImageCacher.cs +++ b/src/NadekoBot/Modules/Nsfw/SearchImageCacher.cs @@ -68,6 +68,7 @@ public class SearchImageCacher : INService .Distinct() .Shuffle() .Take(50) + .ToList() .ForEach(x => typeUsedTags.Add(x)); foreach (var img in images) diff --git a/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs b/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs index 869ada1ba..83f408cc9 100644 --- a/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs +++ b/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs @@ -53,9 +53,7 @@ public class SearchImagesService : ISearchImagesService, INService } private Task GetNsfwImageAsync(ulong? guildId, bool forceExplicit, string[] tags, Booru dapi, CancellationToken cancel = default) - { - return GetNsfwImageAsync(guildId ?? 0, tags ?? Array.Empty(), forceExplicit, dapi, cancel); - } + => GetNsfwImageAsync(guildId ?? 0, tags ?? Array.Empty(), forceExplicit, dapi, cancel); private bool IsValidTag(string tag) => tag.All(x => x != '+' && x != '?' && x != '/'); // tags mustn't contain + or ? or / diff --git a/src/NadekoBot/Modules/Permissions/BlacklistCommands.cs b/src/NadekoBot/Modules/Permissions/BlacklistCommands.cs index 3d7dce875..4e25618c6 100644 --- a/src/NadekoBot/Modules/Permissions/BlacklistCommands.cs +++ b/src/NadekoBot/Modules/Permissions/BlacklistCommands.cs @@ -12,10 +12,8 @@ public partial class Permissions private readonly DiscordSocketClient _client; public BlacklistCommands(DiscordSocketClient client) - { - _client = client; - } - + => _client = client; + private async Task ListBlacklistInternal(string title, BlacklistType type, int page = 0) { if (page < 0) @@ -65,7 +63,7 @@ public partial class Permissions return _eb.Create() .WithTitle(title) - .WithDescription(pageItems.JoinWith('\n')) + .WithDescription(pageItems.Join('\n')) .WithOkColor(); }, items.Length, 10); } diff --git a/src/NadekoBot/Modules/Permissions/CmdCdsCommands.cs b/src/NadekoBot/Modules/Permissions/CmdCdsCommands.cs index 49192c348..79d540b61 100644 --- a/src/NadekoBot/Modules/Permissions/CmdCdsCommands.cs +++ b/src/NadekoBot/Modules/Permissions/CmdCdsCommands.cs @@ -1,6 +1,5 @@ using Microsoft.EntityFrameworkCore; using NadekoBot.Services.Database.Models; -using NadekoBot.Common.Collections; using NadekoBot.Common.TypeReaders; using NadekoBot.Db; using NadekoBot.Modules.Permissions.Services; @@ -31,7 +30,7 @@ public partial class Permissions public async Task CmdCooldown(CommandOrCrInfo command, int secs) { var channel = (ITextChannel)ctx.Channel; - if (secs < 0 || secs > 3600) + if (secs is < 0 or > 3600) { await ReplyErrorLocalizedAsync(strs.invalid_second_param_between(0, 3600)); return; diff --git a/src/NadekoBot/Modules/Permissions/FilterCommands.cs b/src/NadekoBot/Modules/Permissions/FilterCommands.cs index 0f2698e5c..4aa035541 100644 --- a/src/NadekoBot/Modules/Permissions/FilterCommands.cs +++ b/src/NadekoBot/Modules/Permissions/FilterCommands.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore; -using NadekoBot.Common.Collections; using NadekoBot.Modules.Permissions.Services; using NadekoBot.Services.Database.Models; using NadekoBot.Db; @@ -14,9 +13,7 @@ public partial class Permissions private readonly DbService _db; public FilterCommands(DbService db) - { - _db = db; - } + => _db = db; [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Permissions/Permissions.cs b/src/NadekoBot/Modules/Permissions/Permissions.cs index 4e4ccc008..81e657f5f 100644 --- a/src/NadekoBot/Modules/Permissions/Permissions.cs +++ b/src/NadekoBot/Modules/Permissions/Permissions.cs @@ -12,9 +12,7 @@ public partial class Permissions : NadekoModule private readonly DbService _db; public Permissions(DbService db) - { - _db = db; - } + => _db = db; [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] @@ -203,7 +201,7 @@ public partial class Permissions : NadekoModule return; } - catch (Exception e) when (e is ArgumentOutOfRangeException || e is IndexOutOfRangeException) + catch (Exception e) when (e is ArgumentOutOfRangeException or IndexOutOfRangeException) { } } diff --git a/src/NadekoBot/Modules/Permissions/Services/CmdCdService.cs b/src/NadekoBot/Modules/Permissions/Services/CmdCdService.cs index 1ac5767e9..c7a279297 100644 --- a/src/NadekoBot/Modules/Permissions/Services/CmdCdService.cs +++ b/src/NadekoBot/Modules/Permissions/Services/CmdCdService.cs @@ -1,5 +1,4 @@ -using NadekoBot.Common.Collections; -using NadekoBot.Common.ModuleBehaviors; +using NadekoBot.Common.ModuleBehaviors; using NadekoBot.Services.Database.Models; namespace NadekoBot.Modules.Permissions.Services; @@ -12,11 +11,9 @@ public class CmdCdService : ILateBlocker, INService public int Priority { get; } = 0; public CmdCdService(Bot bot) - { - CommandCooldowns = new( + => CommandCooldowns = new( bot.AllGuildConfigs.ToDictionary(k => k.GuildId, v => new ConcurrentHashSet(v.CommandCooldowns))); - } public Task TryBlock(IGuild guild, IUser user, string commandName) { diff --git a/src/NadekoBot/Modules/Permissions/Services/FilterService.cs b/src/NadekoBot/Modules/Permissions/Services/FilterService.cs index 4bec55525..4c99d34f6 100644 --- a/src/NadekoBot/Modules/Permissions/Services/FilterService.cs +++ b/src/NadekoBot/Modules/Permissions/Services/FilterService.cs @@ -1,5 +1,4 @@ -using NadekoBot.Common.Collections; -using NadekoBot.Common.ModuleBehaviors; +using NadekoBot.Common.ModuleBehaviors; using Microsoft.EntityFrameworkCore; using NadekoBot.Services.Database.Models; using NadekoBot.Db; diff --git a/src/NadekoBot/Modules/Permissions/Services/GlobalPermissionService.cs b/src/NadekoBot/Modules/Permissions/Services/GlobalPermissionService.cs index c2a113c36..a4fcd1e9b 100644 --- a/src/NadekoBot/Modules/Permissions/Services/GlobalPermissionService.cs +++ b/src/NadekoBot/Modules/Permissions/Services/GlobalPermissionService.cs @@ -11,9 +11,7 @@ public class GlobalPermissionService : ILateBlocker, INService public HashSet BlockedModules => _bss.Data.Blocked.Modules; public GlobalPermissionService(BotConfigService bss) - { - _bss = bss; - } + => _bss = bss; public Task TryBlockLate(ICommandContext ctx, string moduleName, CommandInfo command) diff --git a/src/NadekoBot/Modules/Permissions/Services/PermissionsService.cs b/src/NadekoBot/Modules/Permissions/Services/PermissionsService.cs index fff78bc27..b1ef8493f 100644 --- a/src/NadekoBot/Modules/Permissions/Services/PermissionsService.cs +++ b/src/NadekoBot/Modules/Permissions/Services/PermissionsService.cs @@ -75,8 +75,7 @@ public class PermissionService : ILateBlocker, INService } public void UpdateCache(GuildConfig config) - { - Cache.AddOrUpdate(config.GuildId, new PermissionCache() + => Cache.AddOrUpdate(config.GuildId, new PermissionCache() { Permissions = new(config.Permissions), PermRole = config.PermissionRole, @@ -88,7 +87,6 @@ public class PermissionService : ILateBlocker, INService old.Verbose = config.VerbosePermissions; return old; }); - } public async Task TryBlockLate(ICommandContext ctx, string moduleName, CommandInfo command) { diff --git a/src/NadekoBot/Modules/Searches/Common/AnimeResult.cs b/src/NadekoBot/Modules/Searches/Common/AnimeResult.cs index 4f8816967..c1696281f 100644 --- a/src/NadekoBot/Modules/Searches/Common/AnimeResult.cs +++ b/src/NadekoBot/Modules/Searches/Common/AnimeResult.cs @@ -20,5 +20,5 @@ public class AnimeResult public string AverageScore { get; set; } public string Link => "http://anilist.co/anime/" + Id; - public string Synopsis => Description?.Substring(0, Description.Length > 500 ? 500 : Description.Length) + "..."; + public string Synopsis => Description?[..(Description.Length > 500 ? 500 : Description.Length)] + "..."; } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Searches/Common/ImageCacherObject.cs b/src/NadekoBot/Modules/Searches/Common/ImageCacherObject.cs index a277b0e37..7d9893de3 100644 --- a/src/NadekoBot/Modules/Searches/Common/ImageCacherObject.cs +++ b/src/NadekoBot/Modules/Searches/Common/ImageCacherObject.cs @@ -33,12 +33,8 @@ public class ImageCacherObject : IComparable } public override string ToString() - { - return FileUrl; - } + => FileUrl; public int CompareTo(ImageCacherObject other) - { - return string.Compare(FileUrl, other.FileUrl, StringComparison.InvariantCulture); - } + => string.Compare(FileUrl, other.FileUrl, StringComparison.InvariantCulture); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Searches/Common/MangaResult.cs b/src/NadekoBot/Modules/Searches/Common/MangaResult.cs index 76354a64d..18512d8ee 100644 --- a/src/NadekoBot/Modules/Searches/Common/MangaResult.cs +++ b/src/NadekoBot/Modules/Searches/Common/MangaResult.cs @@ -20,5 +20,5 @@ public class MangaResult [JsonProperty("average_score")] public string AverageScore { get; set; } public string Link => "http://anilist.co/manga/" + Id; - public string Synopsis => Description?.Substring(0, Description.Length > 500 ? 500 : Description.Length) + "..."; + public string Synopsis => Description?[..(Description.Length > 500 ? 500 : Description.Length)] + "..."; } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/NotifChecker.cs b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/NotifChecker.cs index 2f6e38200..47d7481d1 100644 --- a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/NotifChecker.cs +++ b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/NotifChecker.cs @@ -236,7 +236,5 @@ public class NotifChecker } public void UntrackStreamByKey(in StreamDataKey key) - { - CacheDeleteData(key); - } + => CacheDeleteData(key); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/PicartoProvider.cs b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/PicartoProvider.cs index 1ed650b76..f745e3f27 100644 --- a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/PicartoProvider.cs +++ b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/PicartoProvider.cs @@ -15,9 +15,7 @@ public class PicartoProvider : Provider public override FollowedStream.FType Platform => FollowedStream.FType.Picarto; public PicartoProvider(IHttpClientFactory httpClientFactory) - { - _httpClientFactory = httpClientFactory; - } + => _httpClientFactory = httpClientFactory; public override Task IsValidUrl(string url) { @@ -82,8 +80,7 @@ public class PicartoProvider : Provider } private StreamData ToStreamData(PicartoChannelResponse stream) - { - return new() + => new() { StreamType = FollowedStream.FType.Picarto, Name = stream.Name, @@ -96,5 +93,4 @@ public class PicartoProvider : Provider StreamUrl = $"https://picarto.tv/{stream.Name}", AvatarUrl = stream.Avatar }; - } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/TwitchProvider.cs b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/TwitchProvider.cs index 1e5b5261b..ccca2319d 100644 --- a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/TwitchProvider.cs +++ b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/TwitchProvider.cs @@ -15,9 +15,7 @@ public class TwitchProvider : Provider public override FollowedStream.FType Platform => FollowedStream.FType.Twitch; public TwitchProvider(IHttpClientFactory httpClientFactory) - { - _httpClientFactory = httpClientFactory; - } + => _httpClientFactory = httpClientFactory; public override Task IsValidUrl(string url) { @@ -111,8 +109,7 @@ public class TwitchProvider : Provider } private StreamData ToStreamData(TwitchResponseV5.Stream stream) - { - return new() + => new() { StreamType = FollowedStream.FType.Twitch, Name = stream.Channel.DisplayName, @@ -125,5 +122,4 @@ public class TwitchProvider : Provider StreamUrl = $"https://twitch.tv/{stream.Channel.Name}", AvatarUrl = stream.Channel.Logo }; - } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Searches/JokeCommands.cs b/src/NadekoBot/Modules/Searches/JokeCommands.cs index 2f1d654d8..dd0f037ab 100644 --- a/src/NadekoBot/Modules/Searches/JokeCommands.cs +++ b/src/NadekoBot/Modules/Searches/JokeCommands.cs @@ -10,9 +10,7 @@ public partial class Searches [NadekoCommand, Aliases] public async Task Yomama() - { - await SendConfirmAsync(await _service.GetYomamaJoke().ConfigureAwait(false)).ConfigureAwait(false); - } + => await SendConfirmAsync(await _service.GetYomamaJoke().ConfigureAwait(false)).ConfigureAwait(false); [NadekoCommand, Aliases] public async Task Randjoke() @@ -23,9 +21,7 @@ public partial class Searches [NadekoCommand, Aliases] public async Task ChuckNorris() - { - await SendConfirmAsync(await _service.GetChuckNorrisJoke().ConfigureAwait(false)).ConfigureAwait(false); - } + => await SendConfirmAsync(await _service.GetChuckNorrisJoke().ConfigureAwait(false)).ConfigureAwait(false); [NadekoCommand, Aliases] public async Task WowJoke() diff --git a/src/NadekoBot/Modules/Searches/MemegenCommands.cs b/src/NadekoBot/Modules/Searches/MemegenCommands.cs index d34c3618e..b42d66288 100644 --- a/src/NadekoBot/Modules/Searches/MemegenCommands.cs +++ b/src/NadekoBot/Modules/Searches/MemegenCommands.cs @@ -29,9 +29,7 @@ public partial class Searches private readonly IHttpClientFactory _httpFactory; public MemegenCommands(IHttpClientFactory factory) - { - _httpFactory = factory; - } + => _httpFactory = factory; [NadekoCommand, Aliases] public async Task Memelist(int page = 1) diff --git a/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs b/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs index 5e994dbf9..caa56b511 100644 --- a/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs +++ b/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs @@ -21,9 +21,7 @@ public partial class Searches private readonly IHttpClientFactory _httpFactory; public PathOfExileCommands(IHttpClientFactory httpFactory) - { - _httpFactory = httpFactory; - } + => _httpFactory = httpFactory; [NadekoCommand, Aliases] public async Task PathOfExile(string usr, string league = "", int page = 1) diff --git a/src/NadekoBot/Modules/Searches/PlaceCommands.cs b/src/NadekoBot/Modules/Searches/PlaceCommands.cs index 2ab95b982..45fb34e04 100644 --- a/src/NadekoBot/Modules/Searches/PlaceCommands.cs +++ b/src/NadekoBot/Modules/Searches/PlaceCommands.cs @@ -22,11 +22,9 @@ public partial class Searches [NadekoCommand, Aliases] public async Task Placelist() - { - await SendConfirmAsync(GetText(strs.list_of_place_tags(Prefix)), + => await SendConfirmAsync(GetText(strs.list_of_place_tags(Prefix)), _typesStr) .ConfigureAwait(false); - } [NadekoCommand, Aliases] public async Task Place(PlaceType placeType, uint width = 0, uint height = 0) @@ -60,10 +58,10 @@ public partial class Searches break; } var rng = new NadekoRandom(); - if (width <= 0 || width > 1000) + if (width is <= 0 or > 1000) width = (uint)rng.Next(250, 850); - if (height <= 0 || height > 1000) + if (height is <= 0 or > 1000) height = (uint)rng.Next(250, 850); url += $"/{width}/{height}"; diff --git a/src/NadekoBot/Modules/Searches/PokemonSearchCommands.cs b/src/NadekoBot/Modules/Searches/PokemonSearchCommands.cs index 97fd00e26..45089ced7 100644 --- a/src/NadekoBot/Modules/Searches/PokemonSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/PokemonSearchCommands.cs @@ -14,9 +14,7 @@ public partial class Searches public IReadOnlyDictionary PokemonAbilities => _cache.LocalData.PokemonAbilities; public PokemonSearchCommands(IDataCache cache) - { - _cache = cache; - } + => _cache = cache; [NadekoCommand, Aliases] public async Task Pokemon([Leftover] string pokemon = null) diff --git a/src/NadekoBot/Modules/Searches/Services/FeedsService.cs b/src/NadekoBot/Modules/Searches/Services/FeedsService.cs index ba7148b4d..6fce998bb 100644 --- a/src/NadekoBot/Modules/Searches/Services/FeedsService.cs +++ b/src/NadekoBot/Modules/Searches/Services/FeedsService.cs @@ -130,7 +130,7 @@ public class FeedsService : INService embed.WithTitle(title.TrimTo(256)); - var desc = feedItem.Description?.StripHTML(); + var desc = feedItem.Description?.StripHtml(); if (!string.IsNullOrWhiteSpace(feedItem.Description)) embed.WithDescription(desc.TrimTo(2048)); @@ -167,7 +167,7 @@ public class FeedsService : INService public bool AddFeed(ulong guildId, ulong channelId, string rssFeed) { - rssFeed.ThrowIfNull(nameof(rssFeed)); + ArgumentNullException.ThrowIfNull(rssFeed, nameof(rssFeed)); var fs = new FeedSub() { diff --git a/src/NadekoBot/Modules/Searches/Services/SearchesService.cs b/src/NadekoBot/Modules/Searches/Services/SearchesService.cs index 2d8a4d14e..de2df675b 100644 --- a/src/NadekoBot/Modules/Searches/Services/SearchesService.cs +++ b/src/NadekoBot/Modules/Searches/Services/SearchesService.cs @@ -163,13 +163,12 @@ public class SearchesService : INService } public Task<((string Address, DateTime Time, string TimeZoneName), TimeErrors?)> GetTimeDataAsync(string arg) - { - return GetTimeDataFactory(arg); - //return _cache.GetOrAddCachedDataAsync($"nadeko_time_{arg}", - // GetTimeDataFactory, - // arg, - // TimeSpan.FromMinutes(1)); - } + => GetTimeDataFactory(arg); + + //return _cache.GetOrAddCachedDataAsync($"nadeko_time_{arg}", + // GetTimeDataFactory, + // arg, + // TimeSpan.FromMinutes(1)); private async Task<((string Address, DateTime Time, string TimeZoneName), TimeErrors?)> GetTimeDataFactory(string query) { query = query.Trim(); diff --git a/src/NadekoBot/Modules/Searches/Services/StreamNotificationService.cs b/src/NadekoBot/Modules/Searches/Services/StreamNotificationService.cs index 3829a376a..bb50fa087 100644 --- a/src/NadekoBot/Modules/Searches/Services/StreamNotificationService.cs +++ b/src/NadekoBot/Modules/Searches/Services/StreamNotificationService.cs @@ -3,7 +3,6 @@ using NadekoBot.Modules.Searches.Common; using NadekoBot.Modules.Searches.Common.StreamNotifications; using NadekoBot.Services.Database.Models; using StackExchange.Redis; -using NadekoBot.Common.Collections; using NadekoBot.Db; using NadekoBot.Db.Models; @@ -477,9 +476,7 @@ public sealed class StreamNotificationService : INService } public Task GetStreamDataAsync(string url) - { - return _streamTracker.GetStreamDataByUrlAsync(url); - } + => _streamTracker.GetStreamDataByUrlAsync(url); private HashSet GetLocalGuildStreams(in StreamDataKey key, ulong guildId) { diff --git a/src/NadekoBot/Modules/Searches/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/StreamNotificationCommands.cs index cb22f0c07..ad0142e1e 100644 --- a/src/NadekoBot/Modules/Searches/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/StreamNotificationCommands.cs @@ -13,9 +13,7 @@ public partial class Searches private readonly DbService _db; public StreamNotificationCommands(DbService db) - { - _db = db; - } + => _db = db; // private static readonly Regex picartoRegex = new Regex(@"picarto.tv/(?.+[^/])/?", // RegexOptions.Compiled | RegexOptions.IgnoreCase); diff --git a/src/NadekoBot/Modules/Searches/TranslatorCommands.cs b/src/NadekoBot/Modules/Searches/TranslatorCommands.cs index dd8db8633..8d1a71dee 100644 --- a/src/NadekoBot/Modules/Searches/TranslatorCommands.cs +++ b/src/NadekoBot/Modules/Searches/TranslatorCommands.cs @@ -87,9 +87,6 @@ public partial class Searches [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] public async Task Translangs() - { - await ctx.Channel.SendTableAsync(_service.GetLanguages(), str => $"{str,-15}", 3).ConfigureAwait(false); - } - + => await ctx.Channel.SendTableAsync(_service.GetLanguages(), str => $"{str,-15}", 3).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Searches/XkcdCommands.cs b/src/NadekoBot/Modules/Searches/XkcdCommands.cs index 611bf7ee3..9d35a721e 100644 --- a/src/NadekoBot/Modules/Searches/XkcdCommands.cs +++ b/src/NadekoBot/Modules/Searches/XkcdCommands.cs @@ -11,9 +11,7 @@ public partial class Searches private readonly IHttpClientFactory _httpFactory; public XkcdCommands(IHttpClientFactory factory) - { - _httpFactory = factory; - } + => _httpFactory = factory; [NadekoCommand, Aliases] [Priority(0)] diff --git a/src/NadekoBot/Modules/Utility/ConfigCommands.cs b/src/NadekoBot/Modules/Utility/ConfigCommands.cs index 3adfd6e4c..cd0cdcf9b 100644 --- a/src/NadekoBot/Modules/Utility/ConfigCommands.cs +++ b/src/NadekoBot/Modules/Utility/ConfigCommands.cs @@ -1,6 +1,4 @@ -using NadekoBot.Modules.Administration.Services; - -namespace NadekoBot.Modules.Utility; +namespace NadekoBot.Modules.Utility; public partial class Utility { @@ -9,9 +7,7 @@ public partial class Utility private readonly IEnumerable _settingServices; public ConfigCommands(IEnumerable settingServices) - { - _settingServices = settingServices; - } + => _settingServices = settingServices; [NadekoCommand, Aliases] [OwnerOnly] diff --git a/src/NadekoBot/Modules/Utility/InviteCommands.cs b/src/NadekoBot/Modules/Utility/InviteCommands.cs index 9863f14f0..95bdb2206 100644 --- a/src/NadekoBot/Modules/Utility/InviteCommands.cs +++ b/src/NadekoBot/Modules/Utility/InviteCommands.cs @@ -54,7 +54,7 @@ public partial class Utility var embed = _eb.Create().WithOkColor(); foreach (var inv in invites) { - var expiryString = inv.MaxAge is null || inv.MaxAge == 0 || inv.CreatedAt is null + var expiryString = inv.MaxAge is null or 0 || inv.CreatedAt is null ? "∞" : (inv.CreatedAt.Value.AddSeconds(inv.MaxAge.Value).UtcDateTime - DateTime.UtcNow) .ToString(@"d\.hh\:mm\:ss"); diff --git a/src/NadekoBot/Modules/Utility/QuoteCommands.cs b/src/NadekoBot/Modules/Utility/QuoteCommands.cs index bdaecc606..fe481e93b 100644 --- a/src/NadekoBot/Modules/Utility/QuoteCommands.cs +++ b/src/NadekoBot/Modules/Utility/QuoteCommands.cs @@ -103,15 +103,13 @@ public partial class Utility } private async Task ShowQuoteData(Quote data) - { - await ctx.Channel.EmbedAsync(_eb.Create(ctx) + => await ctx.Channel.EmbedAsync(_eb.Create(ctx) .WithOkColor() .WithTitle(GetText(strs.quote_id($"#{data.Id}"))) .AddField(GetText(strs.trigger), data.Keyword) .AddField(GetText(strs.response), Format.Sanitize(data.Text).Replace("](", "]\\(")) .WithFooter(GetText(strs.created_by($"{data.AuthorName} ({data.AuthorId})"))) ).ConfigureAwait(false); - } [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Utility/RepeatCommands.cs b/src/NadekoBot/Modules/Utility/RepeatCommands.cs index 75e16b5e5..461d6ef88 100644 --- a/src/NadekoBot/Modules/Utility/RepeatCommands.cs +++ b/src/NadekoBot/Modules/Utility/RepeatCommands.cs @@ -175,11 +175,11 @@ public partial class Utility private string GetRepeaterInfoString(RunningRepeater runner) { - var intervalString = Format.Bold(runner.Repeater.Interval.ToPrettyStringHM()); + var intervalString = Format.Bold(runner.Repeater.Interval.ToPrettyStringHm()); var executesIn = runner.NextTime < DateTime.UtcNow ? TimeSpan.Zero : runner.NextTime - DateTime.UtcNow; - var executesInString = Format.Bold(executesIn.ToPrettyStringHM()); + var executesInString = Format.Bold(executesIn.ToPrettyStringHm()); var message = Format.Sanitize(runner.Repeater.Message.TrimTo(50)); var description = string.Empty; diff --git a/src/NadekoBot/Modules/Utility/Services/RemindService.cs b/src/NadekoBot/Modules/Utility/Services/RemindService.cs index f35ca9dfe..7dcfb9bd4 100644 --- a/src/NadekoBot/Modules/Utility/Services/RemindService.cs +++ b/src/NadekoBot/Modules/Utility/Services/RemindService.cs @@ -99,7 +99,7 @@ public class RemindService : INService foreach (var groupName in _regex.GetGroupNames()) { - if (groupName == "0" || groupName== "what") continue; + if (groupName is "0" or "what") continue; if (string.IsNullOrWhiteSpace(m.Groups[groupName].Value)) { values[groupName] = 0; diff --git a/src/NadekoBot/Modules/Utility/Services/RepeaterService.cs b/src/NadekoBot/Modules/Utility/Services/RepeaterService.cs index b881f4fb3..6aa187c65 100644 --- a/src/NadekoBot/Modules/Utility/Services/RepeaterService.cs +++ b/src/NadekoBot/Modules/Utility/Services/RepeaterService.cs @@ -2,7 +2,6 @@ using Microsoft.EntityFrameworkCore; using LinqToDB; using LinqToDB.EntityFrameworkCore; -using NadekoBot.Common.Collections; using NadekoBot.Common.ModuleBehaviors; using NadekoBot.Services.Database.Models; @@ -418,7 +417,5 @@ where ((guildid >> 22) % {_creds.TotalShards}) == {_client.ShardId};") } public bool IsNoRedundant(int repeaterId) - { - return _noRedundant.Contains(repeaterId); - } + => _noRedundant.Contains(repeaterId); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Utility/Services/RunningRepeater.cs b/src/NadekoBot/Modules/Utility/Services/RunningRepeater.cs index 7ee62f1bd..3a67c4594 100644 --- a/src/NadekoBot/Modules/Utility/Services/RunningRepeater.cs +++ b/src/NadekoBot/Modules/Utility/Services/RunningRepeater.cs @@ -16,10 +16,8 @@ public sealed class RunningRepeater } public void UpdateNextTime() - { - NextTime = DateTime.UtcNow + Repeater.Interval; - } - + => NextTime = DateTime.UtcNow + Repeater.Interval; + private DateTime CalculateInitialExecution() { if (Repeater.StartTimeOfDay != null) @@ -93,12 +91,8 @@ public sealed class RunningRepeater } public override bool Equals(object obj) - { - return obj is RunningRepeater rr && rr.Repeater.Id == this.Repeater.Id; - } + => obj is RunningRepeater rr && rr.Repeater.Id == this.Repeater.Id; public override int GetHashCode() - { - return this.Repeater.Id; - } + => this.Repeater.Id; } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Utility/Services/StreamRoleService.cs b/src/NadekoBot/Modules/Utility/Services/StreamRoleService.cs index 2b236f0ec..49b401474 100644 --- a/src/NadekoBot/Modules/Utility/Services/StreamRoleService.cs +++ b/src/NadekoBot/Modules/Utility/Services/StreamRoleService.cs @@ -60,7 +60,7 @@ public class StreamRoleService : INService /// Whether the operation was successful public async Task ApplyListAction(StreamRoleListType listType, IGuild guild, AddRemove action, ulong userId, string userName) { - userName.ThrowIfNull(nameof(userName)); + ArgumentNullException.ThrowIfNull(userName, nameof(userName)); var success = false; await using (var uow = _db.GetDbContext()) @@ -170,8 +170,8 @@ public class StreamRoleService : INService /// Role to add to the user public async Task SetStreamRole(IRole fromRole, IRole addRole) { - fromRole.ThrowIfNull(nameof(fromRole)); - addRole.ThrowIfNull(nameof(addRole)); + ArgumentNullException.ThrowIfNull(fromRole, nameof(fromRole)); + ArgumentNullException.ThrowIfNull(addRole, nameof(addRole)); StreamRoleSettings setting; await using (var uow = _db.GetDbContext()) @@ -304,7 +304,5 @@ public class StreamRoleService : INService } private void UpdateCache(ulong guildId, StreamRoleSettings setting) - { - guildSettings.AddOrUpdate(guildId, key => setting, (key, old) => setting); - } + => guildSettings.AddOrUpdate(guildId, key => setting, (key, old) => setting); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Utility/Services/VerboseErrorsService.cs b/src/NadekoBot/Modules/Utility/Services/VerboseErrorsService.cs index cb1c2526e..7d99fe082 100644 --- a/src/NadekoBot/Modules/Utility/Services/VerboseErrorsService.cs +++ b/src/NadekoBot/Modules/Utility/Services/VerboseErrorsService.cs @@ -1,5 +1,4 @@ -using NadekoBot.Common.Collections; -using NadekoBot.Modules.Help.Services; +using NadekoBot.Modules.Help.Services; using NadekoBot.Db; namespace NadekoBot.Modules.Utility.Services; diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index 165f018d8..642712323 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -154,23 +154,17 @@ public partial class Utility : NadekoModule [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] public async Task RoleId([Leftover] IRole role) - { - await ReplyConfirmLocalizedAsync(strs.roleid("🆔", Format.Bold(role.ToString()), + => await ReplyConfirmLocalizedAsync(strs.roleid("🆔", Format.Bold(role.ToString()), Format.Code(role.Id.ToString()))); - } [NadekoCommand, Aliases] public async Task ChannelId() - { - await ReplyConfirmLocalizedAsync(strs.channelid("🆔", Format.Code(ctx.Channel.Id.ToString()))); - } + => await ReplyConfirmLocalizedAsync(strs.channelid("🆔", Format.Code(ctx.Channel.Id.ToString()))); [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] public async Task ServerId() - { - await ReplyConfirmLocalizedAsync(strs.serverid("🆔", Format.Code(ctx.Guild.Id.ToString()))); - } + => await ReplyConfirmLocalizedAsync(strs.serverid("🆔", Format.Code(ctx.Guild.Id.ToString()))); [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] @@ -180,7 +174,7 @@ public partial class Utility : NadekoModule const int rolesPerPage = 20; - if (page < 1 || page > 100) + if (page is < 1 or > 100) return; if (target != null) diff --git a/src/NadekoBot/Modules/Xp/Club.cs b/src/NadekoBot/Modules/Xp/Club.cs index dc9f4ee7b..230219600 100644 --- a/src/NadekoBot/Modules/Xp/Club.cs +++ b/src/NadekoBot/Modules/Xp/Club.cs @@ -10,9 +10,7 @@ public partial class Xp private readonly XpService _xps; public Club(XpService xps) - { - _xps = xps; - } + => _xps = xps; [NadekoCommand, Aliases] public async Task ClubTransfer([Leftover] IUser newOwner) diff --git a/src/NadekoBot/Modules/Xp/Common/XpTemplate.cs b/src/NadekoBot/Modules/Xp/Common/XpTemplate.cs index bdfa20e62..ed8bc41c3 100644 --- a/src/NadekoBot/Modules/Xp/Common/XpTemplate.cs +++ b/src/NadekoBot/Modules/Xp/Common/XpTemplate.cs @@ -283,12 +283,8 @@ public enum XpTemplateDirection public class XpRgba32Converter : JsonConverter { public override Rgba32 ReadJson(JsonReader reader, Type objectType, Rgba32 existingValue, bool hasExistingValue, JsonSerializer serializer) - { - return SixLabors.ImageSharp.Color.ParseHex(reader.Value?.ToString()); - } + => SixLabors.ImageSharp.Color.ParseHex(reader.Value?.ToString()); public override void WriteJson(JsonWriter writer, Rgba32 value, JsonSerializer serializer) - { - writer.WriteValue(value.ToHex().ToLowerInvariant()); - } + => writer.WriteValue(value.ToHex().ToLowerInvariant()); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Xp/Services/UserCacheItem.cs b/src/NadekoBot/Modules/Xp/Services/UserCacheItem.cs index a43ba21e6..ae995a69d 100644 --- a/src/NadekoBot/Modules/Xp/Services/UserCacheItem.cs +++ b/src/NadekoBot/Modules/Xp/Services/UserCacheItem.cs @@ -8,12 +8,8 @@ public class UserCacheItem public int XpAmount { get; set; } public override int GetHashCode() - { - return User.GetHashCode(); - } + => User.GetHashCode(); public override bool Equals(object obj) - { - return obj is UserCacheItem uci && uci.User == User; - } + => obj is UserCacheItem uci && uci.User == User; } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Xp/Services/XpService.cs b/src/NadekoBot/Modules/Xp/Services/XpService.cs index 0d90698aa..f007231ad 100644 --- a/src/NadekoBot/Modules/Xp/Services/XpService.cs +++ b/src/NadekoBot/Modules/Xp/Services/XpService.cs @@ -1,4 +1,3 @@ -using NadekoBot.Common.Collections; using NadekoBot.Db.Models; using Newtonsoft.Json; using SixLabors.Fonts; @@ -312,9 +311,7 @@ public class XpService : INService } public void ReloadXpTemplate() - { - _pubSub.Pub(_xpTemplateReloadKey, true); - } + => _pubSub.Pub(_xpTemplateReloadKey, true); public void SetCurrencyReward(ulong guildId, int level, int amount) { @@ -527,14 +524,10 @@ public class XpService : INService } private bool ShouldTrackVoiceChannel(SocketVoiceChannel channel) - { - return channel.Users.Where(UserParticipatingInVoiceChannel).Take(2).Count() >= 2; - } + => channel.Users.Where(UserParticipatingInVoiceChannel).Take(2).Count() >= 2; private bool UserParticipatingInVoiceChannel(SocketGuildUser user) - { - return !user.IsDeafened && !user.IsMuted && !user.IsSelfDeafened && !user.IsSelfMuted; - } + => !user.IsDeafened && !user.IsMuted && !user.IsSelfDeafened && !user.IsSelfMuted; private void UserJoinedVoiceChannel(SocketGuildUser user) { @@ -650,9 +643,7 @@ public class XpService : INService } public bool IsServerExcluded(ulong id) - { - return _excludedServers.Contains(id); - } + => _excludedServers.Contains(id); public IEnumerable GetExcludedRoles(ulong id) { diff --git a/src/NadekoBot/Modules/Xp/Xp.cs b/src/NadekoBot/Modules/Xp/Xp.cs index d3e184589..4f783cf84 100644 --- a/src/NadekoBot/Modules/Xp/Xp.cs +++ b/src/NadekoBot/Modules/Xp/Xp.cs @@ -51,7 +51,7 @@ public partial class Xp : NadekoModule { page--; - if (page < 0 || page > 100) + if (page is < 0 or > 100) return Task.CompletedTask; var allRewards = _service.GetRoleRewards(ctx.Guild.Id) diff --git a/src/NadekoBot/NadekoBot.csproj b/src/NadekoBot/NadekoBot.csproj index cda9b0080..0bbf74f7c 100644 --- a/src/NadekoBot/NadekoBot.csproj +++ b/src/NadekoBot/NadekoBot.csproj @@ -82,7 +82,7 @@ - 3.0.0 + 4.0.0 $(VersionPrefix).$(VersionSuffix) $(VersionPrefix) diff --git a/src/NadekoBot/Services/CommandHandler.cs b/src/NadekoBot/Services/CommandHandler.cs index f05ccd696..912937e27 100644 --- a/src/NadekoBot/Services/CommandHandler.cs +++ b/src/NadekoBot/Services/CommandHandler.cs @@ -1,5 +1,4 @@ -using NadekoBot.Common.Collections; -using System.Collections.Immutable; +using System.Collections.Immutable; using NadekoBot.Common.Configs; using NadekoBot.Db; using Discord.Interactions; @@ -267,7 +266,7 @@ public class CommandHandler : INService } public Task<(bool Success, string Error, CommandInfo Info)> ExecuteCommandAsync(CommandContext context, string input, int argPos, IServiceProvider serviceProvider, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception) - => ExecuteCommand(context, input.Substring(argPos), serviceProvider, multiMatchHandling); + => ExecuteCommand(context, input[argPos..], serviceProvider, multiMatchHandling); public async Task<(bool Success, string Error, CommandInfo Info)> ExecuteCommand(CommandContext context, string input, IServiceProvider services, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception) diff --git a/src/NadekoBot/Services/Common/GreetGrouper.cs b/src/NadekoBot/Services/Common/GreetGrouper.cs index 18ab816a4..d0728fccd 100644 --- a/src/NadekoBot/Services/Common/GreetGrouper.cs +++ b/src/NadekoBot/Services/Common/GreetGrouper.cs @@ -6,9 +6,7 @@ public class GreetGrouper private readonly object locker = new(); public GreetGrouper() - { - group = new(); - } + => group = new(); /// diff --git a/src/NadekoBot/Services/GreetSettingsService.cs b/src/NadekoBot/Services/GreetSettingsService.cs index 48eb70b8c..796bbc24e 100644 --- a/src/NadekoBot/Services/GreetSettingsService.cs +++ b/src/NadekoBot/Services/GreetSettingsService.cs @@ -27,9 +27,7 @@ public class GreetSettingsService : INService _bss = bss; _eb = eb; - GuildConfigsCache = new( - bot.AllGuildConfigs - .ToDictionary(g => g.GuildId, GreetSettings.Create)); + GuildConfigsCache = new(bot.AllGuildConfigs.ToDictionary(g => g.GuildId, GreetSettings.Create)); _client.UserJoined += UserJoined; _client.UserLeft += UserLeft; @@ -326,10 +324,8 @@ public class GreetSettingsService : INService public async Task SetSettings(ulong guildId, GreetSettings settings) { - if (settings.AutoDeleteByeMessagesTimer > 600 || - settings.AutoDeleteByeMessagesTimer < 0 || - settings.AutoDeleteGreetMessagesTimer > 600 || - settings.AutoDeleteGreetMessagesTimer < 0) + if (settings.AutoDeleteByeMessagesTimer is > 600 or < 0 || + settings.AutoDeleteGreetMessagesTimer is > 600 or < 0) { return false; } @@ -510,7 +506,7 @@ public class GreetSettingsService : INService public async Task SetByeDel(ulong guildId, int timer) { - if (timer < 0 || timer > 600) + if (timer is < 0 or > 600) return; await using var uow = _db.GetDbContext(); @@ -525,7 +521,7 @@ public class GreetSettingsService : INService public async Task SetGreetDel(ulong id, int timer) { - if (timer < 0 || timer > 600) + if (timer is < 0 or > 600) return; await using var uow = _db.GetDbContext(); @@ -555,7 +551,7 @@ public class GreetSettingsService : INService public async Task SetBoostDel(ulong guildId, int timer) { - if (timer < 0 || timer > 600) + if (timer is < 0 or > 600) throw new ArgumentOutOfRangeException(nameof(timer)); await using var uow = _db.GetDbContext(); diff --git a/src/NadekoBot/Services/IEmbedBuilderService.cs b/src/NadekoBot/Services/IEmbedBuilderService.cs index 37a6ea021..9b3102575 100644 --- a/src/NadekoBot/Services/IEmbedBuilderService.cs +++ b/src/NadekoBot/Services/IEmbedBuilderService.cs @@ -13,10 +13,8 @@ public class EmbedBuilderService : IEmbedBuilderService, INService private readonly BotConfigService _botConfigService; public EmbedBuilderService(BotConfigService botConfigService) - { - _botConfigService = botConfigService; - } - + => _botConfigService = botConfigService; + public IEmbedBuilder Create(ICommandContext ctx = null) => new DiscordEmbedBuilderWrapper(_botConfigService.Data); diff --git a/src/NadekoBot/Services/Impl/BehaviorExecutor.cs b/src/NadekoBot/Services/Impl/BehaviorExecutor.cs index 575b24113..dfaa6bbf2 100644 --- a/src/NadekoBot/Services/Impl/BehaviorExecutor.cs +++ b/src/NadekoBot/Services/Impl/BehaviorExecutor.cs @@ -12,9 +12,7 @@ public sealed class BehaviorExecutor : IBehaviourExecutor, INService private IEnumerable _transformers; public BehaviorExecutor(IServiceProvider services) - { - _services = services; - } + => _services = services; public void Initialize() { diff --git a/src/NadekoBot/Services/Impl/CurrencyService.cs b/src/NadekoBot/Services/Impl/CurrencyService.cs index 633ac818f..1616ca3cc 100644 --- a/src/NadekoBot/Services/Impl/CurrencyService.cs +++ b/src/NadekoBot/Services/Impl/CurrencyService.cs @@ -60,9 +60,7 @@ public class CurrencyService : ICurrencyService, INService } public Task AddAsync(ulong userId, string reason, long amount, bool gamble = false) - { - return InternalAddAsync(userId, null, null, null, reason, amount, gamble); - } + => InternalAddAsync(userId, null, null, null, reason, amount, gamble); public async Task AddAsync(IUser user, string reason, long amount, bool sendMessage = false, bool gamble = false) { @@ -141,12 +139,8 @@ public class CurrencyService : ICurrencyService, INService } public Task RemoveAsync(ulong userId, string reason, long amount, bool gamble = false) - { - return InternalRemoveAsync(userId, null, null, null, reason, amount, gamble); - } + => InternalRemoveAsync(userId, null, null, null, reason, amount, gamble); public Task RemoveAsync(IUser user, string reason, long amount, bool sendMessage = false, bool gamble = false) - { - return InternalRemoveAsync(user.Id, user.Username, user.Discriminator, user.AvatarId, reason, amount, gamble); - } + => InternalRemoveAsync(user.Id, user.Username, user.Discriminator, user.AvatarId, reason, amount, gamble); } \ No newline at end of file diff --git a/src/NadekoBot/Services/Impl/Localization.cs b/src/NadekoBot/Services/Impl/Localization.cs index bacd59668..834dacd63 100644 --- a/src/NadekoBot/Services/Impl/Localization.cs +++ b/src/NadekoBot/Services/Impl/Localization.cs @@ -74,12 +74,10 @@ public class Localization : ILocalization, INService } public void SetDefaultCulture(CultureInfo ci) - { - _bss.ModifyConfig(bs => + => _bss.ModifyConfig(bs => { bs.DefaultLocale = ci; }); - } public void ResetDefaultCulture() => SetDefaultCulture(CultureInfo.CurrentCulture); diff --git a/src/NadekoBot/Services/Impl/RedisImagesCache.cs b/src/NadekoBot/Services/Impl/RedisImagesCache.cs index 1486331fb..8730f1300 100644 --- a/src/NadekoBot/Services/Impl/RedisImagesCache.cs +++ b/src/NadekoBot/Services/Impl/RedisImagesCache.cs @@ -69,11 +69,8 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor => GetByteData(ImageKeys.RipOverlay); public byte[] GetCard(string key) - { // since cards are always local for now, don't cache them - return File.ReadAllBytes(Path.Join(_cardsPath, key + ".jpg")); - - } + => File.ReadAllBytes(Path.Join(_cardsPath, key + ".jpg")); public async Task OnReadyAsync() { diff --git a/src/NadekoBot/Services/Impl/RedisLocalDataCache.cs b/src/NadekoBot/Services/Impl/RedisLocalDataCache.cs index 6f6934b6f..a2564648b 100644 --- a/src/NadekoBot/Services/Impl/RedisLocalDataCache.cs +++ b/src/NadekoBot/Services/Impl/RedisLocalDataCache.cs @@ -82,12 +82,8 @@ public class RedisLocalDataCache : ILocalDataCache } private T Get(string key) where T : class - { - return JsonConvert.DeserializeObject(_db.StringGet($"{_creds.RedisKey()}_localdata_{key}")); - } + => JsonConvert.DeserializeObject(_db.StringGet($"{_creds.RedisKey()}_localdata_{key}")); private void Set(string key, object obj) - { - _db.StringSet($"{_creds.RedisKey()}_localdata_{key}", JsonConvert.SerializeObject(obj)); - } + => _db.StringSet($"{_creds.RedisKey()}_localdata_{key}", JsonConvert.SerializeObject(obj)); } \ No newline at end of file diff --git a/src/NadekoBot/Services/Impl/RemoteGrpcCoordinator.cs b/src/NadekoBot/Services/Impl/RemoteGrpcCoordinator.cs index 4e8f41d42..8e4889028 100644 --- a/src/NadekoBot/Services/Impl/RemoteGrpcCoordinator.cs +++ b/src/NadekoBot/Services/Impl/RemoteGrpcCoordinator.cs @@ -31,12 +31,10 @@ public class RemoteGrpcCoordinator : ICoordinator, IReadyExecutor } public void Die(bool graceful) - { - _coordClient.Die(new() + => _coordClient.Die(new() { Graceful = graceful }); - } public bool RestartShard(int shardId) { @@ -71,9 +69,7 @@ public class RemoteGrpcCoordinator : ICoordinator, IReadyExecutor } public async Task Reload() - { - await _coordClient.ReloadAsync(new()); - } + => await _coordClient.ReloadAsync(new()); public Task OnReadyAsync() { diff --git a/src/NadekoBot/Services/Impl/SingleProcessCoordinator.cs b/src/NadekoBot/Services/Impl/SingleProcessCoordinator.cs index 4b7e3c878..e74c9c2bf 100644 --- a/src/NadekoBot/Services/Impl/SingleProcessCoordinator.cs +++ b/src/NadekoBot/Services/Impl/SingleProcessCoordinator.cs @@ -31,18 +31,13 @@ public class SingleProcessCoordinator : ICoordinator } public void Die(bool graceful = false) - { - Environment.Exit(5); - } + => Environment.Exit(5); public bool RestartShard(int shardId) - { - return RestartBot(); - } + => RestartBot(); public IList GetAllShardStatuses() - { - return new[] + => new[] { new ShardStatus() { @@ -52,15 +47,10 @@ public class SingleProcessCoordinator : ICoordinator ShardId = _client.ShardId } }; - } public int GetGuildCount() - { - return _client.Guilds.Count; - } + => _client.Guilds.Count; public Task Reload() - { - return Task.CompletedTask; - } + => Task.CompletedTask; } \ No newline at end of file diff --git a/src/NadekoBot/Services/Impl/SoundCloudApiService.cs b/src/NadekoBot/Services/Impl/SoundCloudApiService.cs index 723a6bd7a..efd0fd26e 100644 --- a/src/NadekoBot/Services/Impl/SoundCloudApiService.cs +++ b/src/NadekoBot/Services/Impl/SoundCloudApiService.cs @@ -7,9 +7,7 @@ public class SoundCloudApiService : INService private readonly IHttpClientFactory _httpFactory; public SoundCloudApiService(IHttpClientFactory factory) - { - _httpFactory = factory; - } + => _httpFactory = factory; public async Task ResolveVideoAsync(string url) { diff --git a/src/NadekoBot/Services/Impl/StartingGuildsListService.cs b/src/NadekoBot/Services/Impl/StartingGuildsListService.cs index da2cebd4c..048d1ce79 100644 --- a/src/NadekoBot/Services/Impl/StartingGuildsListService.cs +++ b/src/NadekoBot/Services/Impl/StartingGuildsListService.cs @@ -8,9 +8,7 @@ public class StartingGuildsService : IEnumerable, INService private readonly ImmutableList _guilds; public StartingGuildsService(DiscordSocketClient client) - { - this._guilds = client.Guilds.Select(x => x.Id).ToImmutableList(); - } + => this._guilds = client.Guilds.Select(x => x.Id).ToImmutableList(); public IEnumerator GetEnumerator() => _guilds.GetEnumerator(); diff --git a/src/NadekoBot/Services/Impl/YtdlOperation.cs b/src/NadekoBot/Services/Impl/YtdlOperation.cs index 94a3f6588..d392d3e5a 100644 --- a/src/NadekoBot/Services/Impl/YtdlOperation.cs +++ b/src/NadekoBot/Services/Impl/YtdlOperation.cs @@ -9,9 +9,7 @@ public class YtdlOperation private readonly string _baseArgString; public YtdlOperation(string baseArgString) - { - _baseArgString = baseArgString; - } + => _baseArgString = baseArgString; private Process CreateProcess(string[] args) { diff --git a/src/NadekoBot/Services/Settings/ConfigServiceBase.cs b/src/NadekoBot/Services/Settings/ConfigServiceBase.cs index 0dd4c035a..600d9a2e3 100644 --- a/src/NadekoBot/Services/Settings/ConfigServiceBase.cs +++ b/src/NadekoBot/Services/Settings/ConfigServiceBase.cs @@ -44,10 +44,8 @@ public abstract class ConfigServiceBase : IConfigService } private void PublishChange() - { - _pubSub.Pub(_changeKey, _data); - } - + => _pubSub.Pub(_changeKey, _data); + private ValueTask OnChangePublished(TSettings newData) { _data = newData; diff --git a/src/NadekoBot/Services/StandardConversions.cs b/src/NadekoBot/Services/StandardConversions.cs index c1f4d9514..e573e3f2e 100644 --- a/src/NadekoBot/Services/StandardConversions.cs +++ b/src/NadekoBot/Services/StandardConversions.cs @@ -3,7 +3,5 @@ public static class StandardConversions { public static double CelsiusToFahrenheit(double cel) - { - return (cel * 1.8f) + 32; - } + => (cel * 1.8f) + 32; } \ 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 f8b398aaf..2605767e6 100644 --- a/src/NadekoBot/Services/strings/impl/BotStrings.cs +++ b/src/NadekoBot/Services/strings/impl/BotStrings.cs @@ -90,9 +90,7 @@ public class BotStrings : IBotStrings } public void Reload() - { - _stringsProvider.Reload(); - } + => _stringsProvider.Reload(); } public class CommandStrings diff --git a/src/NadekoBot/_Extensions/ArrayExtensions.cs b/src/NadekoBot/_Extensions/ArrayExtensions.cs index 39aa0dd45..b6cc1f7f0 100644 --- a/src/NadekoBot/_Extensions/ArrayExtensions.cs +++ b/src/NadekoBot/_Extensions/ArrayExtensions.cs @@ -4,6 +4,9 @@ // and they get looped through constantly public static class ArrayExtensions { + private static int x = 0; + + /// /// Create a new array from the old array + new element at the end /// @@ -14,11 +17,16 @@ public static class ArrayExtensions public static T[] With(this T[] input, T added) { var newCrs = new T[input.Length + 1]; - Array.Copy(input, 0, newCrs, 0, input.Length); + Array.Copy(input, + 0, + newCrs, + 0, + input.Length + ); newCrs[input.Length] = added; return newCrs; } - + /// /// Creates a new array by applying the specified function to every element in the input array /// diff --git a/src/NadekoBot/_Extensions/EnumerableExtensions.cs b/src/NadekoBot/_Extensions/EnumerableExtensions.cs new file mode 100644 index 000000000..a6db53ef2 --- /dev/null +++ b/src/NadekoBot/_Extensions/EnumerableExtensions.cs @@ -0,0 +1,85 @@ +using System.Security.Cryptography; +using NadekoBot.Common.Collections; +using NadekoBot.Services.Database.Models; + +namespace NadekoBot.Extensions; + +public static class EnumerableExtensions +{ + /// + /// Concatenates the members of a collection, using the specified separator between each member. + /// + /// Collection to join + /// The character to use as a separator. separator is included in the returned string only if values has more than one element. + /// Optional transformation to apply to each element before concatenation. + /// The type of the members of values. + /// A string that consists of the members of values delimited by the separator character. -or- Empty if values has no elements. + public static string Join(this IEnumerable data, char separator, Func func = null) + => string.Join(separator, data.Select(func ?? (x => x?.ToString() ?? string.Empty))); + + /// + /// Concatenates the members of a collection, using the specified separator between each member. + /// + /// Collection to join + /// The string to use as a separator.separator is included in the returned string only if values has more than one element. + /// Optional transformation to apply to each element before concatenation. + /// The type of the members of values. + /// A string that consists of the members of values delimited by the separator character. -or- Empty if values has no elements. + public static string Join(this IEnumerable data, string separator, Func func = null) + => string.Join(separator, data.Select(func ?? (x => x?.ToString() ?? string.Empty))); + + /// + /// Randomize element order by performing the Fisher-Yates shuffle + /// + /// Item type + /// Items to shuffle + public static IReadOnlyList Shuffle(this IEnumerable items) + { + using var provider = RandomNumberGenerator.Create(); + var list = items.ToList(); + var n = list.Count; + while (n > 1) + { + var box = new byte[(n / Byte.MaxValue) + 1]; + int boxSum; + do + { + provider.GetBytes(box); + boxSum = box.Sum(b => b); + } while (!(boxSum < n * (Byte.MaxValue * box.Length / n))); + + var k = boxSum % n; + n--; + (list[k], list[n]) = (list[n], list[k]); + } + + return list; + } + + /// + /// Initializes a new instance of the class + /// that contains elements copied from the specified + /// has the default concurrency level, has the default initial capacity, + /// and uses the default comparer for the key type. + /// + /// The whose elements are copied to the new . + /// A new instance of the class + public static ConcurrentDictionary ToConcurrent( + this IEnumerable> dict) + => new(dict); + + public static IndexedCollection ToIndexed(this IEnumerable enumerable) where T : class, IIndexed + => new(enumerable); + + // todo use this extension instead of Task.WhenAll + + /// + /// Creates a task that will complete when all of the objects in an enumerable + /// collection have completed + /// + /// The tasks to wait on for completion. + /// The type of the completed task. + /// A task that represents the completion of all of the supplied tasks. + public static Task WhenAll(this IEnumerable> tasks) + => Task.WhenAll(tasks); +} \ No newline at end of file diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index 4cdab1d67..484a0ef83 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -1,4 +1,4 @@ -using NadekoBot.Common.Collections; +using Humanizer.Localisation; using NadekoBot.Modules.Administration.Services; using SixLabors.Fonts; using SixLabors.ImageSharp; @@ -10,32 +10,34 @@ using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using System.Globalization; using System.Net.Http.Headers; -using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using Color = Discord.Color; using JsonSerializer = System.Text.Json.JsonSerializer; +// todo imagesharp extensions namespace NadekoBot.Extensions; public static class Extensions { - public static Regex UrlRegex = new(@"^(https?|ftp)://(?[^\s/$.?#].[^\s]*)$", RegexOptions.Compiled); + private static readonly Regex _urlRegex = + new(@"^(https?|ftp)://(?[^\s/$.?#].[^\s]*)$", RegexOptions.Compiled); - public static Task EditAsync(this IUserMessage msg, SmartText text) => text switch { SmartEmbedText set => msg.ModifyAsync(x => - { - x.Embed = set.GetEmbed().Build(); - x.Content = set.PlainText?.SanitizeMentions() ?? ""; - }), + { + x.Embed = set.GetEmbed().Build(); + x.Content = set.PlainText?.SanitizeMentions() ?? ""; + } + ), SmartPlainText spt => msg.ModifyAsync(x => - { - x.Content = spt.Text.SanitizeMentions(); - x.Embed = null; - }), + { + x.Content = spt.Text.SanitizeMentions(); + x.Embed = null; + } + ), _ => throw new ArgumentOutOfRangeException(nameof(text)) }; @@ -43,34 +45,29 @@ public static class Extensions => client.Guilds.Select(x => x.Id).ToList(); /// - /// Generates a string in the format HHH:mm if timespan is <= 2m. + /// Generates a string in the format HHH:mm if timespan is >= 2m. /// Generates a string in the format 00:mm:ss if timespan is less than 2m. /// /// Timespan to convert to string /// Formatted duration string - public static string ToPrettyStringHM(this TimeSpan span) - { - if (span < TimeSpan.FromMinutes(2)) - return $"{span:mm}m {span:ss}s"; - return $"{(int) span.TotalHours:D2}h {span:mm}m"; - } + public static string ToPrettyStringHm(this TimeSpan span) + => span.Humanize(2, minUnit: TimeUnit.Second); public static bool TryGetUrlPath(this string input, out string path) { - var match = UrlRegex.Match(input); + var match = _urlRegex.Match(input); if (match.Success) { path = match.Groups["path"].Value; return true; } + path = string.Empty; return false; } public static IEmote ToIEmote(this string emojiStr) - => Emote.TryParse(emojiStr, out var maybeEmote) - ? maybeEmote - : new Emoji(emojiStr); + => Emote.TryParse(emojiStr, out var maybeEmote) ? maybeEmote : new Emoji(emojiStr); // https://github.com/SixLabors/Samples/blob/master/ImageSharp/AvatarWithRoundedCorner/Program.cs public static IImageProcessingContext ApplyRoundedCorners(this IImageProcessingContext ctx, float cornerRadius) @@ -79,22 +76,29 @@ public static class Extensions var corners = BuildCorners(size.Width, size.Height, cornerRadius); ctx.SetGraphicsOptions(new GraphicsOptions() - { - Antialias = true, - AlphaCompositionMode = PixelAlphaCompositionMode.DestOut // enforces that any part of this shape that has color is punched out of the background - }); + { + Antialias = true, + // enforces that any part of this shape that has color is punched out of the background + AlphaCompositionMode = PixelAlphaCompositionMode.DestOut + } + ); foreach (var c in corners) { ctx = ctx.Fill(SixLabors.ImageSharp.Color.Red, c); } + return ctx; } private static IPathCollection BuildCorners(int imageWidth, int imageHeight, float cornerRadius) { // first create a square - var rect = new RectangularPolygon(-0.5f, -0.5f, cornerRadius, cornerRadius); + var rect = new RectangularPolygon(-0.5f, + -0.5f, + cornerRadius, + cornerRadius + ); // then cut out of the square a circle so we are left with a corner var cornerTopLeft = rect.Clip(new EllipsePolygon(cornerRadius - 0.5f, cornerRadius - 0.5f, cornerRadius)); @@ -110,57 +114,43 @@ public static class Extensions var cornerBottomLeft = cornerTopLeft.RotateDegree(-90).Translate(0, bottomPos); var cornerBottomRight = cornerTopLeft.RotateDegree(180).Translate(rightPos, bottomPos); - return new PathCollection(cornerTopLeft, cornerBottomLeft, cornerTopRight, cornerBottomRight); + return new PathCollection(cornerTopLeft, + cornerBottomLeft, + cornerTopRight, + cornerBottomRight + ); } /// /// First 10 characters of teh bot token. /// public static string RedisKey(this IBotCredentials bc) - { - return bc.Token.Substring(0, 10); - } - - public static async Task ReplaceAsync(this Regex regex, string input, Func> replacementFn) - { - var sb = new StringBuilder(); - var lastIndex = 0; - - foreach (Match match in regex.Matches(input)) - { - sb.Append(input, lastIndex, match.Index - lastIndex) - .Append(await replacementFn(match).ConfigureAwait(false)); - - lastIndex = match.Index + match.Length; - } - - sb.Append(input, lastIndex, input.Length - lastIndex); - return sb.ToString(); - } - - public static void ThrowIfNull(this T o, string name) where T : class - { - if (o is null) - throw new ArgumentNullException(nameof(name)); - } + => bc.Token[..10]; public static bool IsAuthor(this IMessage msg, IDiscordClient client) => msg.Author?.Id == client.CurrentUser.Id; - public static string RealSummary(this CommandInfo cmd, IBotStrings strings, ulong? guildId, string prefix) + public static string RealSummary( + this CommandInfo cmd, + IBotStrings strings, + ulong? guildId, + string prefix) => string.Format(strings.GetCommandStrings(cmd.Name, guildId).Desc, prefix); - public static string[] RealRemarksArr(this CommandInfo cmd, IBotStrings strings, ulong? guildId, string prefix) + public static string[] RealRemarksArr( + this CommandInfo cmd, + IBotStrings strings, + ulong? guildId, + string prefix) => Array.ConvertAll(strings.GetCommandStrings(cmd.MethodName(), guildId).Args, - arg => GetFullUsage(cmd.Name, arg, prefix)); + arg => GetFullUsage(cmd.Name, arg, prefix) + ); - public static string MethodName(this CommandInfo cmd) - => ((NadekoCommandAttribute) cmd.Attributes.FirstOrDefault(x => x is NadekoCommandAttribute))?.MethodName - ?? cmd.Name; - // public static string RealRemarks(this CommandInfo cmd, IBotStrings strings, string prefix) - // => string.Join('\n', cmd.RealRemarksArr(strings, prefix)); + private static string MethodName(this CommandInfo cmd) + => ((NadekoCommandAttribute)cmd.Attributes.FirstOrDefault(x => x is NadekoCommandAttribute))?.MethodName ?? + cmd.Name; - public static string GetFullUsage(string commandName, string args, string prefix) + private static string GetFullUsage(string commandName, string args, string prefix) => $"{prefix}{commandName} {string.Format(args, prefix)}"; public static IEmbedBuilder AddPaginatedFooter(this IEmbedBuilder embed, int curPage, int? lastPage) @@ -171,25 +161,36 @@ public static class Extensions return embed.WithFooter(curPage.ToString()); } - public static Color ToDiscordColor(this Rgba32 color) => new(color.R, color.G, color.B); - - public static IEmbedBuilder WithOkColor(this IEmbedBuilder eb) => - eb.WithColor(EmbedColor.Ok); + public static Color ToDiscordColor(this Rgba32 color) + => new(color.R, color.G, color.B); - public static IEmbedBuilder WithPendingColor(this IEmbedBuilder eb) => - eb.WithColor(EmbedColor.Pending); - - public static IEmbedBuilder WithErrorColor(this IEmbedBuilder eb) => - eb.WithColor(EmbedColor.Error); + public static IEmbedBuilder WithOkColor(this IEmbedBuilder eb) + => eb.WithColor(EmbedColor.Ok); - public static ReactionEventWrapper OnReaction(this IUserMessage msg, DiscordSocketClient client, Func reactionAdded, Func reactionRemoved = null) + public static IEmbedBuilder WithPendingColor(this IEmbedBuilder eb) + => eb.WithColor(EmbedColor.Pending); + + public static IEmbedBuilder WithErrorColor(this IEmbedBuilder eb) + => eb.WithColor(EmbedColor.Error); + + public static ReactionEventWrapper OnReaction( + this IUserMessage msg, + DiscordSocketClient client, + Func reactionAdded, + Func reactionRemoved = null) { if (reactionRemoved is null) reactionRemoved = _ => Task.CompletedTask; var wrap = new ReactionEventWrapper(client, msg); - wrap.OnReactionAdded += r => { var _ = Task.Run(() => reactionAdded(r)); }; - wrap.OnReactionRemoved += r => { var _ = Task.Run(() => reactionRemoved(r)); }; + wrap.OnReactionAdded += r => + { + var _ = Task.Run(() => reactionAdded(r)); + }; + wrap.OnReactionRemoved += r => + { + var _ = Task.Run(() => reactionRemoved(r)); + }; return wrap; } @@ -203,24 +204,28 @@ public static class Extensions { dict.Clear(); dict.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); - dict.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"); + dict.Add("User-Agent", + "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1" + ); } public static IMessage DeleteAfter(this IUserMessage msg, int seconds, ILogCommandService logService = null) { if (msg is null) return null; - + Task.Run(async () => - { - await Task.Delay(seconds * 1000).ConfigureAwait(false); - if(logService != null) { - logService.AddDeleteIgnore(msg.Id); + await Task.Delay(seconds * 1000).ConfigureAwait(false); + if (logService != null) + { + logService.AddDeleteIgnore(msg.Id); + } + + try { await msg.DeleteAsync().ConfigureAwait(false); } + catch { } } - try { await msg.DeleteAsync().ConfigureAwait(false); } - catch { } - }); + ); return msg; } @@ -230,33 +235,18 @@ public static class Extensions { module = module.Parent; } + return module; } - public static void AddRange(this HashSet target, IEnumerable elements) where T : class + public static async Task> GetMembersAsync(this IRole role) { - foreach (var item in elements) - { - target.Add(item); - } + var users = await role.Guild.GetUsersAsync(CacheMode.CacheOnly).ConfigureAwait(false); + return users.Where(u => u.RoleIds.Contains(role.Id)); } - public static void AddRange(this ConcurrentHashSet target, IEnumerable elements) where T : class - { - foreach (var item in elements) - { - target.Add(item); - } - } - - public static double UnixTimestamp(this DateTime dt) - => dt.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds; - - public static async Task> GetMembersAsync(this IRole role) => - (await role.Guild.GetUsersAsync(CacheMode.CacheOnly).ConfigureAwait(false)).Where(u => u.RoleIds.Contains(role.Id)) ?? Enumerable.Empty(); - - public static string ToJson(this T any, JsonSerializerOptions options = null) => - JsonSerializer.Serialize(any, options); + public static string ToJson(this T any, JsonSerializerOptions options = null) + => JsonSerializer.Serialize(any, options); /// /// Adds fallback fonts to @@ -270,6 +260,7 @@ public static class Extensions { opts.FallbackFonts.Add(ff); } + return opts; } @@ -294,12 +285,11 @@ public static class Extensions } else { - img.SaveAsPng(imageStream, new() - { - ColorType = PngColorType.RgbWithAlpha, - CompressionLevel = PngCompressionLevel.BestCompression - }); + img.SaveAsPng(imageStream, + new() { ColorType = PngColorType.RgbWithAlpha, CompressionLevel = PngCompressionLevel.BestCompression } + ); } + imageStream.Position = 0; return imageStream; } @@ -311,27 +301,20 @@ public static class Extensions return ms; } - public static IEnumerable GetRoles(this IGuildUser user) => - user.RoleIds.Select(r => user.Guild.GetRole(r)).Where(r => r != null); + public static IEnumerable GetRoles(this IGuildUser user) + => user.RoleIds.Select(r => user.Guild.GetRole(r)).Where(r => r != null); - public static async Task SendMessageToOwnerAsync(this IGuild guild, string message) - { - var owner = await guild.GetOwnerAsync(); - - return await owner.SendMessageAsync(message); - } - - public static bool IsImage(this HttpResponseMessage msg) => IsImage(msg, out _); + public static bool IsImage(this HttpResponseMessage msg) + => IsImage(msg, out _); public static bool IsImage(this HttpResponseMessage msg, out string mimeType) { mimeType = msg.Content.Headers.ContentType?.MediaType; - if (mimeType == "image/png" - || mimeType == "image/jpeg" - || mimeType == "image/gif") + if (mimeType is "image/png" or "image/jpeg" or "image/gif") { return true; } + return false; } @@ -342,12 +325,12 @@ public static class Extensions return null; } - return msg.Content.Headers.ContentLength / 1.MB(); + return msg.Content.Headers.ContentLength.Value / 1.Mb(); } public static string GetText(this IBotStrings strings, in LocStr str, ulong? guildId = null) => strings.GetText(str.Key, guildId, str.Params); - + public static string GetText(this IBotStrings strings, in LocStr str, CultureInfo culture) => strings.GetText(str.Key, culture, str.Params); } \ No newline at end of file diff --git a/src/NadekoBot/_Extensions/IEnumerableExtensions.cs b/src/NadekoBot/_Extensions/IEnumerableExtensions.cs deleted file mode 100644 index 4759b9419..000000000 --- a/src/NadekoBot/_Extensions/IEnumerableExtensions.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.Security.Cryptography; -using NadekoBot.Common.Collections; -using NadekoBot.Services.Database.Models; - -namespace NadekoBot.Extensions; - -public static class IEnumerableExtensions -{ - public static string JoinWith(this IEnumerable data, char separator, Func func = null) - { - if (func is null) - func = x => x?.ToString() ?? string.Empty; - - return string.Join(separator, data.Select(func)); - } - - public static string JoinWith(this IEnumerable data, string separator, Func func = null) - { - func ??= x => x?.ToString() ?? string.Empty; - - return string.Join(separator, data.Select(func)); - } - - /// - /// Randomize element order by performing the Fisher-Yates shuffle - /// - /// Item type - /// Items to shuffle - public static IReadOnlyList Shuffle(this IEnumerable items) - { - using var provider = RandomNumberGenerator.Create(); - var list = items.ToList(); - var n = list.Count; - while (n > 1) - { - var box = new byte[(n / Byte.MaxValue) + 1]; - int boxSum; - do - { - provider.GetBytes(box); - boxSum = box.Sum(b => b); - } while (!(boxSum < n * (Byte.MaxValue * box.Length / n))); - - var k = boxSum % n; - n--; - var value = list[k]; - list[k] = list[n]; - list[n] = value; - } - - return list; - } - - public static IEnumerable ForEach(this IEnumerable elems, Action exec) - { - var realElems = elems.ToList(); - foreach (var elem in realElems) - { - exec(elem); - } - - return realElems; - } - - public static ConcurrentDictionary ToConcurrent( - this IEnumerable> dict) => new(dict); - - public static IndexedCollection ToIndexed(this IEnumerable enumerable) where T : class, IIndexed => - new(enumerable); - - public static Task WhenAll(this IEnumerable> items) - => Task.WhenAll(items); -} \ No newline at end of file diff --git a/src/NadekoBot/_Extensions/IMessageChannelExtensions.cs b/src/NadekoBot/_Extensions/IMessageChannelExtensions.cs index dc1468705..1d9eb187c 100644 --- a/src/NadekoBot/_Extensions/IMessageChannelExtensions.cs +++ b/src/NadekoBot/_Extensions/IMessageChannelExtensions.cs @@ -1,20 +1,21 @@ namespace NadekoBot.Extensions; -public static class IMessageChannelExtensions +public static class MessageChannelExtensions { public static Task EmbedAsync(this IMessageChannel ch, IEmbedBuilder embed, string msg = "") - => ch.SendMessageAsync(msg, embed: embed.Build(), - options: new() { RetryMode = RetryMode.AlwaysRetry }); - - public static Task SendAsync(this IMessageChannel channel, string plainText, Embed embed, bool sanitizeAll = false) + => ch.SendMessageAsync(msg, embed: embed.Build(), options: new() { RetryMode = RetryMode.AlwaysRetry }); + + public static Task SendAsync( + this IMessageChannel channel, + string plainText, + Embed embed, + bool sanitizeAll = false) { - plainText = sanitizeAll - ? plainText?.SanitizeAllMentions() ?? "" - : plainText?.SanitizeMentions() ?? ""; + plainText = sanitizeAll ? plainText?.SanitizeAllMentions() ?? "" : plainText?.SanitizeMentions() ?? ""; return channel.SendMessageAsync(plainText, embed: embed); } - + public static Task SendAsync(this IMessageChannel channel, SmartText text, bool sanitizeAll = false) => text switch { @@ -26,89 +27,115 @@ public static class IMessageChannelExtensions // this is a huge problem, because now i don't have // access to embed builder service // as this is an extension of the message channel - public static Task SendErrorAsync(this IMessageChannel ch, IEmbedBuilderService eb, string title, string error, string url = null, string footer = null) + public static Task SendErrorAsync( + this IMessageChannel ch, + IEmbedBuilderService eb, + string title, + string error, + string url = null, + string footer = null) { - var embed = eb.Create() - .WithErrorColor() - .WithDescription(error) - .WithTitle(title); + var embed = eb.Create().WithErrorColor().WithDescription(error).WithTitle(title); - if (url != null && Uri.IsWellFormedUriString(url, UriKind.Absolute)) + if (url != null && + Uri.IsWellFormedUriString(url, UriKind.Absolute)) embed.WithUrl(url); - + if (!string.IsNullOrWhiteSpace(footer)) embed.WithFooter(footer); - + return ch.SendMessageAsync("", embed: embed.Build()); } public static Task SendErrorAsync(this IMessageChannel ch, IEmbedBuilderService eb, string error) - => ch.SendMessageAsync("", - embed: eb.Create() - .WithErrorColor() - .WithDescription(error) - .Build()); + => ch.SendMessageAsync("", embed: eb.Create().WithErrorColor().WithDescription(error).Build()); public static Task SendPendingAsync(this IMessageChannel ch, IEmbedBuilderService eb, string message) - => ch.SendMessageAsync("", embed: eb.Create() - .WithPendingColor() - .WithDescription(message) - .Build()); - - public static Task SendConfirmAsync(this IMessageChannel ch, IEmbedBuilderService eb, string title, string text, string url = null, string footer = null) + => ch.SendMessageAsync("", embed: eb.Create().WithPendingColor().WithDescription(message).Build()); + + public static Task SendConfirmAsync( + this IMessageChannel ch, + IEmbedBuilderService eb, + string title, + string text, + string url = null, + string footer = null) { - var embed = eb.Create().WithOkColor().WithDescription(text) - .WithTitle(title); - - if (url != null && Uri.IsWellFormedUriString(url, UriKind.Absolute)) + var embed = eb.Create().WithOkColor().WithDescription(text).WithTitle(title); + + if (url != null && + Uri.IsWellFormedUriString(url, UriKind.Absolute)) embed.WithUrl(url); - + if (!string.IsNullOrWhiteSpace(footer)) embed.WithFooter(footer); - + return ch.SendMessageAsync("", embed: embed.Build()); } public static Task SendConfirmAsync(this IMessageChannel ch, IEmbedBuilderService eb, string text) - => ch.SendMessageAsync("", embed: eb.Create() - .WithOkColor() - .WithDescription(text) - .Build()); + => ch.SendMessageAsync("", embed: eb.Create().WithOkColor().WithDescription(text).Build()); - public static Task SendTableAsync(this IMessageChannel ch, string seed, IEnumerable items, Func howToPrint, int columns = 3) - { - return ch.SendMessageAsync($@"{seed}```css + public static Task SendTableAsync( + this IMessageChannel ch, + string seed, + IEnumerable items, + Func howToPrint, + int columns = 3) + => ch.SendMessageAsync($@"{seed}```css {string.Join("\n", items.Chunk(columns) - .Select(ig => string.Concat(ig.Select(el => howToPrint(el)))))} -```"); - } + .Select(ig => string.Concat(ig.Select(howToPrint))))} +```" + ); - public static Task SendTableAsync(this IMessageChannel ch, IEnumerable items, Func howToPrint, int columns = 3) => - ch.SendTableAsync("", items, howToPrint, columns); - - private static readonly IEmote arrow_left = new Emoji("⬅"); - private static readonly IEmote arrow_right = new Emoji("➡"); + public static Task SendTableAsync( + this IMessageChannel ch, + IEnumerable items, + Func howToPrint, + int columns = 3) + => ch.SendTableAsync("", + items, + howToPrint, + columns + ); - public static Task SendPaginatedConfirmAsync(this ICommandContext ctx, - int currentPage, Func pageFunc, int totalElements, - int itemsPerPage, bool addPaginatedFooter = true) + private static readonly IEmote _arrowLeft = new Emoji("⬅"); + private static readonly IEmote _arrowRight = new Emoji("➡"); + + public static Task SendPaginatedConfirmAsync( + this ICommandContext ctx, + int currentPage, + Func pageFunc, + int totalElements, + int itemsPerPage, + bool addPaginatedFooter = true) => ctx.SendPaginatedConfirmAsync(currentPage, - x => Task.FromResult(pageFunc(x)), totalElements, itemsPerPage, addPaginatedFooter); + x => Task.FromResult(pageFunc(x)), + totalElements, + itemsPerPage, + addPaginatedFooter + ); + /// /// danny kamisama /// - public static async Task SendPaginatedConfirmAsync(this ICommandContext ctx, int currentPage, - Func> pageFunc, int totalElements, int itemsPerPage, bool addPaginatedFooter = true) + public static async Task SendPaginatedConfirmAsync( + this ICommandContext ctx, + int currentPage, + Func> pageFunc, + int totalElements, + int itemsPerPage, + bool addPaginatedFooter = true) { var embed = await pageFunc(currentPage).ConfigureAwait(false); var lastPage = (totalElements - 1) / itemsPerPage; - + var canPaginate = true; - var sg = ctx.Guild as SocketGuild; - if (sg is not null && !sg.CurrentUser.GetPermissions((IGuildChannel) ctx.Channel).AddReactions) + if (ctx.Guild is SocketGuild sg && + !sg.CurrentUser.GetPermissions((IGuildChannel)ctx.Channel).AddReactions) canPaginate = false; - + if (!canPaginate) embed.WithFooter("⚠️ AddReaction permission required for pagination."); else if (addPaginatedFooter) @@ -116,17 +143,18 @@ public static class IMessageChannelExtensions var msg = await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false); - if (lastPage == 0 || !canPaginate) + if (lastPage == 0 || + !canPaginate) return; - await msg.AddReactionAsync(arrow_left).ConfigureAwait(false); - await msg.AddReactionAsync(arrow_right).ConfigureAwait(false); + await msg.AddReactionAsync(_arrowLeft).ConfigureAwait(false); + await msg.AddReactionAsync(_arrowRight).ConfigureAwait(false); await Task.Delay(2000).ConfigureAwait(false); var lastPageChange = DateTime.MinValue; - async Task changePage(SocketReaction r) + async Task ChangePage(SocketReaction r) { try { @@ -134,7 +162,7 @@ public static class IMessageChannelExtensions return; if (DateTime.UtcNow - lastPageChange < TimeSpan.FromSeconds(1)) return; - if (r.Emote.Name == arrow_left.Name) + if (r.Emote.Name == _arrowLeft.Name) { if (currentPage == 0) return; @@ -144,7 +172,7 @@ public static class IMessageChannelExtensions toSend.AddPaginatedFooter(currentPage, lastPage); await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false); } - else if (r.Emote.Name == arrow_right.Name) + else if (r.Emote.Name == _arrowRight.Name) { if (lastPage > currentPage) { @@ -162,21 +190,23 @@ public static class IMessageChannelExtensions } } - using (msg.OnReaction((DiscordSocketClient)ctx.Client, changePage, changePage)) + using (msg.OnReaction((DiscordSocketClient)ctx.Client, ChangePage, ChangePage)) { await Task.Delay(30000).ConfigureAwait(false); } try { - if(msg.Channel is ITextChannel && ((SocketGuild)ctx.Guild).CurrentUser.GuildPermissions.ManageMessages) + if (msg.Channel is ITextChannel && + ((SocketGuild)ctx.Guild).CurrentUser.GuildPermissions.ManageMessages) { await msg.RemoveAllReactionsAsync().ConfigureAwait(false); } else { await Task.WhenAll(msg.Reactions.Where(x => x.Value.IsMe) - .Select(x => msg.RemoveReactionAsync(x.Key, ctx.Client.CurrentUser))); + .Select(x => msg.RemoveReactionAsync(x.Key, ctx.Client.CurrentUser)) + ); } } catch @@ -187,10 +217,10 @@ public static class IMessageChannelExtensions public static Task OkAsync(this ICommandContext ctx) => ctx.Message.AddReactionAsync(new Emoji("✅")); - + public static Task ErrorAsync(this ICommandContext ctx) => ctx.Message.AddReactionAsync(new Emoji("❌")); - + public static Task WarningAsync(this ICommandContext ctx) => ctx.Message.AddReactionAsync(new Emoji("⚠️")); } \ No newline at end of file diff --git a/src/NadekoBot/_Extensions/IUserExtensions.cs b/src/NadekoBot/_Extensions/IUserExtensions.cs deleted file mode 100644 index fc065e77d..000000000 --- a/src/NadekoBot/_Extensions/IUserExtensions.cs +++ /dev/null @@ -1,83 +0,0 @@ -using Discord; -using NadekoBot.Db.Models; - -namespace NadekoBot.Extensions; - -public static class IUserExtensions -{ - public static async Task EmbedAsync(this IUser user, IEmbedBuilder embed, string msg = "") - { - var ch = await user.CreateDMChannelAsync(); - return await ch.EmbedAsync(embed, msg); - } - - public static async Task SendAsync(this IUser user, string plainText, Embed embed, bool sanitizeAll = false) - { - var ch = await user.CreateDMChannelAsync(); - return await ch.SendAsync(plainText, embed, sanitizeAll); - } - - public static async Task SendAsync(this IUser user, SmartText text, bool sanitizeAll = false) - { - var ch = await user.CreateDMChannelAsync(); - return await ch.SendAsync(text, sanitizeAll); - } - - public static async Task SendConfirmAsync(this IUser user, IEmbedBuilderService eb, string text) - => await user.SendMessageAsync("", embed: eb.Create() - .WithOkColor() - .WithDescription(text) - .Build()); - - public static async Task SendConfirmAsync(this IUser user, IEmbedBuilderService eb, string title, string text, string url = null) - { - var embed = eb.Create().WithOkColor().WithDescription(text).WithTitle(title); - if (url != null && Uri.IsWellFormedUriString(url, UriKind.Absolute)) - embed.WithUrl(url); - - return await user.SendMessageAsync("", embed: embed.Build()); - } - - public static async Task SendErrorAsync(this IUser user, IEmbedBuilderService eb, string title, string error, string url = null) - { - var embed = eb.Create().WithErrorColor().WithDescription(error).WithTitle(title); - if (url != null && Uri.IsWellFormedUriString(url, UriKind.Absolute)) - embed.WithUrl(url); - - return await user.SendMessageAsync("", embed: embed.Build()).ConfigureAwait(false); - } - - public static async Task SendErrorAsync(this IUser user, IEmbedBuilderService eb, string error) - => await user - .SendMessageAsync("", embed: eb.Create() - .WithErrorColor() - .WithDescription(error) - .Build()); - - public static async Task SendFileAsync(this IUser user, string filePath, string caption = null, string text = null, bool isTTS = false) - { - await using var file = File.Open(filePath, FileMode.Open); - return await UserExtensions.SendFileAsync(user, file, caption ?? "x", text, isTTS).ConfigureAwait(false); - } - - public static async Task SendFileAsync(this IUser user, Stream fileStream, string fileName, string caption = null, bool isTTS = false) => - await UserExtensions.SendFileAsync(user, fileStream, fileName, caption, isTTS).ConfigureAwait(false); - - // This method is used by everything that fetches the avatar from a user - public static Uri RealAvatarUrl(this IUser usr, ushort size = 128) - { - return usr.AvatarId is null - ? new(usr.GetDefaultAvatarUrl()) - : new Uri(usr.GetAvatarUrl(ImageFormat.Auto, size)); - } - - // This method is only used for the xp card - public static Uri RealAvatarUrl(this DiscordUser usr) - { - return usr.AvatarId is null - ? null - : new Uri(usr.AvatarId.StartsWith("a_", StringComparison.InvariantCulture) - ? $"{DiscordConfig.CDNUrl}avatars/{usr.UserId}/{usr.AvatarId}.gif" - : $"{DiscordConfig.CDNUrl}avatars/{usr.UserId}/{usr.AvatarId}.png"); - } -} \ No newline at end of file diff --git a/src/NadekoBot/_Extensions/MusicExtensions.cs b/src/NadekoBot/_Extensions/MusicExtensions.cs deleted file mode 100644 index ad7a69701..000000000 --- a/src/NadekoBot/_Extensions/MusicExtensions.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace NadekoBot.Extensions; - -public static class MusicExtensions -{ - public static EmbedAuthorBuilder WithMusicIcon(this EmbedAuthorBuilder eab) => - eab.WithIconUrl("http://i.imgur.com/nhKS3PT.png"); -} \ No newline at end of file diff --git a/src/NadekoBot/_Extensions/NumberExtensions.cs b/src/NadekoBot/_Extensions/NumberExtensions.cs index 6f3bd9fd4..f15c2d210 100644 --- a/src/NadekoBot/_Extensions/NumberExtensions.cs +++ b/src/NadekoBot/_Extensions/NumberExtensions.cs @@ -2,26 +2,52 @@ public static class NumberExtensions { - public static int KiB(this int value) => value * 1024; - public static int KB(this int value) => value * 1000; + public static int KiB(this int value) + => value * 1024; - public static int MiB(this int value) => value.KiB() * 1024; - public static int MB(this int value) => value.KB() * 1000; + public static int Kb(this int value) + => value * 1000; - public static int GiB(this int value) => value.MiB() * 1024; - public static int GB(this int value) => value.MB() * 1000; + public static int MiB(this int value) + => value.KiB() * 1024; - public static ulong KiB(this ulong value) => value * 1024; - public static ulong KB(this ulong value) => value * 1000; + public static int Mb(this int value) + => value.Kb() * 1000; - public static ulong MiB(this ulong value) => value.KiB() * 1024; - public static ulong MB(this ulong value) => value.KB() * 1000; + public static int GiB(this int value) + => value.MiB() * 1024; - public static ulong GiB(this ulong value) => value.MiB() * 1024; - public static ulong GB(this ulong value) => value.MB() * 1000; + public static int Gb(this int value) + => value.Mb() * 1000; - public static bool IsInteger(this decimal number) => number == Math.Truncate(number); + public static ulong KiB(this ulong value) + => value * 1024; + + public static ulong Kb(this ulong value) + => value * 1000; + + public static ulong MiB(this ulong value) + => value.KiB() * 1024; + + public static ulong Mb(this ulong value) + => value.Kb() * 1000; + + public static ulong GiB(this ulong value) + => value.MiB() * 1024; + + public static ulong Gb(this ulong value) + => value.Mb() * 1000; + + public static bool IsInteger(this decimal number) + => number == Math.Truncate(number); public static DateTimeOffset ToUnixTimestamp(this double number) - => new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddSeconds(number); + => new DateTimeOffset(1970, + 1, + 1, + 0, + 0, + 0, + TimeSpan.Zero + ).AddSeconds(number); } \ No newline at end of file diff --git a/src/NadekoBot/_Extensions/ProcessExtensions.cs b/src/NadekoBot/_Extensions/ProcessExtensions.cs index 15ea6a829..86aba17ac 100644 --- a/src/NadekoBot/_Extensions/ProcessExtensions.cs +++ b/src/NadekoBot/_Extensions/ProcessExtensions.cs @@ -13,19 +13,17 @@ public static class ProcessExtensions private static readonly TimeSpan _defaultTimeout = TimeSpan.FromSeconds(10); public static void KillTree(this Process process) - { - process.KillTree(_defaultTimeout); - } + => process.KillTree(_defaultTimeout); public static void KillTree(this Process process, TimeSpan timeout) { if (_isWindows) { - RunProcessAndWaitForExit( - "taskkill", + RunProcessAndWaitForExit("taskkill", $"/T /F /PID {process.Id}", timeout, - out var stdout); + out _ + ); } else { @@ -35,19 +33,21 @@ public static class ProcessExtensions { KillProcessUnix(childId, timeout); } + KillProcessUnix(process.Id, timeout); } } private static void GetAllChildIdsUnix(int parentId, ISet children, TimeSpan timeout) { - var exitCode = RunProcessAndWaitForExit( - "pgrep", + var exitCode = RunProcessAndWaitForExit("pgrep", $"-P {parentId}", timeout, - out var stdout); + out var stdout + ); - if (exitCode == 0 && !string.IsNullOrEmpty(stdout)) + if (exitCode == 0 && + !string.IsNullOrEmpty(stdout)) { using var reader = new StringReader(stdout); while (true) @@ -69,27 +69,30 @@ public static class ProcessExtensions } private static void KillProcessUnix(int processId, TimeSpan timeout) - { - RunProcessAndWaitForExit( - "kill", + => RunProcessAndWaitForExit("kill", $"-TERM {processId}", timeout, - out var stdout); - } + out _ + ); - private static int RunProcessAndWaitForExit(string fileName, string arguments, TimeSpan timeout, out string stdout) + private static int RunProcessAndWaitForExit( + string fileName, + string arguments, + TimeSpan timeout, + out string stdout) { + stdout = null; + 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); - stdout = null; + if (process is null) + return -1; + if (process.WaitForExit((int)timeout.TotalMilliseconds)) { stdout = process.StandardOutput.ReadToEnd(); diff --git a/src/NadekoBot/_Extensions/Rgba32Extensions.cs b/src/NadekoBot/_Extensions/Rgba32Extensions.cs index 83d5e291a..0eb796d32 100644 --- a/src/NadekoBot/_Extensions/Rgba32Extensions.cs +++ b/src/NadekoBot/_Extensions/Rgba32Extensions.cs @@ -10,27 +10,26 @@ namespace NadekoBot.Extensions; public static class Rgba32Extensions { public static Image Merge(this IEnumerable> images) - { - return images.Merge(out _); - } + => images.Merge(out _); public static Image Merge(this IEnumerable> images, out IImageFormat format) { format = PngFormat.Instance; - void DrawFrame(Image[] imgArray, Image imgFrame, int frameNumber) + void DrawFrame(IList> imgArray, Image imgFrame, int frameNumber) { var xOffset = 0; - for (var i = 0; i < imgArray.Length; i++) + for (var i = 0; i < imgArray.Count; i++) { var frame = imgArray[i].Frames.CloneFrame(frameNumber % imgArray[i].Frames.Count); - imgFrame.Mutate(x => x.DrawImage(frame, new(xOffset, 0), new GraphicsOptions())); + var offset = xOffset; + imgFrame.Mutate(x => x.DrawImage(frame, new(offset, 0), new GraphicsOptions())); xOffset += imgArray[i].Bounds().Width; } } - var imgs = images.ToArray(); - var frames = images.Max(x => x.Frames.Count); + var imgs = images.ToList(); + var frames = imgs.Max(x => x.Frames.Count); var width = imgs.Sum(img => img.Width); var height = imgs.Max(img => img.Height); diff --git a/src/NadekoBot/_Extensions/StringExtensions.cs b/src/NadekoBot/_Extensions/StringExtensions.cs index 72fecad45..f23ba5922 100644 --- a/src/NadekoBot/_Extensions/StringExtensions.cs +++ b/src/NadekoBot/_Extensions/StringExtensions.cs @@ -13,24 +13,21 @@ public static class StringExtensions var padLeft = (spaces / 2) + str.Length; return str.PadLeft(padLeft).PadRight(length); } - + public static T MapJson(this string str) => JsonConvert.DeserializeObject(str); - private static readonly HashSet lettersAndDigits = new(Enumerable.Range(48, 10) + private static readonly HashSet _lettersAndDigits = new(Enumerable.Range(48, 10) .Concat(Enumerable.Range(65, 26)) .Concat(Enumerable.Range(97, 26)) - .Select(x => (char)x)); + .Select(x => (char)x) + ); - public static string StripHTML(this string input) - { - return Regex.Replace(input, "<.*?>", String.Empty); - } + public static string StripHtml(this string input) + => Regex.Replace(input, "<.*?>", String.Empty); public static string TrimTo(this string str, int maxLength, bool hideDots = false) - => hideDots - ? str?.Truncate(maxLength, string.Empty) - : str?.Truncate(maxLength); + => hideDots ? str?.Truncate(maxLength, string.Empty) : str?.Truncate(maxLength); public static string ToTitleCase(this string str) { @@ -38,12 +35,10 @@ public static class StringExtensions for (var i = 0; i < tokens.Length; i++) { var token = tokens[i]; - tokens[i] = token.Substring(0, 1).ToUpperInvariant() + token.Substring(1); + tokens[i] = token[..1].ToUpperInvariant() + token[1..]; } - return string.Join(" ", tokens) - .Replace(" Of ", " of ") - .Replace(" The ", " the "); + return string.Join(" ", tokens).Replace(" Of ", " of ").Replace(" The ", " the "); } //http://www.dotnetperls.com/levenshtein @@ -83,11 +78,10 @@ public static class StringExtensions var cost = t[j - 1] == s[i - 1] ? 0 : 1; // Step 6 - d[i, j] = Math.Min( - Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), - d[i - 1, j - 1] + cost); + d[i, j] = Math.Min(Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); } } + // Step 7 return d[n, m]; } @@ -102,11 +96,15 @@ public static class StringExtensions return ms; } - private static readonly Regex filterRegex = new(@"discord(?:\.gg|\.io|\.me|\.li|(?:app)?\.com\/invite)\/(\w+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); - public static bool IsDiscordInvite(this string str) - => filterRegex.IsMatch(str); + private static readonly Regex _filterRegex = new(@"discord(?:\.gg|\.io|\.me|\.li|(?:app)?\.com\/invite)\/(\w+)", + RegexOptions.Compiled | RegexOptions.IgnoreCase + ); - public static string Unmention(this string str) => str.Replace("@", "ම", StringComparison.InvariantCulture); + public static bool IsDiscordInvite(this string str) + => _filterRegex.IsMatch(str); + + public static string Unmention(this string str) + => str.Replace("@", "ම", StringComparison.InvariantCulture); public static string SanitizeMentions(this string str, bool sanitizeRoleMentions = false) { @@ -118,11 +116,11 @@ public static class StringExtensions return str; } - public static string SanitizeRoleMentions(this string str) => - str.Replace("<@&", "<ම&", StringComparison.InvariantCultureIgnoreCase); + public static string SanitizeRoleMentions(this string str) + => str.Replace("<@&", "<ම&", StringComparison.InvariantCultureIgnoreCase); - public static string SanitizeAllMentions(this string str) => - str.SanitizeMentions().SanitizeRoleMentions(); + public static string SanitizeAllMentions(this string str) + => str.SanitizeMentions().SanitizeRoleMentions(); public static string ToBase64(this string plainText) { @@ -130,23 +128,24 @@ public static class StringExtensions return Convert.ToBase64String(plainTextBytes); } - public static string GetInitials(this string txt, string glue = "") => - string.Join(glue, txt.Split(' ').Select(x => x.FirstOrDefault())); + public static string GetInitials(this string txt, string glue = "") + => string.Join(glue, txt.Split(' ').Select(x => x.FirstOrDefault())); - public static bool IsAlphaNumeric(this string txt) => - txt.All(c => lettersAndDigits.Contains(c)); + public static bool IsAlphaNumeric(this string txt) + => txt.All(c => _lettersAndDigits.Contains(c)); + + private static readonly Regex _codePointRegex = + new(@"(\\U(?[a-zA-Z0-9]{8})|\\u(?[a-zA-Z0-9]{4})|\\x(?[a-zA-Z0-9]{2}))", + RegexOptions.Compiled + ); - private static readonly Regex CodePointRegex - = new(@"(\\U(?[a-zA-Z0-9]{8})|\\u(?[a-zA-Z0-9]{4})|\\x(?[a-zA-Z0-9]{2}))", - RegexOptions.Compiled); - public static string UnescapeUnicodeCodePoints(this string input) - { - return CodePointRegex.Replace(input, me => - { - var str = me.Groups["code"].Value; - var newString = YamlHelper.UnescapeUnicodeCodePoint(str); - return newString; - }); - } + => _codePointRegex.Replace(input, + me => + { + var str = me.Groups["code"].Value; + var newString = YamlHelper.UnescapeUnicodeCodePoint(str); + return newString; + } + ); } \ No newline at end of file diff --git a/src/NadekoBot/_Extensions/UserExtensions.cs b/src/NadekoBot/_Extensions/UserExtensions.cs new file mode 100644 index 000000000..84e123bd5 --- /dev/null +++ b/src/NadekoBot/_Extensions/UserExtensions.cs @@ -0,0 +1,40 @@ +using NadekoBot.Db.Models; + +namespace NadekoBot.Extensions; + +public static class UserExtensions +{ + public static async Task EmbedAsync(this IUser user, IEmbedBuilder embed, string msg = "") + { + var ch = await user.CreateDMChannelAsync(); + return await ch.EmbedAsync(embed, msg); + } + + public static async Task SendAsync(this IUser user, SmartText text, bool sanitizeAll = false) + { + var ch = await user.CreateDMChannelAsync(); + return await ch.SendAsync(text, sanitizeAll); + } + + public static async Task SendConfirmAsync(this IUser user, IEmbedBuilderService eb, string text) + => await user.SendMessageAsync("", embed: eb.Create().WithOkColor().WithDescription(text).Build()); + + public static async Task SendErrorAsync(this IUser user, IEmbedBuilderService eb, string error) + => await user.SendMessageAsync("", embed: eb.Create().WithErrorColor().WithDescription(error).Build()); + + public static async Task SendPendingAsync(this IUser user, IEmbedBuilderService eb, string message) + => await user.SendMessageAsync("", embed: eb.Create().WithPendingColor().WithDescription(message).Build()); + + // This method is used by everything that fetches the avatar from a user + public static Uri RealAvatarUrl(this IUser usr, ushort size = 256) + => usr.AvatarId is null ? new(usr.GetDefaultAvatarUrl()) : new Uri(usr.GetAvatarUrl(ImageFormat.Auto, size)); + + // This method is only used for the xp card + public static Uri RealAvatarUrl(this DiscordUser usr) + => usr.AvatarId is null + ? null + : new Uri(usr.AvatarId.StartsWith("a_", StringComparison.InvariantCulture) + ? $"{DiscordConfig.CDNUrl}avatars/{usr.UserId}/{usr.AvatarId}.gif" + : $"{DiscordConfig.CDNUrl}avatars/{usr.UserId}/{usr.AvatarId}.png" + ); +} \ No newline at end of file