diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..4b01ffbaa --- /dev/null +++ b/.editorconfig @@ -0,0 +1,111 @@ + +[*.{appxmanifest,asax,ascx,aspx,axaml,build,cg,cginc,compute,cs,cshtml,dtd,hlsl,hlsli,hlslinc,master,nuspec,paml,razor,resw,resx,shader,skin,usf,ush,vb,xaml,xamlx,xoml,xsd}] +indent_style = space +indent_size = 4 +tab_width = 4 + +[*.cs] + +# Microsoft .NET properties +csharp_new_line_before_members_in_object_initializers = false +csharp_preferred_modifier_order = public, private, protected, internal, new, static, abstract, virtual, sealed, readonly, override, extern, unsafe, volatile, async:suggestion +csharp_style_var_elsewhere = true:suggestion +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +dotnet_naming_rule.constants_rule.import_to_resharper = as_predefined +dotnet_naming_rule.constants_rule.severity = suggestion +dotnet_naming_rule.constants_rule.style = all_upper_style +dotnet_naming_rule.constants_rule.symbols = constants_symbols +dotnet_naming_rule.local_constants_rule.import_to_resharper = as_predefined +dotnet_naming_rule.local_constants_rule.severity = suggestion +dotnet_naming_rule.local_constants_rule.style = all_upper_style +dotnet_naming_rule.local_constants_rule.symbols = local_constants_symbols +dotnet_naming_rule.private_constants_rule.import_to_resharper = as_predefined +dotnet_naming_rule.private_constants_rule.severity = suggestion +dotnet_naming_rule.private_constants_rule.style = all_upper_style +dotnet_naming_rule.private_constants_rule.symbols = private_constants_symbols +dotnet_naming_rule.private_static_readonly_rule.import_to_resharper = as_predefined +dotnet_naming_rule.private_static_readonly_rule.resharper_style = _ + aaBb, aaBb +dotnet_naming_rule.private_static_readonly_rule.severity = suggestion +dotnet_naming_rule.private_static_readonly_rule.style = lower_camel_case_style_1 +dotnet_naming_rule.private_static_readonly_rule.symbols = private_static_readonly_symbols +dotnet_naming_rule.unity_serialized_field_rule.import_to_resharper = True +dotnet_naming_rule.unity_serialized_field_rule.resharper_description = Unity serialized field +dotnet_naming_rule.unity_serialized_field_rule.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef +dotnet_naming_rule.unity_serialized_field_rule.severity = suggestion +dotnet_naming_rule.unity_serialized_field_rule.style = lower_camel_case_style +dotnet_naming_rule.unity_serialized_field_rule.symbols = unity_serialized_field_symbols +dotnet_naming_rule.unity_serialized_field_rule_1.import_to_resharper = True +dotnet_naming_rule.unity_serialized_field_rule_1.resharper_description = Unity serialized field +dotnet_naming_rule.unity_serialized_field_rule_1.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef +dotnet_naming_rule.unity_serialized_field_rule_1.severity = suggestion +dotnet_naming_rule.unity_serialized_field_rule_1.style = lower_camel_case_style +dotnet_naming_rule.unity_serialized_field_rule_1.symbols = unity_serialized_field_symbols_1 +dotnet_naming_style.all_upper_style.capitalization = all_upper +dotnet_naming_style.all_upper_style.word_separator = _ +dotnet_naming_style.lower_camel_case_style.capitalization = camel_case +dotnet_naming_style.lower_camel_case_style_1.capitalization = camel_case +dotnet_naming_style.lower_camel_case_style_1.required_prefix = _ +dotnet_naming_symbols.constants_symbols.applicable_accessibilities = public,internal,protected,protected_internal,private_protected +dotnet_naming_symbols.constants_symbols.applicable_kinds = field +dotnet_naming_symbols.constants_symbols.required_modifiers = const +dotnet_naming_symbols.local_constants_symbols.applicable_accessibilities = * +dotnet_naming_symbols.local_constants_symbols.applicable_kinds = local +dotnet_naming_symbols.local_constants_symbols.required_modifiers = const +dotnet_naming_symbols.private_constants_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_constants_symbols.applicable_kinds = field +dotnet_naming_symbols.private_constants_symbols.required_modifiers = const +dotnet_naming_symbols.private_static_readonly_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_static_readonly_symbols.applicable_kinds = field +dotnet_naming_symbols.private_static_readonly_symbols.required_modifiers = static,readonly +dotnet_naming_symbols.unity_serialized_field_symbols.applicable_accessibilities = * +dotnet_naming_symbols.unity_serialized_field_symbols.applicable_kinds = +dotnet_naming_symbols.unity_serialized_field_symbols.resharper_applicable_kinds = unity_serialised_field +dotnet_naming_symbols.unity_serialized_field_symbols.resharper_required_modifiers = instance +dotnet_naming_symbols.unity_serialized_field_symbols_1.applicable_accessibilities = * +dotnet_naming_symbols.unity_serialized_field_symbols_1.applicable_kinds = +dotnet_naming_symbols.unity_serialized_field_symbols_1.resharper_applicable_kinds = unity_serialised_field +dotnet_naming_symbols.unity_serialized_field_symbols_1.resharper_required_modifiers = instance +dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none +dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:none +dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion +dotnet_style_qualification_for_event = false:suggestion +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion + +# ReSharper properties +resharper_autodetect_indent_settings = true +resharper_object_creation_when_type_not_evident = target_typed +resharper_show_autodetect_configure_formatting_tip = false +resharper_use_indent_from_vs = false + +# ReSharper inspection severities +resharper_arrange_object_creation_when_type_evident_highlighting = none +resharper_arrange_redundant_parentheses_highlighting = hint +resharper_arrange_this_qualifier_highlighting = hint +resharper_arrange_type_member_modifiers_highlighting = hint +resharper_arrange_type_modifiers_highlighting = hint +resharper_built_in_type_reference_style_for_member_access_highlighting = hint +resharper_built_in_type_reference_style_highlighting = hint +resharper_check_namespace_highlighting = none +resharper_comment_typo_highlighting = none +resharper_empty_general_catch_clause_highlighting = none +resharper_function_never_returns_highlighting = suggestion +resharper_identifier_typo_highlighting = none +resharper_inconsistent_naming_highlighting = suggestion +resharper_invert_if_highlighting = none +resharper_non_readonly_member_in_get_hash_code_highlighting = suggestion +resharper_redundant_anonymous_type_property_name_highlighting = suggestion +resharper_redundant_base_qualifier_highlighting = warning +resharper_string_literal_typo_highlighting = none +resharper_suggest_var_or_type_built_in_types_highlighting = hint +resharper_suggest_var_or_type_elsewhere_highlighting = hint +resharper_suggest_var_or_type_simple_types_highlighting = hint +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 diff --git a/NadekoBot.sln.DotSettings b/NadekoBot.sln.DotSettings new file mode 100644 index 000000000..9a858cca7 --- /dev/null +++ b/NadekoBot.sln.DotSettings @@ -0,0 +1,8 @@ + + 3 + EXPANDED + True + CHOP_IF_LONG + True + CHOP_IF_LONG + CHOP_ALWAYS \ No newline at end of file diff --git a/src/NadekoBot/.editorconfig b/src/NadekoBot/.editorconfig new file mode 100644 index 000000000..d2a8ed9c5 --- /dev/null +++ b/src/NadekoBot/.editorconfig @@ -0,0 +1,328 @@ +# Remove the line below if you want to inherit .editorconfig settings from higher directories +root = true + +# C# files +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 4 +indent_style = space +tab_width = 4 + +# New line preferences +end_of_line = crlf +insert_final_newline = false + +#### .NET Coding Conventions #### + +# 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 +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_method = false +dotnet_style_qualification_for_property = false + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_other_operators = never_if_unnecessary +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:warning + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = always:error + +# Expression-level preferences +dotnet_style_coalesce_expression = true +dotnet_style_collection_initializer = true +dotnet_style_explicit_tuple_names = true +dotnet_style_namespace_match_folder = true +dotnet_style_null_propagation = true +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_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 +dotnet_style_prefer_simplified_boolean_expressions = true +dotnet_style_prefer_simplified_interpolation = true + +# Field preferences +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 +csharp_style_var_elsewhere = true +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:suggestion +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_properties = true:suggestion + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true:error +csharp_style_pattern_matching_over_is_with_cast_check = true:error +csharp_style_prefer_not_pattern = true:error +csharp_style_prefer_pattern_matching = true:suggestion +csharp_style_prefer_switch_expression = true + +# Null-checking preferences +csharp_style_conditional_delegate_call = true:error + +# Modifier preferences +csharp_prefer_static_local_function = true +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async + +# Code-block preferences +csharp_prefer_braces = when_multiline:suggestion +csharp_prefer_simple_using_statement = true + +# Expression-level preferences +csharp_prefer_simple_default_expression = true +csharp_style_deconstructed_variable_declaration = true +csharp_style_implicit_object_creation_when_type_is_apparent = true:error +csharp_style_inlined_variable_declaration = true:warning +csharp_style_pattern_local_over_anonymous_function = true +csharp_style_prefer_index_operator = true +csharp_style_prefer_range_operator = true +csharp_style_throw_expression = true:error +csharp_style_unused_value_assignment_preference = discard_variable:warning +csharp_style_unused_value_expression_statement_preference = discard_variable + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:error + +# Enforce file-scoped namespaces +csharp_style_namespace_declarations=file_scoped:error + +# New line preferences +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false +csharp_style_allow_embedded_statements_on_same_line_experimental = true + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = true +csharp_new_line_before_else = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.const_fields.symbols = const_fields +dotnet_naming_rule.const_fields.style = all_upper +dotnet_naming_rule.const_fields.severity = warning + +dotnet_naming_rule.class_should_be_pascal_case.severity = error +dotnet_naming_rule.class_should_be_pascal_case.symbols = class +dotnet_naming_rule.class_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.struct_should_be_pascal_case.severity = error +dotnet_naming_rule.struct_should_be_pascal_case.symbols = struct +dotnet_naming_rule.struct_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = error +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = error +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.enum_should_be_pascal_case.severity = error +dotnet_naming_rule.enum_should_be_pascal_case.symbols = enum +dotnet_naming_rule.enum_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.property_should_be_pascal_case.severity = error +dotnet_naming_rule.property_should_be_pascal_case.symbols = property +dotnet_naming_rule.property_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.method_should_be_pascal_case.severity = error +dotnet_naming_rule.method_should_be_pascal_case.symbols = method +dotnet_naming_rule.method_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.async_method_should_be_ends_with_async.severity = error +dotnet_naming_rule.async_method_should_be_ends_with_async.symbols = async_method +dotnet_naming_rule.async_method_should_be_ends_with_async.style = ends_with_async + +dotnet_naming_rule.private_field_should_be_begins_with_underscore.severity = error +dotnet_naming_rule.private_field_should_be_begins_with_underscore.symbols = private_field +dotnet_naming_rule.private_field_should_be_begins_with_underscore.style = begins_with_underscore + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = error +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.local_variable_should_be_camel_case.severity = error +dotnet_naming_rule.local_variable_should_be_camel_case.symbols = local_variable +dotnet_naming_rule.local_variable_should_be_camel_case.style = camel_case + +dotnet_naming_rule.public_anything_should_be_pascal_case.severity = error +dotnet_naming_rule.public_anything_should_be_pascal_case.symbols = public_anything +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.class.applicable_kinds = class +dotnet_naming_symbols.class.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.class.required_modifiers = + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.struct.applicable_kinds = struct +dotnet_naming_symbols.struct.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.struct.required_modifiers = + +dotnet_naming_symbols.enum.applicable_kinds = enum +dotnet_naming_symbols.enum.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.enum.required_modifiers = + +dotnet_naming_symbols.method.applicable_kinds = method +dotnet_naming_symbols.method.applicable_accessibilities = public +dotnet_naming_symbols.method.required_modifiers = + +dotnet_naming_symbols.property.applicable_kinds = property +dotnet_naming_symbols.property.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.property.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +dotnet_naming_symbols.private_field.applicable_kinds = field +dotnet_naming_symbols.private_field.applicable_accessibilities = private +dotnet_naming_symbols.private_field.required_modifiers = + +dotnet_naming_symbols.async_method.applicable_kinds = method, local_function +dotnet_naming_symbols.async_method.applicable_accessibilities = * +dotnet_naming_symbols.async_method.required_modifiers = async + +dotnet_naming_symbols.local_variable.applicable_kinds = parameter, local +dotnet_naming_symbols.local_variable.applicable_accessibilities = local +dotnet_naming_symbols.local_variable.required_modifiers = + +dotnet_naming_symbols.public_anything.applicable_kinds = property, field, event, class, struct, interface, enum, delegate, method +dotnet_naming_symbols.public_anything.applicable_accessibilities = public, internal +dotnet_naming_symbols.public_anything.required_modifiers = + +# Naming styles + + +dotnet_naming_style.all_upper.capitalization = all_upper + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.begins_with_underscore.required_prefix = _ +dotnet_naming_style.begins_with_underscore.required_suffix = +dotnet_naming_style.begins_with_underscore.word_separator = +dotnet_naming_style.begins_with_underscore.capitalization = camel_case + +dotnet_naming_style.ends_with_async.required_prefix = +# dotnet_naming_style.ends_with_async.required_suffix = Async +dotnet_naming_style.ends_with_async.word_separator = +dotnet_naming_style.ends_with_async.capitalization = pascal_case + +dotnet_naming_style.camel_case.required_prefix = +dotnet_naming_style.camel_case.required_suffix = +dotnet_naming_style.camel_case.word_separator = +dotnet_naming_style.camel_case.capitalization = camel_case + +# CA1822: Mark members as static +dotnet_diagnostic.CA1822.severity = suggestion + +# IDE0004: Cast is redundant +dotnet_diagnostic.IDE0004.severity = error + +# IDE0058: Expression value is never used +dotnet_diagnostic.IDE0058.severity = none + +# IDE0011: Add braces to 'if'/'else' statement +dotnet_diagnostic.IDE0011.severity = none \ No newline at end of file diff --git a/src/NadekoBot/Bot.cs b/src/NadekoBot/Bot.cs index 438af1002..8a90eb1b5 100644 --- a/src/NadekoBot/Bot.cs +++ b/src/NadekoBot/Bot.cs @@ -8,7 +8,6 @@ using NadekoBot.Common.Configs; using NadekoBot.Db; using NadekoBot.Modules.Administration.Services; using Discord.Interactions; -using RunMode = Discord.Interactions.RunMode; namespace NadekoBot; diff --git a/src/NadekoBot/Common/Attributes/CommandNameLoadHelper.cs b/src/NadekoBot/Common/Attributes/CommandNameLoadHelper.cs index 56bdc514e..9bebf0c36 100644 --- a/src/NadekoBot/Common/Attributes/CommandNameLoadHelper.cs +++ b/src/NadekoBot/Common/Attributes/CommandNameLoadHelper.cs @@ -3,11 +3,10 @@ public static class CommandNameLoadHelper { - private static YamlDotNet.Serialization.IDeserializer _deserializer + private static readonly YamlDotNet.Serialization.IDeserializer _deserializer = new YamlDotNet.Serialization.Deserializer(); - public static Lazy> LazyCommandAliases - = new Lazy>(() => LoadCommandNames()); + public static Lazy> LazyCommandAliases = new(() => LoadCommandNames()); public static Dictionary LoadCommandNames(string aliasesFilePath = "data/aliases.yml") { var text = File.ReadAllText(aliasesFilePath); diff --git a/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs b/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs index 56fb18043..2643862ed 100644 --- a/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs +++ b/src/NadekoBot/Common/Collections/ConcurrentHashSet.cs @@ -344,7 +344,7 @@ public sealed class ConcurrentHashSet : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IReadOnlyCollection, ICollection : IList where T : class, IIndexed { public List Source { get; } - private readonly object _locker = new object(); + private readonly object _locker = new(); public int Count => Source.Count; public bool IsReadOnly => false; diff --git a/src/NadekoBot/Common/DownloadTracker.cs b/src/NadekoBot/Common/DownloadTracker.cs index e60c33496..22bdb301b 100644 --- a/src/NadekoBot/Common/DownloadTracker.cs +++ b/src/NadekoBot/Common/DownloadTracker.cs @@ -2,8 +2,8 @@ public class DownloadTracker : INService { - private ConcurrentDictionary LastDownloads { get; } = new ConcurrentDictionary(); - private SemaphoreSlim downloadUsersSemaphore = new SemaphoreSlim(1, 1); + private ConcurrentDictionary LastDownloads { get; } = new(); + private readonly SemaphoreSlim downloadUsersSemaphore = new(1, 1); /// /// Ensures all users on the specified guild were downloaded within the last hour. diff --git a/src/NadekoBot/Common/Kwum.cs b/src/NadekoBot/Common/Kwum.cs index f050ad9ce..fd5cba307 100644 --- a/src/NadekoBot/Common/Kwum.cs +++ b/src/NadekoBot/Common/Kwum.cs @@ -49,7 +49,7 @@ public readonly struct kwum : IEquatable } public static kwum operator +(kwum left, kwum right) - => new kwum(left._value + right._value); + => new(left._value + right._value); public static bool operator ==(kwum left, kwum right) => left._value == right._value; @@ -63,7 +63,7 @@ public readonly struct kwum : IEquatable public static implicit operator int(kwum kwum) => kwum._value; public static implicit operator kwum(int num) - => new kwum(num); + => new(num); public static bool IsValidChar(char c) => ValidCharacters.Contains(c); @@ -77,7 +77,7 @@ public readonly struct kwum : IEquatable while (localValue > 0) { localValue = Math.DivRem(localValue, count, out var rem); - chars[--arrSize] = ValidCharacters[(int)rem]; + chars[--arrSize] = ValidCharacters[rem]; } return new(chars); diff --git a/src/NadekoBot/Common/NadekoModule.cs b/src/NadekoBot/Common/NadekoModule.cs index bb7482241..ca09a8bf8 100644 --- a/src/NadekoBot/Common/NadekoModule.cs +++ b/src/NadekoBot/Common/NadekoModule.cs @@ -112,8 +112,8 @@ public abstract class NadekoModule : ModuleBase { var _ = Task.Run(() => { - if (!(arg is SocketUserMessage userMsg) || - !(userMsg.Channel is ITextChannel chan) || + if (arg is not SocketUserMessage userMsg || + userMsg.Channel is not ITextChannel chan || userMsg.Author.Id != userId || userMsg.Channel.Id != channelId) { diff --git a/src/NadekoBot/Common/NadekoRandom.cs b/src/NadekoBot/Common/NadekoRandom.cs index 2f928c486..a874bddf0 100644 --- a/src/NadekoBot/Common/NadekoRandom.cs +++ b/src/NadekoBot/Common/NadekoRandom.cs @@ -36,7 +36,7 @@ public class NadekoRandom : Random var bytes = new byte[sizeof(int)]; _rng.GetBytes(bytes); var sign = Math.Sign(BitConverter.ToInt32(bytes, 0)); - return sign * BitConverter.ToInt32(bytes, 0) % (maxValue - minValue) + minValue; + return (sign * BitConverter.ToInt32(bytes, 0) % (maxValue - minValue)) + minValue; } public long NextLong(long minValue, long maxValue) @@ -48,7 +48,7 @@ public class NadekoRandom : Random var bytes = new byte[sizeof(long)]; _rng.GetBytes(bytes); var sign = Math.Sign(BitConverter.ToInt64(bytes, 0)); - return sign * BitConverter.ToInt64(bytes, 0) % (maxValue - minValue) + minValue; + return (sign * BitConverter.ToInt64(bytes, 0) % (maxValue - minValue)) + minValue; } public override void NextBytes(byte[] buffer) @@ -60,7 +60,7 @@ public class NadekoRandom : Random { var bytes = new byte[sizeof(double)]; _rng.GetBytes(bytes); - return Math.Abs(BitConverter.ToDouble(bytes, 0) / double.MaxValue + 1); + return Math.Abs((BitConverter.ToDouble(bytes, 0) / double.MaxValue) + 1); } public override double NextDouble() diff --git a/src/NadekoBot/Common/PubSub/EventPubSub.cs b/src/NadekoBot/Common/PubSub/EventPubSub.cs index e4cc2182b..fee3772c3 100644 --- a/src/NadekoBot/Common/PubSub/EventPubSub.cs +++ b/src/NadekoBot/Common/PubSub/EventPubSub.cs @@ -2,9 +2,8 @@ public class EventPubSub : IPubSub { - private readonly Dictionary>>> _actions - = new Dictionary>>>(); - private readonly object locker = new object(); + private readonly Dictionary>>> _actions = new(); + private readonly object locker = new(); public Task Sub(in TypedKey key, Func action) { diff --git a/src/NadekoBot/Common/PubSub/JsonSeria.cs b/src/NadekoBot/Common/PubSub/JsonSeria.cs index a1273023c..4c3cad887 100644 --- a/src/NadekoBot/Common/PubSub/JsonSeria.cs +++ b/src/NadekoBot/Common/PubSub/JsonSeria.cs @@ -5,7 +5,7 @@ namespace NadekoBot.Common; public class JsonSeria : ISeria { - private JsonSerializerOptions serializerOptions = new JsonSerializerOptions() + private readonly JsonSerializerOptions serializerOptions = new() { Converters = { diff --git a/src/NadekoBot/Common/PubSub/TypedKey.cs b/src/NadekoBot/Common/PubSub/TypedKey.cs index 6e768c0ad..f1b7fd0aa 100644 --- a/src/NadekoBot/Common/PubSub/TypedKey.cs +++ b/src/NadekoBot/Common/PubSub/TypedKey.cs @@ -10,7 +10,7 @@ public readonly struct TypedKey } public static implicit operator TypedKey(in string input) - => new TypedKey(input); + => new(input); public static implicit operator string(in TypedKey input) => input.Key; diff --git a/src/NadekoBot/Common/PubSub/YamlSeria.cs b/src/NadekoBot/Common/PubSub/YamlSeria.cs index 0a66754a3..8f1453e1c 100644 --- a/src/NadekoBot/Common/PubSub/YamlSeria.cs +++ b/src/NadekoBot/Common/PubSub/YamlSeria.cs @@ -11,7 +11,7 @@ public class YamlSeria : IConfigSeria private readonly IDeserializer _deserializer; private static readonly Regex CodePointRegex - = new Regex(@"(\\U(?[a-zA-Z0-9]{8})|\\u(?[a-zA-Z0-9]{4})|\\x(?[a-zA-Z0-9]{2}))", + = new(@"(\\U(?[a-zA-Z0-9]{8})|\\u(?[a-zA-Z0-9]{4})|\\x(?[a-zA-Z0-9]{2}))", RegexOptions.Compiled); public YamlSeria() diff --git a/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs b/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs index 964bcdbb0..73b801c13 100644 --- a/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs +++ b/src/NadekoBot/Common/Replacements/ReplacementBuilder.cs @@ -5,9 +5,9 @@ namespace NadekoBot.Common; public class ReplacementBuilder { - private static readonly Regex rngRegex = new Regex("%rng(?:(?(?:-)?\\d+)-(?(?:-)?\\d+))?%", RegexOptions.Compiled); - private ConcurrentDictionary> _reps = new ConcurrentDictionary>(); - private ConcurrentDictionary> _regex = new ConcurrentDictionary>(); + private static readonly Regex rngRegex = new("%rng(?:(?(?:-)?\\d+)-(?(?:-)?\\d+))?%", RegexOptions.Compiled); + private readonly ConcurrentDictionary> _reps = new(); + private readonly ConcurrentDictionary> _regex = new(); public ReplacementBuilder() { diff --git a/src/NadekoBot/Common/SmartText/SmartEmbedText.cs b/src/NadekoBot/Common/SmartText/SmartEmbedText.cs index 9c4f35657..6a42a3e1e 100644 --- a/src/NadekoBot/Common/SmartText/SmartEmbedText.cs +++ b/src/NadekoBot/Common/SmartText/SmartEmbedText.cs @@ -21,7 +21,7 @@ public sealed record SmartEmbedText : SmartText !string.IsNullOrWhiteSpace(Url) || !string.IsNullOrWhiteSpace(Thumbnail) || !string.IsNullOrWhiteSpace(Image) || - Footer != null && (!string.IsNullOrWhiteSpace(Footer.Text) || !string.IsNullOrWhiteSpace(Footer.IconUrl)) || + (Footer != null && (!string.IsNullOrWhiteSpace(Footer.Text) || !string.IsNullOrWhiteSpace(Footer.IconUrl))) || Fields is { Length: > 0 }; public static SmartEmbedText FromEmbed(IEmbed eb, string plainText = null) diff --git a/src/NadekoBot/Common/SmartText/SmartPlainText.cs b/src/NadekoBot/Common/SmartText/SmartPlainText.cs index 247febe82..2d67df1e2 100644 --- a/src/NadekoBot/Common/SmartText/SmartPlainText.cs +++ b/src/NadekoBot/Common/SmartText/SmartPlainText.cs @@ -10,7 +10,7 @@ public sealed record SmartPlainText : SmartText } public static implicit operator SmartPlainText(string input) - => new SmartPlainText(input); + => new(input); public static implicit operator string(SmartPlainText input) => input.Text; diff --git a/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs b/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs index 2e787fd75..066bdebc5 100644 --- a/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs +++ b/src/NadekoBot/Common/TypeReaders/Models/PermissionAction.cs @@ -2,8 +2,8 @@ public class PermissionAction { - public static PermissionAction Enable => new PermissionAction(true); - public static PermissionAction Disable => new PermissionAction(false); + public static PermissionAction Enable => new(true); + public static PermissionAction Disable => new(false); public bool Value { get; } diff --git a/src/NadekoBot/Common/TypeReaders/Models/StoopidTime.cs b/src/NadekoBot/Common/TypeReaders/Models/StoopidTime.cs index f2fab26be..d21c9895e 100644 --- a/src/NadekoBot/Common/TypeReaders/Models/StoopidTime.cs +++ b/src/NadekoBot/Common/TypeReaders/Models/StoopidTime.cs @@ -7,7 +7,7 @@ public class StoopidTime public string Input { get; set; } public TimeSpan Time { get; set; } - private static readonly Regex _regex = new Regex( + private static readonly Regex _regex = new( @"^(?:(?\d)mo)?(?:(?\d{1,2})w)?(?:(?\d{1,2})d)?(?:(?\d{1,4})h)?(?:(?\d{1,5})m)?(?:(?\d{1,6})s)?$", RegexOptions.Compiled | RegexOptions.Multiline); @@ -42,8 +42,8 @@ public class StoopidTime namesAndValues[groupName] = value; output += m.Groups[groupName].Value + " " + groupName + " "; } - var ts = new TimeSpan(30 * namesAndValues["months"] + - 7 * namesAndValues["weeks"] + + var ts = new TimeSpan((30 * namesAndValues["months"]) + + (7 * namesAndValues["weeks"]) + namesAndValues["days"], namesAndValues["hours"], namesAndValues["minutes"], diff --git a/src/NadekoBot/Common/TypeReaders/ShmartNumberTypeReader.cs b/src/NadekoBot/Common/TypeReaders/ShmartNumberTypeReader.cs index f3e67728f..d9f59737b 100644 --- a/src/NadekoBot/Common/TypeReaders/ShmartNumberTypeReader.cs +++ b/src/NadekoBot/Common/TypeReaders/ShmartNumberTypeReader.cs @@ -68,7 +68,7 @@ public sealed class ShmartNumberTypeReader : NadekoTypeReader } } - private static readonly Regex percentRegex = new Regex(@"^((?100|\d{1,2})%)$", RegexOptions.Compiled); + private static readonly Regex percentRegex = new(@"^((?100|\d{1,2})%)$", RegexOptions.Compiled); private long Cur(ICommandContext ctx) { diff --git a/src/NadekoBot/Common/Yml/Rgba32Converter.cs b/src/NadekoBot/Common/Yml/Rgba32Converter.cs index fd4551ad7..fb46192ef 100644 --- a/src/NadekoBot/Common/Yml/Rgba32Converter.cs +++ b/src/NadekoBot/Common/Yml/Rgba32Converter.cs @@ -23,7 +23,7 @@ public class Rgba32Converter : IYamlTypeConverter public void WriteYaml(IEmitter emitter, object value, Type type) { var color = (Rgba32)value; - var val = (uint) (color.B << 0 | color.G << 8 | color.R << 16); + var val = (uint) ((color.B << 0) | (color.G << 8) | (color.R << 16)); emitter.Emit(new Scalar(val.ToString("X6").ToLower())); } } diff --git a/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs b/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs index d0c3658c0..649a08222 100644 --- a/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs +++ b/src/NadekoBot/Db/Extensions/GuildConfigExtensions.cs @@ -32,12 +32,12 @@ public static class GuildConfigExtensions } private static List DefaultWarnPunishments => - new List() { - new WarningPunishment() { + new() { + new() { Count = 3, Punishment = PunishmentAction.Kick }, - new WarningPunishment() { + new() { Count = 5, Punishment = PunishmentAction.Ban } diff --git a/src/NadekoBot/Db/Models/AntiProtection.cs b/src/NadekoBot/Db/Models/AntiProtection.cs index d03a37cca..7aaed51d8 100644 --- a/src/NadekoBot/Db/Models/AntiProtection.cs +++ b/src/NadekoBot/Db/Models/AntiProtection.cs @@ -25,7 +25,7 @@ public class AntiSpamSetting : DbEntity public int MessageThreshold { get; set; } = 3; public int MuteTime { get; set; } = 0; public ulong? RoleId { get; set; } - public HashSet IgnoredChannels { get; set; } = new HashSet(); + public HashSet IgnoredChannels { get; set; } = new(); } public class AntiAltSetting diff --git a/src/NadekoBot/Db/Models/ClubInfo.cs b/src/NadekoBot/Db/Models/ClubInfo.cs index d32231447..60ffe4ce4 100644 --- a/src/NadekoBot/Db/Models/ClubInfo.cs +++ b/src/NadekoBot/Db/Models/ClubInfo.cs @@ -16,10 +16,10 @@ public class ClubInfo : DbEntity public int OwnerId { get; set; } public DiscordUser Owner { get; set; } - public List Users { get; set; } = new List(); + public List Users { get; set; } = new(); - public List Applicants { get; set; } = new List(); - public List Bans { get; set; } = new List(); + public List Applicants { get; set; } = new(); + public List Bans { get; set; } = new(); public string Description { get; set; } public override string ToString() diff --git a/src/NadekoBot/Db/Models/CurrencyTransaction.cs b/src/NadekoBot/Db/Models/CurrencyTransaction.cs index a9ec396a8..3e31af27d 100644 --- a/src/NadekoBot/Db/Models/CurrencyTransaction.cs +++ b/src/NadekoBot/Db/Models/CurrencyTransaction.cs @@ -6,7 +6,7 @@ public class CurrencyTransaction : DbEntity public string Reason { get; set; } public ulong UserId { get; set; } - public CurrencyTransaction Clone() => new CurrencyTransaction + public CurrencyTransaction Clone() => new() { Amount = Amount, Reason = Reason, diff --git a/src/NadekoBot/Db/Models/FollowedStream.cs b/src/NadekoBot/Db/Models/FollowedStream.cs index f48e75f9f..8c02989d3 100644 --- a/src/NadekoBot/Db/Models/FollowedStream.cs +++ b/src/NadekoBot/Db/Models/FollowedStream.cs @@ -34,6 +34,5 @@ public class FollowedStream : DbEntity public override bool Equals(object obj) => obj is FollowedStream fs && Equals(fs); - public StreamDataKey CreateKey() => - new StreamDataKey(Type, Username.ToLower()); + public StreamDataKey CreateKey() => new(Type, Username.ToLower()); } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/GuildConfig.cs b/src/NadekoBot/Db/Models/GuildConfig.cs index 8cebcbfee..b90789af1 100644 --- a/src/NadekoBot/Db/Models/GuildConfig.cs +++ b/src/NadekoBot/Db/Models/GuildConfig.cs @@ -10,7 +10,7 @@ public class GuildConfig : DbEntity public string Prefix { get; set; } = null; public bool DeleteMessageOnCommand { get; set; } - public HashSet DelMsgOnCmdChannels { get; set; } = new HashSet(); + public HashSet DelMsgOnCmdChannels { get; set; } = new(); public string AutoAssignRoleIds { get; set; } //greet stuff public bool AutoDeleteGreetMessages { get; set; } //unused @@ -44,31 +44,31 @@ public class GuildConfig : DbEntity public bool AutoDeleteSelfAssignedRoleMessages { get; set; } //stream notifications - public HashSet FollowedStreams { get; set; } = new HashSet(); + public HashSet FollowedStreams { get; set; } = new(); //currencyGeneration - public HashSet GenerateCurrencyChannelIds { get; set; } = new HashSet(); + public HashSet GenerateCurrencyChannelIds { get; set; } = new(); public List Permissions { get; set; } public bool VerbosePermissions { get; set; } = true; public string PermissionRole { get; set; } = null; - public HashSet CommandCooldowns { get; set; } = new HashSet(); + public HashSet CommandCooldowns { get; set; } = new(); //filtering public bool FilterInvites { get; set; } public bool FilterLinks { get; set; } - public HashSet FilterInvitesChannelIds { get; set; } = new HashSet(); - public HashSet FilterLinksChannelIds { get; set; } = new HashSet(); + public HashSet FilterInvitesChannelIds { get; set; } = new(); + public HashSet FilterLinksChannelIds { get; set; } = new(); //public bool FilterLinks { get; set; } //public HashSet FilterLinksChannels { get; set; } = new HashSet(); public bool FilterWords { get; set; } - public HashSet FilteredWords { get; set; } = new HashSet(); - public HashSet FilterWordsChannelIds { get; set; } = new HashSet(); + public HashSet FilteredWords { get; set; } = new(); + public HashSet FilterWordsChannelIds { get; set; } = new(); - public HashSet MutedUsers { get; set; } = new HashSet(); + public HashSet MutedUsers { get; set; } = new(); public string MuteRoleName { get; set; } public bool CleverbotEnabled { get; set; } @@ -80,12 +80,12 @@ public class GuildConfig : DbEntity public string Locale { get; set; } = null; public string TimeZoneId { get; set; } = null; - public HashSet UnmuteTimers { get; set; } = new HashSet(); - public HashSet UnbanTimer { get; set; } = new HashSet(); - public HashSet UnroleTimer { get; set; } = new HashSet(); + public HashSet UnmuteTimers { get; set; } = new(); + public HashSet UnbanTimer { get; set; } = new(); + public HashSet UnroleTimer { get; set; } = new(); public HashSet VcRoleInfos { get; set; } - public HashSet CommandAliases { get; set; } = new HashSet(); - public List WarnPunishments { get; set; } = new List(); + public HashSet CommandAliases { get; set; } = new(); + public List WarnPunishments { get; set; } = new(); public bool WarningsInitialized { get; set; } public HashSet SlowmodeIgnoredUsers { get; set; } public HashSet SlowmodeIgnoredRoles { get; set; } @@ -97,8 +97,8 @@ public class GuildConfig : DbEntity public StreamRoleSettings StreamRole { get; set; } public XpSettings XpSettings { get; set; } - public List FeedSubs { get; set; } = new List(); - public IndexedCollection ReactionRoleMessages { get; set; } = new IndexedCollection(); + public List FeedSubs { get; set; } = new(); + public IndexedCollection ReactionRoleMessages { get; set; } = new(); public bool NotifyStreamOffline { get; set; } public List SelfAssignableRoleGroupNames { get; set; } public int WarnExpireHours { get; set; } = 0; diff --git a/src/NadekoBot/Db/Models/LogSetting.cs b/src/NadekoBot/Db/Models/LogSetting.cs index b7a7dd8d2..46b4237e4 100644 --- a/src/NadekoBot/Db/Models/LogSetting.cs +++ b/src/NadekoBot/Db/Models/LogSetting.cs @@ -2,7 +2,7 @@ public class LogSetting : DbEntity { - public List LogIgnores { get; set; } = new List(); + public List LogIgnores { get; set; } = new(); public ulong GuildId { get; set; } public ulong? LogOtherId { get; set; } diff --git a/src/NadekoBot/Db/Models/MusicPlaylist.cs b/src/NadekoBot/Db/Models/MusicPlaylist.cs index 21c8f8330..6543833d2 100644 --- a/src/NadekoBot/Db/Models/MusicPlaylist.cs +++ b/src/NadekoBot/Db/Models/MusicPlaylist.cs @@ -5,5 +5,5 @@ public class MusicPlaylist : DbEntity public string Name { get; set; } public string Author { get; set; } public ulong AuthorId { get; set; } - public List Songs { get; set; } = new List(); + public List Songs { get; set; } = new(); } \ No newline at end of file diff --git a/src/NadekoBot/Db/Models/Permission.cs b/src/NadekoBot/Db/Models/Permission.cs index 5fb40c8bf..6680ca1f3 100644 --- a/src/NadekoBot/Db/Models/Permission.cs +++ b/src/NadekoBot/Db/Models/Permission.cs @@ -25,7 +25,7 @@ public class Permissionv2 : DbEntity, IIndexed public bool State { get; set; } [NotMapped] - public static Permissionv2 AllowAllPerm => new Permissionv2() + public static Permissionv2 AllowAllPerm => new() { PrimaryTarget = PrimaryPermissionType.Server, PrimaryTargetId = 0, @@ -36,7 +36,7 @@ public class Permissionv2 : DbEntity, IIndexed }; public static List GetDefaultPermlist => - new List + new() { AllowAllPerm }; diff --git a/src/NadekoBot/Db/Models/Poll.cs b/src/NadekoBot/Db/Models/Poll.cs index 8981e5866..f2216d4ae 100644 --- a/src/NadekoBot/Db/Models/Poll.cs +++ b/src/NadekoBot/Db/Models/Poll.cs @@ -8,7 +8,7 @@ public class Poll : DbEntity public ulong ChannelId { get; set; } public string Question { get; set; } public IndexedCollection Answers { get; set; } - public HashSet Votes { get; set; } = new HashSet(); + public HashSet Votes { get; set; } = new(); } public class PollAnswer : DbEntity, IIndexed diff --git a/src/NadekoBot/Db/Models/ShopEntry.cs b/src/NadekoBot/Db/Models/ShopEntry.cs index ef5bc2048..64339aa58 100644 --- a/src/NadekoBot/Db/Models/ShopEntry.cs +++ b/src/NadekoBot/Db/Models/ShopEntry.cs @@ -21,7 +21,7 @@ public class ShopEntry : DbEntity, IIndexed public ulong RoleId { get; set; } //list - public HashSet Items { get; set; } = new HashSet(); + public HashSet Items { get; set; } = new(); } public class ShopEntryItem : DbEntity diff --git a/src/NadekoBot/Db/Models/StreamRoleSettings.cs b/src/NadekoBot/Db/Models/StreamRoleSettings.cs index 0bd5b564f..28a6fc98b 100644 --- a/src/NadekoBot/Db/Models/StreamRoleSettings.cs +++ b/src/NadekoBot/Db/Models/StreamRoleSettings.cs @@ -29,12 +29,12 @@ public class StreamRoleSettings : DbEntity /// A collection of whitelisted users' IDs. Whitelisted users don't require 'keyword' in /// order to get the stream role. /// - public HashSet Whitelist { get; set; } = new HashSet(); + public HashSet Whitelist { get; set; } = new(); /// /// A collection of blacklisted users' IDs. Blacklisted useres will never get the stream role. /// - public HashSet Blacklist { get; set; } = new HashSet(); + public HashSet Blacklist { get; set; } = new(); } public class StreamRoleBlacklistedUser : DbEntity @@ -44,7 +44,7 @@ public class StreamRoleBlacklistedUser : DbEntity public override bool Equals(object obj) { - if (!(obj is StreamRoleBlacklistedUser x)) + if (obj is not StreamRoleBlacklistedUser x) return false; return x.UserId == UserId; diff --git a/src/NadekoBot/Db/Models/Waifu.cs b/src/NadekoBot/Db/Models/Waifu.cs index b05834c7a..712658538 100644 --- a/src/NadekoBot/Db/Models/Waifu.cs +++ b/src/NadekoBot/Db/Models/Waifu.cs @@ -14,7 +14,7 @@ public class WaifuInfo : DbEntity public DiscordUser Affinity { get; set; } public int Price { get; set; } - public List Items { get; set; } = new List(); + public List Items { get; set; } = new(); public override string ToString() { diff --git a/src/NadekoBot/Db/Models/XpSettings.cs b/src/NadekoBot/Db/Models/XpSettings.cs index 9d5ceb16d..88d28de57 100644 --- a/src/NadekoBot/Db/Models/XpSettings.cs +++ b/src/NadekoBot/Db/Models/XpSettings.cs @@ -5,9 +5,9 @@ public class XpSettings : DbEntity public int GuildConfigId { get; set; } public GuildConfig GuildConfig { get; set; } - public HashSet RoleRewards { get; set; } = new HashSet(); - public HashSet CurrencyRewards { get; set; } = new HashSet(); - public HashSet ExclusionList { get; set; } = new HashSet(); + public HashSet RoleRewards { get; set; } = new(); + public HashSet CurrencyRewards { get; set; } = new(); + public HashSet ExclusionList { get; set; } = new(); public bool ServerExcluded { get; set; } } diff --git a/src/NadekoBot/Db/NadekoContext.cs b/src/NadekoBot/Db/NadekoContext.cs index 1a1a37236..d2619e9ba 100644 --- a/src/NadekoBot/Db/NadekoContext.cs +++ b/src/NadekoBot/Db/NadekoContext.cs @@ -65,7 +65,7 @@ public class NadekoContext : DbContext } #if DEBUG - public static readonly ILoggerFactory _debugLoggerFactory = + private static readonly ILoggerFactory _debugLoggerFactory = LoggerFactory.Create(x => x.AddConsole()); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { @@ -162,7 +162,6 @@ public class NadekoContext : DbContext // .WithOne() // .OnDelete(DeleteBehavior.Cascade); - var wu = modelBuilder.Entity(); #endregion #region DiscordUser diff --git a/src/NadekoBot/Modules/Administration/Common/ProtectionStats.cs b/src/NadekoBot/Modules/Administration/Common/ProtectionStats.cs index 0c84585dc..f7655e063 100644 --- a/src/NadekoBot/Modules/Administration/Common/ProtectionStats.cs +++ b/src/NadekoBot/Modules/Administration/Common/ProtectionStats.cs @@ -14,14 +14,13 @@ public class AntiRaidStats { public AntiRaidSetting AntiRaidSettings { get; set; } public int UsersCount { get; set; } - public ConcurrentHashSet RaidUsers { get; set; } = new ConcurrentHashSet(); + public ConcurrentHashSet RaidUsers { get; set; } = new(); } public class AntiSpamStats { public AntiSpamSetting AntiSpamSettings { get; set; } - public ConcurrentDictionary UserStats { get; set; } - = new ConcurrentDictionary(); + public ConcurrentDictionary UserStats { get; set; } = new(); } public class AntiAltStats diff --git a/src/NadekoBot/Modules/Administration/Common/UserSpamStats.cs b/src/NadekoBot/Modules/Administration/Common/UserSpamStats.cs index c0a881390..a0521f350 100644 --- a/src/NadekoBot/Modules/Administration/Common/UserSpamStats.cs +++ b/src/NadekoBot/Modules/Administration/Common/UserSpamStats.cs @@ -15,13 +15,13 @@ public sealed class UserSpamStats : IDisposable ApplyNextMessage(msg); } - private readonly object applyLock = new object(); + private readonly object applyLock = new(); public void ApplyNextMessage(IUserMessage message) { lock (applyLock) { var upperMsg = message.Content.ToUpperInvariant(); - if (upperMsg != LastMessage || string.IsNullOrWhiteSpace(upperMsg) && message.Attachments.Any()) + if (upperMsg != LastMessage || (string.IsNullOrWhiteSpace(upperMsg) && message.Attachments.Any())) { LastMessage = upperMsg; while (timers.TryDequeue(out var old)) diff --git a/src/NadekoBot/Modules/Administration/RoleCommands.cs b/src/NadekoBot/Modules/Administration/RoleCommands.cs index eb5637a1f..cecfd6945 100644 --- a/src/NadekoBot/Modules/Administration/RoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/RoleCommands.cs @@ -263,7 +263,7 @@ public partial class Administration .Where(x => !x.IsManaged && x != x.Guild.EveryoneRole) .ToList(); - if (user.Id == ctx.Guild.OwnerId || ctx.User.Id != ctx.Guild.OwnerId && guser.GetRoles().Max(x => x.Position) <= userRoles.Max(x => x.Position)) + if (user.Id == ctx.Guild.OwnerId || (ctx.User.Id != ctx.Guild.OwnerId && guser.GetRoles().Max(x => x.Position) <= userRoles.Max(x => x.Position))) return; try { diff --git a/src/NadekoBot/Modules/Administration/SelfCommands.cs b/src/NadekoBot/Modules/Administration/SelfCommands.cs index c81d6256c..925b2b5af 100644 --- a/src/NadekoBot/Modules/Administration/SelfCommands.cs +++ b/src/NadekoBot/Modules/Administration/SelfCommands.cs @@ -101,7 +101,7 @@ public partial class Administration await SendConfirmAsync( text: string.Join("\n", scmds .Select(x => $@"```css -#{++i + page * 5} +#{++i + (page * 5)} [{GetText(strs.server)}]: {(x.GuildId.HasValue ? $"{x.GuildName} #{x.GuildId}" : "-")} [{GetText(strs.channel)}]: {x.ChannelName} #{x.ChannelId} [{GetText(strs.command_text)}]: {x.CommandText}```")), @@ -133,7 +133,7 @@ public partial class Administration await SendConfirmAsync( text: string.Join("\n", scmds .Select(x => $@"```css -#{++i + page * 5} +#{++i + (page * 5)} [{GetText(strs.server)}]: {(x.GuildId.HasValue ? $"{x.GuildName} #{x.GuildId}" : "-")} [{GetText(strs.channel)}]: {x.ChannelName} #{x.ChannelId} {GetIntervalText(x.Interval)} diff --git a/src/NadekoBot/Modules/Administration/Services/AdministrationService.cs b/src/NadekoBot/Modules/Administration/Services/AdministrationService.cs index 9c7847463..202c03fcd 100644 --- a/src/NadekoBot/Modules/Administration/Services/AdministrationService.cs +++ b/src/NadekoBot/Modules/Administration/Services/AdministrationService.cs @@ -45,7 +45,7 @@ public class AdministrationService : INService { var _ = Task.Run(async () => { - if (!(msg.Channel is SocketTextChannel channel)) + if (msg.Channel is not SocketTextChannel channel) return; //wat ?! @@ -145,7 +145,7 @@ public class AdministrationService : INService { var msg = await chanl.GetMessageAsync(messageId); - if (!(msg is IUserMessage umsg) || msg.Author.Id != context.Client.CurrentUser.Id) + if (msg is not IUserMessage umsg || msg.Author.Id != context.Client.CurrentUser.Id) return; var rep = new ReplacementBuilder() diff --git a/src/NadekoBot/Modules/Administration/Services/AutoAssignRoleService.cs b/src/NadekoBot/Modules/Administration/Services/AutoAssignRoleService.cs index 509a16d65..ded9a4838 100644 --- a/src/NadekoBot/Modules/Administration/Services/AutoAssignRoleService.cs +++ b/src/NadekoBot/Modules/Administration/Services/AutoAssignRoleService.cs @@ -14,7 +14,7 @@ public sealed class AutoAssignRoleService : INService //guildid/roleid private readonly ConcurrentDictionary> _autoAssignableRoles; - private Channel _assignQueue = Channel.CreateBounded( + private readonly Channel _assignQueue = Channel.CreateBounded( new BoundedChannelOptions(100) { FullMode = BoundedChannelFullMode.DropOldest, diff --git a/src/NadekoBot/Modules/Administration/Services/DiscordPermOverrideService.cs b/src/NadekoBot/Modules/Administration/Services/DiscordPermOverrideService.cs index 9b0d73846..ac9d4cee4 100644 --- a/src/NadekoBot/Modules/Administration/Services/DiscordPermOverrideService.cs +++ b/src/NadekoBot/Modules/Administration/Services/DiscordPermOverrideService.cs @@ -41,7 +41,7 @@ public class DiscordPermOverrideService : INService, ILateBlocker public Task ExecuteOverrides(ICommandContext ctx, CommandInfo command, GuildPerm perms, IServiceProvider services) { - var rupa = new RequireUserPermissionAttribute((GuildPermission) perms); + var rupa = new RequireUserPermissionAttribute(perms); return rupa.CheckPermissionsAsync(ctx, command, services); } diff --git a/src/NadekoBot/Modules/Administration/Services/GameVoiceChannelService.cs b/src/NadekoBot/Modules/Administration/Services/GameVoiceChannelService.cs index 7e62c8c61..5bac97b6c 100644 --- a/src/NadekoBot/Modules/Administration/Services/GameVoiceChannelService.cs +++ b/src/NadekoBot/Modules/Administration/Services/GameVoiceChannelService.cs @@ -6,7 +6,7 @@ namespace NadekoBot.Modules.Administration.Services; // todo if any activity... public class GameVoiceChannelService : INService { - public ConcurrentHashSet GameVoiceChannels { get; } = new ConcurrentHashSet(); + public ConcurrentHashSet GameVoiceChannels { get; } = new(); private readonly DbService _db; private readonly DiscordSocketClient _client; @@ -84,7 +84,7 @@ public class GameVoiceChannelService : INService { try { - if (!(usr is SocketGuildUser gUser)) + if (usr is not SocketGuildUser gUser) return; var game = gUser.Activities.FirstOrDefault()?.Name; diff --git a/src/NadekoBot/Modules/Administration/Services/GuildTimezoneService.cs b/src/NadekoBot/Modules/Administration/Services/GuildTimezoneService.cs index 0d9f289dc..a58ed0559 100644 --- a/src/NadekoBot/Modules/Administration/Services/GuildTimezoneService.cs +++ b/src/NadekoBot/Modules/Administration/Services/GuildTimezoneService.cs @@ -5,7 +5,7 @@ namespace NadekoBot.Modules.Administration.Services; public class GuildTimezoneService : INService { - public static ConcurrentDictionary AllServices { get; } = new ConcurrentDictionary(); + public static ConcurrentDictionary AllServices { get; } = new(); private readonly ConcurrentDictionary _timezones; private readonly DbService _db; diff --git a/src/NadekoBot/Modules/Administration/Services/ImageOnlyChannelService.cs b/src/NadekoBot/Modules/Administration/Services/ImageOnlyChannelService.cs index 997330ffd..f8f4b14ce 100644 --- a/src/NadekoBot/Modules/Administration/Services/ImageOnlyChannelService.cs +++ b/src/NadekoBot/Modules/Administration/Services/ImageOnlyChannelService.cs @@ -14,7 +14,7 @@ public sealed class ImageOnlyChannelService : IEarlyBehavior private readonly DbService _db; private readonly ConcurrentDictionary> _enabledOn; - private Channel _deleteQueue = Channel.CreateBounded(new BoundedChannelOptions(100) + private readonly Channel _deleteQueue = Channel.CreateBounded(new BoundedChannelOptions(100) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true, @@ -74,8 +74,8 @@ public sealed class ImageOnlyChannelService : IEarlyBehavior var newState = false; using var uow = _db.GetDbContext(); if (forceDisable - || _enabledOn.TryGetValue(guildId, out var channels) - && channels.TryRemove(channelId)) + || (_enabledOn.TryGetValue(guildId, out var channels) + && channels.TryRemove(channelId))) { uow.ImageOnlyChannels.Delete(x => x.ChannelId == channelId); } diff --git a/src/NadekoBot/Modules/Administration/Services/LogCommandService.cs b/src/NadekoBot/Modules/Administration/Services/LogCommandService.cs index 9644f3551..ab2a28823 100644 --- a/src/NadekoBot/Modules/Administration/Services/LogCommandService.cs +++ b/src/NadekoBot/Modules/Administration/Services/LogCommandService.cs @@ -49,8 +49,7 @@ public sealed class LogCommandService : ILogCommandService public ConcurrentDictionary GuildLogSettings { get; } - private ConcurrentDictionary> PresenceUpdates { get; } = - new ConcurrentDictionary>(); + private ConcurrentDictionary> PresenceUpdates { get; } = new(); private readonly Timer _timerReference; private readonly IBotStrings _strings; @@ -62,7 +61,7 @@ public sealed class LogCommandService : ILogCommandService private readonly IMemoryCache _memoryCache; private readonly Timer _clearTimer; - private readonly ConcurrentHashSet _ignoreMessageIds = new ConcurrentHashSet(); + private readonly ConcurrentHashSet _ignoreMessageIds = new(); public LogCommandService(DiscordSocketClient client, IBotStrings strings, DbService db, MuteService mute, ProtectionService prot, GuildTimezoneService tz, @@ -218,7 +217,7 @@ public sealed class LogCommandService : ILogCommandService logSetting.LogVoicePresenceId = logSetting.UserMutedId = logSetting.LogVoicePresenceTTSId = - value ? channelId : (ulong?) null; + value ? channelId : null; ; await uow.SaveChangesAsync(); GuildLogSettings.AddOrUpdate(guildId, id => logSetting, (id, old) => logSetting); @@ -231,7 +230,7 @@ public sealed class LogCommandService : ILogCommandService { try { - if (!(uAfter is SocketGuildUser after)) + if (uAfter is not SocketGuildUser after) return; var g = after.Guild; @@ -359,7 +358,7 @@ public sealed class LogCommandService : ILogCommandService { try { - if (!(iusr is IGuildUser usr)) + if (iusr is not IGuildUser usr) return; var beforeVch = before.VoiceChannel; @@ -673,7 +672,7 @@ public sealed class LogCommandService : ILogCommandService { try { - if (!(cbefore is IGuildChannel before)) + if (cbefore is not IGuildChannel before) return; var after = (IGuildChannel) cafter; @@ -726,7 +725,7 @@ public sealed class LogCommandService : ILogCommandService { try { - if (!(ich is IGuildChannel ch)) + if (ich is not IGuildChannel ch) return; if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out var logSetting) @@ -766,7 +765,7 @@ public sealed class LogCommandService : ILogCommandService { try { - if (!(ich is IGuildChannel ch)) + if (ich is not IGuildChannel ch) return; if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out var logSetting) @@ -805,7 +804,7 @@ public sealed class LogCommandService : ILogCommandService { try { - if (!(iusr is IGuildUser usr) || usr.IsBot) + if (iusr is not IGuildUser usr || usr.IsBot) return; var beforeVch = before.VoiceChannel; @@ -1024,7 +1023,7 @@ public sealed class LogCommandService : ILogCommandService return; var ch = optCh.Value; - if (!(ch is ITextChannel channel)) + if (ch is not ITextChannel channel) return; if (!GuildLogSettings.TryGetValue(channel.Guild.Id, out var logSetting) @@ -1069,14 +1068,14 @@ public sealed class LogCommandService : ILogCommandService { try { - if (!(imsg2 is IUserMessage after) || after.IsAuthor(_client)) + if (imsg2 is not IUserMessage after || after.IsAuthor(_client)) return; var before = (optmsg.HasValue ? optmsg.Value : null) as IUserMessage; if (before is null) return; - if (!(ch is ITextChannel channel)) + if (ch is not ITextChannel channel) return; if (before.Content == after.Content) diff --git a/src/NadekoBot/Modules/Administration/Services/MuteService.cs b/src/NadekoBot/Modules/Administration/Services/MuteService.cs index 0ac94ff53..3b9365f2e 100644 --- a/src/NadekoBot/Modules/Administration/Services/MuteService.cs +++ b/src/NadekoBot/Modules/Administration/Services/MuteService.cs @@ -17,14 +17,13 @@ public class MuteService : INService public ConcurrentDictionary GuildMuteRoles { get; } public ConcurrentDictionary> MutedUsers { get; } - public ConcurrentDictionary> Un_Timers { get; } - = new ConcurrentDictionary>(); + public ConcurrentDictionary> Un_Timers { get; } = new(); public event Action UserMuted = delegate { }; public event Action UserUnmuted = delegate { }; private static readonly OverwritePermissions denyOverwrite = - new OverwritePermissions(addReactions: PermValue.Deny, sendMessages: PermValue.Deny, + new(addReactions: PermValue.Deny, sendMessages: PermValue.Deny, attachFiles: PermValue.Deny); private readonly DiscordSocketClient _client; diff --git a/src/NadekoBot/Modules/Administration/Services/ProtectionService.cs b/src/NadekoBot/Modules/Administration/Services/ProtectionService.cs index 57f43f8c9..c623dde7f 100644 --- a/src/NadekoBot/Modules/Administration/Services/ProtectionService.cs +++ b/src/NadekoBot/Modules/Administration/Services/ProtectionService.cs @@ -8,14 +8,11 @@ namespace NadekoBot.Modules.Administration.Services; public class ProtectionService : INService { - private readonly ConcurrentDictionary _antiRaidGuilds - = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _antiRaidGuilds = new(); - private readonly ConcurrentDictionary _antiSpamGuilds - = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _antiSpamGuilds = new(); - private readonly ConcurrentDictionary _antiAltGuilds - = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _antiAltGuilds = new(); public event Func OnAntiProtectionTriggered = delegate { return Task.CompletedTask; }; @@ -171,7 +168,7 @@ public class ProtectionService : INService try { - if (!(maybeStats is { } stats) || !stats.RaidUsers.Add(user)) + if (maybeStats is not { } stats || !stats.RaidUsers.Add(user)) return; ++stats.UsersCount; @@ -201,10 +198,10 @@ public class ProtectionService : INService private Task HandleAntiSpam(SocketMessage arg) { - if (!(arg is SocketUserMessage msg) || msg.Author.IsBot) + if (arg is not SocketUserMessage msg || msg.Author.IsBot) return Task.CompletedTask; - if (!(msg.Channel is ITextChannel channel)) + if (msg.Channel is not ITextChannel channel) return Task.CompletedTask; var _ = Task.Run(async () => { diff --git a/src/NadekoBot/Modules/Administration/Services/PruneService.cs b/src/NadekoBot/Modules/Administration/Services/PruneService.cs index f59e2e462..b3bdfd3c3 100644 --- a/src/NadekoBot/Modules/Administration/Services/PruneService.cs +++ b/src/NadekoBot/Modules/Administration/Services/PruneService.cs @@ -5,7 +5,7 @@ namespace NadekoBot.Modules.Administration.Services; public class PruneService : INService { //channelids where prunes are currently occuring - private ConcurrentHashSet _pruningGuilds = new ConcurrentHashSet(); + private readonly ConcurrentHashSet _pruningGuilds = new(); private readonly TimeSpan twoWeeks = TimeSpan.FromDays(14); private readonly ILogCommandService _logService; diff --git a/src/NadekoBot/Modules/Administration/Services/SelfService.cs b/src/NadekoBot/Modules/Administration/Services/SelfService.cs index 4af3938a2..31c1fdc77 100644 --- a/src/NadekoBot/Modules/Administration/Services/SelfService.cs +++ b/src/NadekoBot/Modules/Administration/Services/SelfService.cs @@ -17,8 +17,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService private ImmutableDictionary ownerChannels = new Dictionary().ToImmutableDictionary(); - private ConcurrentDictionary> _autoCommands = - new ConcurrentDictionary>(); + private ConcurrentDictionary> _autoCommands = new(); private readonly IImageCache _imgs; private readonly IHttpClientFactory _httpFactory; diff --git a/src/NadekoBot/Modules/Administration/Services/UserPunishService.cs b/src/NadekoBot/Modules/Administration/Services/UserPunishService.cs index b6e68cf36..1340ff44f 100644 --- a/src/NadekoBot/Modules/Administration/Services/UserPunishService.cs +++ b/src/NadekoBot/Modules/Administration/Services/UserPunishService.cs @@ -312,7 +312,7 @@ WHERE GuildId={guildId} // these 3 don't make sense with time if ((punish == PunishmentAction.Softban || punish == PunishmentAction.Kick || punish == PunishmentAction.RemoveRoles) && time != null) return false; - if (number <= 0 || time != null && time.Time > TimeSpan.FromDays(49)) + if (number <= 0 || (time != null && time.Time > TimeSpan.FromDays(49))) return false; using (var uow = _db.GetDbContext()) diff --git a/src/NadekoBot/Modules/Administration/UserPunishCommands.cs b/src/NadekoBot/Modules/Administration/UserPunishCommands.cs index 371d5a28e..6d228e71f 100644 --- a/src/NadekoBot/Modules/Administration/UserPunishCommands.cs +++ b/src/NadekoBot/Modules/Administration/UserPunishCommands.cs @@ -31,7 +31,7 @@ public partial class Administration // bot can't punish a user who is higher in the hierarchy. Discord will return 403 // moderator can be owner, in which case role hierarchy doesn't matter // otherwise, moderator has to have a higher role - if (botMaxRole <= targetMaxRole || ctx.User.Id != ownerId && targetMaxRole >= modMaxRole || target.Id == ownerId) + if (botMaxRole <= targetMaxRole || (ctx.User.Id != ownerId && targetMaxRole >= modMaxRole) || target.Id == ownerId) { await ReplyErrorLocalizedAsync(strs.hierarchy); return false; diff --git a/src/NadekoBot/Modules/CustomReactions/Common/ExportedExpr.cs b/src/NadekoBot/Modules/CustomReactions/Common/ExportedExpr.cs index 8b579a0d1..213d7cb3e 100644 --- a/src/NadekoBot/Modules/CustomReactions/Common/ExportedExpr.cs +++ b/src/NadekoBot/Modules/CustomReactions/Common/ExportedExpr.cs @@ -13,7 +13,7 @@ public class ExportedExpr public string[] React; public static ExportedExpr FromModel(CustomReaction cr) - => new ExportedExpr() + => new() { Res = cr.Response, Id = ((kwum)cr.Id).ToString(), diff --git a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs index 33ca8ceb7..1ed7dea2a 100644 --- a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs @@ -13,8 +13,8 @@ public class CustomReactions : NadekoModule _clientFactory = clientFactory; } - private bool AdminInGuildOrOwnerInDm() => ctx.Guild is null && _creds.IsOwner(ctx.User) - || ctx.Guild != null && ((IGuildUser)ctx.User).GuildPermissions.Administrator; + private bool AdminInGuildOrOwnerInDm() => (ctx.Guild is null && _creds.IsOwner(ctx.User)) + || (ctx.Guild != null && ((IGuildUser)ctx.User).GuildPermissions.Administrator); [NadekoCommand, Aliases] public async Task AddCustReact(string key, [Leftover] string message) @@ -33,7 +33,7 @@ public class CustomReactions : NadekoModule await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor() .WithTitle(GetText(strs.new_cust_react)) - .WithDescription($"#{(kwum)cr.Id}") + .WithDescription($"#{cr.Id}") .AddField(GetText(strs.trigger), key) .AddField(GetText(strs.response), message.Length > 1024 ? GetText(strs.redacted_too_long) : message) ).ConfigureAwait(false); @@ -46,13 +46,13 @@ public class CustomReactions : NadekoModule if (string.IsNullOrWhiteSpace(message) || id < 0) return; - if (channel is null && !_creds.IsOwner(ctx.User) || channel != null && !((IGuildUser)ctx.User).GuildPermissions.Administrator) + if ((channel is null && !_creds.IsOwner(ctx.User)) || (channel != null && !((IGuildUser)ctx.User).GuildPermissions.Administrator)) { await ReplyErrorLocalizedAsync(strs.insuff_perms).ConfigureAwait(false); return; } - var cr = await _service.EditAsync(ctx.Guild?.Id, (int)id, message).ConfigureAwait(false); + var cr = await _service.EditAsync(ctx.Guild?.Id, id, message).ConfigureAwait(false); if (cr != null) { await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor() @@ -112,7 +112,7 @@ public class CustomReactions : NadekoModule [NadekoCommand, Aliases] public async Task ShowCustReact(kwum id) { - var found = _service.GetCustomReaction(ctx.Guild?.Id, (int)id); + var found = _service.GetCustomReaction(ctx.Guild?.Id, id); if (found is null) { @@ -138,7 +138,7 @@ public class CustomReactions : NadekoModule return; } - var cr = await _service.DeleteAsync(ctx.Guild?.Id, (int)id); + var cr = await _service.DeleteAsync(ctx.Guild?.Id, id); if (cr != null) { diff --git a/src/NadekoBot/Modules/CustomReactions/Services/CustomReactionsService.cs b/src/NadekoBot/Modules/CustomReactions/Services/CustomReactionsService.cs index 068744352..60981066f 100644 --- a/src/NadekoBot/Modules/CustomReactions/Services/CustomReactionsService.cs +++ b/src/NadekoBot/Modules/CustomReactions/Services/CustomReactionsService.cs @@ -22,12 +22,12 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor Message, } - private readonly object _gcrWriteLock = new object(); + private readonly object _gcrWriteLock = new(); - private readonly TypedKey _gcrAddedKey = new TypedKey("gcr.added"); - private readonly TypedKey _gcrDeletedkey = new TypedKey("gcr.deleted"); - private readonly TypedKey _gcrEditedKey = new TypedKey("gcr.edited"); - private readonly TypedKey _crsReloadedKey = new TypedKey("crs.reloaded"); + private readonly TypedKey _gcrAddedKey = new("gcr.added"); + private readonly TypedKey _gcrDeletedkey = new("gcr.deleted"); + private readonly TypedKey _gcrEditedKey = new("gcr.edited"); + private readonly TypedKey _crsReloadedKey = new("crs.reloaded"); private const string MentionPh = "%bot.mention%"; // it is perfectly fine to have global customreactions as an array @@ -119,8 +119,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor public Task OnReadyAsync() => ReloadInternal(_bot.GetCurrentGuildIds()); - private ValueTask OnCrsShouldReload(bool _) - => new ValueTask(ReloadInternal(_bot.GetCurrentGuildIds())); + private ValueTask OnCrsShouldReload(bool _) => new(ReloadInternal(_bot.GetCurrentGuildIds())); private ValueTask OnGcrAdded(CustomReaction c) { @@ -257,7 +256,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor if (toDelete is null) return null; - if (toDelete.IsGlobal() && guildId is null || guildId == toDelete.GuildId) + if ((toDelete.IsGlobal() && guildId is null) || guildId == toDelete.GuildId) { uow.CustomReactions.Remove(toDelete); await uow.SaveChangesAsync(); @@ -290,7 +289,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor if (!ready) return null; - if (!(umsg.Channel is SocketTextChannel channel)) + if (umsg.Channel is not SocketTextChannel channel) return null; var content = umsg.Content.Trim().ToLowerInvariant(); diff --git a/src/NadekoBot/Modules/Gambling/AnimalRacingCommands.cs b/src/NadekoBot/Modules/Gambling/AnimalRacingCommands.cs index 27e59d9f8..d1b38811d 100644 --- a/src/NadekoBot/Modules/Gambling/AnimalRacingCommands.cs +++ b/src/NadekoBot/Modules/Gambling/AnimalRacingCommands.cs @@ -70,7 +70,7 @@ public partial class Gambling GetText(strs.animal_race_won_money( Format.Bold(winner.Username), winner.Animal.Icon, - race.FinishedUsers[0].Bet * (race.Users.Count - 1) + CurrencySign))); + (race.FinishedUsers[0].Bet * (race.Users.Count - 1)) + CurrencySign))); } else { diff --git a/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/AnimalRace.cs b/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/AnimalRace.cs index dc22a9b9c..36c68aa7f 100644 --- a/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/AnimalRace.cs +++ b/src/NadekoBot/Modules/Gambling/Common/AnimalRacing/AnimalRace.cs @@ -20,10 +20,10 @@ public sealed class AnimalRace : IDisposable public event Func OnEnded = delegate { return Task.CompletedTask; }; public IReadOnlyCollection Users => _users.ToList(); - public List FinishedUsers { get; } = new List(); + public List FinishedUsers { get; } = new(); - private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1); - private readonly HashSet _users = new HashSet(); + private readonly SemaphoreSlim _locker = new(1, 1); + private readonly HashSet _users = new(); private readonly ICurrencyService _currency; private readonly RaceOptions _options; private readonly Queue _animalsQueue; diff --git a/src/NadekoBot/Modules/Gambling/Common/Blackjack/Blackjack.cs b/src/NadekoBot/Modules/Gambling/Common/Blackjack/Blackjack.cs index fad6161a7..865940206 100644 --- a/src/NadekoBot/Modules/Gambling/Common/Blackjack/Blackjack.cs +++ b/src/NadekoBot/Modules/Gambling/Common/Blackjack/Blackjack.cs @@ -13,7 +13,7 @@ public class Blackjack public Dealer Dealer { get; set; } - public List Players { get; set; } = new List(); + public List Players { get; set; } = new(); public GameState State { get; set; } = GameState.Starting; public User CurrentUser { get; private set; } @@ -24,7 +24,7 @@ public class Blackjack public event Func StateUpdated; public event Func GameEnded; - private readonly SemaphoreSlim locker = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim locker = new(1, 1); public Blackjack(ICurrencyService cs, DbService db) { @@ -174,7 +174,7 @@ public class Blackjack { var hw = Dealer.GetHandValue(); while (hw < 17 - || hw == 17 && Dealer.Cards.Count(x => x.Number == 1) > (Dealer.GetRawHandValue() - 17) / 10)// hit on soft 17 + || (hw == 17 && Dealer.Cards.Count(x => x.Number == 1) > (Dealer.GetRawHandValue() - 17) / 10))// hit on soft 17 { /* Dealer has A 6 diff --git a/src/NadekoBot/Modules/Gambling/Common/Blackjack/Player.cs b/src/NadekoBot/Modules/Gambling/Common/Blackjack/Player.cs index f04ec58ac..d75bd546d 100644 --- a/src/NadekoBot/Modules/Gambling/Common/Blackjack/Player.cs +++ b/src/NadekoBot/Modules/Gambling/Common/Blackjack/Player.cs @@ -2,7 +2,7 @@ public abstract class Player { - public List Cards { get; } = new List(); + public List Cards { get; } = new(); public int GetHandValue() { diff --git a/src/NadekoBot/Modules/Gambling/Common/CurrencyRaffleGame.cs b/src/NadekoBot/Modules/Gambling/Common/CurrencyRaffleGame.cs index e8a98b4e4..823c5772c 100644 --- a/src/NadekoBot/Modules/Gambling/Common/CurrencyRaffleGame.cs +++ b/src/NadekoBot/Modules/Gambling/Common/CurrencyRaffleGame.cs @@ -25,7 +25,7 @@ public class CurrencyRaffleGame } } - private readonly HashSet _users = new HashSet(); + private readonly HashSet _users = new(); public IEnumerable Users => _users; public Type GameType { get; } diff --git a/src/NadekoBot/Modules/Gambling/Common/Deck.cs b/src/NadekoBot/Modules/Gambling/Common/Deck.cs index 5cadbab52..ee31e52b2 100644 --- a/src/NadekoBot/Modules/Gambling/Common/Deck.cs +++ b/src/NadekoBot/Modules/Gambling/Common/Deck.cs @@ -20,7 +20,7 @@ public class QuadDeck : Deck public class Deck { - private static readonly Dictionary cardNames = new Dictionary() { + private static readonly Dictionary _cardNames = new() { { 1, "Ace" }, { 2, "Two" }, { 3, "Three" }, @@ -35,7 +35,7 @@ public class Deck { 12, "Queen" }, { 13, "King" } }; - private static Dictionary, bool>> handValues; + private static Dictionary, bool>> _handValues; public enum CardSuit @@ -75,15 +75,14 @@ public class Deck this.Number = cardNum; } - public string GetValueText() => cardNames[Number]; + public string GetValueText() => _cardNames[Number]; - public override string ToString() => cardNames[Number] + " Of " + Suit; + public override string ToString() => _cardNames[Number] + " Of " + Suit; public int CompareTo(object obj) { - if (!(obj is Card)) return 0; - var c = (Card)obj; - return this.Number - c.Number; + if (obj is not Card card) return 0; + return this.Number - card.Number; } public static Card Parse(string input) @@ -133,7 +132,7 @@ public class Deck {CardSuit.Spades, "♠"}, {CardSuit.Hearts, "♥"}, }; - private static IReadOnlyDictionary _suitCharToSuit = new Dictionary + private static readonly IReadOnlyDictionary _suitCharToSuit = new Dictionary { {"♦", CardSuit.Diamonds }, {"d", CardSuit.Diamonds }, @@ -144,7 +143,7 @@ public class Deck {"♥", CardSuit.Hearts }, {"h", CardSuit.Hearts }, }; - private static IReadOnlyDictionary _numberCharToNumber = new Dictionary() + private static readonly IReadOnlyDictionary _numberCharToNumber = new Dictionary() { {'a', 1 }, {'2', 2 }, @@ -200,7 +199,7 @@ public class Deck } } } - private Random r = new NadekoRandom(); + private readonly Random _r = new NadekoRandom(); /// /// Take a card from the pool, you either take it from the top if the deck is shuffled, or from a random place if the deck is in the default order. /// @@ -211,7 +210,7 @@ public class Deck Restart(); //you can either do this if your deck is not shuffled - var num = r.Next(0, CardPool.Count); + var num = _r.Next(0, CardPool.Count); var c = CardPool[num]; CardPool.RemoveAt(num); return c; @@ -230,73 +229,73 @@ public class Deck { if (CardPool.Count <= 1) return; var orderedPool = CardPool.Shuffle(); - CardPool = CardPool as List ?? orderedPool.ToList(); + CardPool ??= orderedPool.ToList(); } public override string ToString() => string.Concat(CardPool.Select(c => c.ToString())) + Environment.NewLine; private static void InitHandValues() { - bool hasPair(List cards) => cards.GroupBy(card => card.Number) + bool HasPair(List cards) => cards.GroupBy(card => card.Number) .Count(group => group.Count() == 2) == 1; - bool isPair(List cards) => cards.GroupBy(card => card.Number) + bool IsPair(List cards) => cards.GroupBy(card => card.Number) .Count(group => group.Count() == 3) == 0 - && hasPair(cards); + && HasPair(cards); - bool isTwoPair(List cards) => cards.GroupBy(card => card.Number) + bool IsTwoPair(List cards) => cards.GroupBy(card => card.Number) .Count(group => group.Count() == 2) == 2; - bool isStraight(List cards) + bool IsStraight(List cards) { if (cards.GroupBy(card => card.Number).Count() != cards.Count()) return false; - var toReturn = cards.Max(card => (int)card.Number) - - cards.Min(card => (int)card.Number) == 4; + var toReturn = cards.Max(card => card.Number) + - cards.Min(card => card.Number) == 4; if (toReturn || cards.All(c => c.Number != 1)) return toReturn; var newCards = cards.Select(c => c.Number == 1 ? new(c.Suit, 14) : c); - return newCards.Max(card => (int)card.Number) - - newCards.Min(card => (int)card.Number) == 4; + return newCards.Max(card => card.Number) + - newCards.Min(card => card.Number) == 4; } - bool hasThreeOfKind(List cards) => cards.GroupBy(card => card.Number) + bool HasThreeOfKind(List cards) => cards.GroupBy(card => card.Number) .Any(group => group.Count() == 3); - bool isThreeOfKind(List cards) => hasThreeOfKind(cards) && !hasPair(cards); + bool IsThreeOfKind(List cards) => HasThreeOfKind(cards) && !HasPair(cards); - bool isFlush(List cards) => cards.GroupBy(card => card.Suit).Count() == 1; + bool IsFlush(List cards) => cards.GroupBy(card => card.Suit).Count() == 1; - bool isFourOfKind(List cards) => cards.GroupBy(card => card.Number) + bool IsFourOfKind(List cards) => cards.GroupBy(card => card.Number) .Any(group => group.Count() == 4); - bool isFullHouse(List cards) => hasPair(cards) && hasThreeOfKind(cards); + bool IsFullHouse(List cards) => HasPair(cards) && HasThreeOfKind(cards); - bool hasStraightFlush(List cards) => isFlush(cards) && isStraight(cards); + bool HasStraightFlush(List cards) => IsFlush(cards) && IsStraight(cards); - bool isRoyalFlush(List cards) => cards.Min(card => card.Number) == 1 && + bool IsRoyalFlush(List cards) => cards.Min(card => card.Number) == 1 && cards.Max(card => card.Number) == 13 - && hasStraightFlush(cards); + && HasStraightFlush(cards); - bool isStraightFlush(List cards) => hasStraightFlush(cards) && !isRoyalFlush(cards); + bool IsStraightFlush(List cards) => HasStraightFlush(cards) && !IsRoyalFlush(cards); - handValues = new() + _handValues = new() { - { "Royal Flush", isRoyalFlush }, - { "Straight Flush", isStraightFlush }, - { "Four Of A Kind", isFourOfKind }, - { "Full House", isFullHouse }, - { "Flush", isFlush }, - { "Straight", isStraight }, - { "Three Of A Kind", isThreeOfKind }, - { "Two Pairs", isTwoPair }, - { "A Pair", isPair } + { "Royal Flush", IsRoyalFlush }, + { "Straight Flush", IsStraightFlush }, + { "Four Of A Kind", IsFourOfKind }, + { "Full House", IsFullHouse }, + { "Flush", IsFlush }, + { "Straight", IsStraight }, + { "Three Of A Kind", IsThreeOfKind }, + { "Two Pairs", IsTwoPair }, + { "A Pair", IsPair } }; } public static string GetHandValue(List cards) { - if (handValues is null) + if (_handValues is null) InitHandValues(); - foreach (var kvp in handValues.Where(x => x.Value(cards))) + foreach (var kvp in _handValues.Where(x => x.Value(cards))) { return kvp.Key; } diff --git a/src/NadekoBot/Modules/Gambling/Common/Events/GameStatusEvent.cs b/src/NadekoBot/Modules/Gambling/Common/Events/GameStatusEvent.cs index bf66440cd..473f8c623 100644 --- a/src/NadekoBot/Modules/Gambling/Common/Events/GameStatusEvent.cs +++ b/src/NadekoBot/Modules/Gambling/Common/Events/GameStatusEvent.cs @@ -18,8 +18,8 @@ public class GameStatusEvent : ICurrencyEvent private readonly Func _embedFunc; private readonly bool _isPotLimited; private readonly ITextChannel _channel; - private readonly ConcurrentHashSet _awardedUsers = new ConcurrentHashSet(); - private readonly ConcurrentQueue _toAward = new ConcurrentQueue(); + private readonly ConcurrentHashSet _awardedUsers = new(); + private readonly ConcurrentQueue _toAward = new(); private readonly Timer _t; private readonly Timer _timeout = null; private readonly EventOptions _opts; @@ -127,7 +127,7 @@ public class GameStatusEvent : ICurrencyEvent } } - private readonly object stopLock = new object(); + private readonly object stopLock = new(); public async Task StopEvent() { await Task.Yield(); @@ -150,7 +150,7 @@ public class GameStatusEvent : ICurrencyEvent { var _ = Task.Run(async () => { - if (!(msg.Author is IGuildUser gu) // no unknown users, as they could be bots, or alts + if (msg.Author is not IGuildUser gu // no unknown users, as they could be bots, or alts || gu.IsBot // no bots || msg.Content != _code // code has to be the same || (DateTime.UtcNow - gu.CreatedAt).TotalDays <= 5) // no recently created accounts @@ -178,7 +178,7 @@ public class GameStatusEvent : ICurrencyEvent return Task.CompletedTask; } - private readonly object potLock = new object(); + private readonly object potLock = new(); private bool TryTakeFromPot() { if (_isPotLimited) diff --git a/src/NadekoBot/Modules/Gambling/Common/Events/ReactionEvent.cs b/src/NadekoBot/Modules/Gambling/Common/Events/ReactionEvent.cs index d6cf739e9..e7ae08bae 100644 --- a/src/NadekoBot/Modules/Gambling/Common/Events/ReactionEvent.cs +++ b/src/NadekoBot/Modules/Gambling/Common/Events/ReactionEvent.cs @@ -19,8 +19,8 @@ public class ReactionEvent : ICurrencyEvent private readonly Func _embedFunc; private readonly bool _isPotLimited; private readonly ITextChannel _channel; - private readonly ConcurrentHashSet _awardedUsers = new ConcurrentHashSet(); - private readonly ConcurrentQueue _toAward = new ConcurrentQueue(); + private readonly ConcurrentHashSet _awardedUsers = new(); + private readonly ConcurrentQueue _toAward = new(); private readonly Timer _t; private readonly Timer _timeout = null; private readonly bool _noRecentlyJoinedServer; @@ -130,7 +130,7 @@ public class ReactionEvent : ICurrencyEvent } } - private readonly object stopLock = new object(); + private readonly object stopLock = new(); public async Task StopEvent() { await Task.Yield(); @@ -160,8 +160,8 @@ public class ReactionEvent : ICurrencyEvent || msg.Id != _msg.Id // same message || gu.IsBot // no bots || (DateTime.UtcNow - gu.CreatedAt).TotalDays <= 5 // no recently created accounts - || _noRecentlyJoinedServer && // if specified, no users who joined the server in the last 24h - (gu.JoinedAt is null || (DateTime.UtcNow - gu.JoinedAt.Value).TotalDays < 1)) // and no users for who we don't know when they joined + || (_noRecentlyJoinedServer && // if specified, no users who joined the server in the last 24h + (gu.JoinedAt is null || (DateTime.UtcNow - gu.JoinedAt.Value).TotalDays < 1))) // and no users for who we don't know when they joined { return; } @@ -177,7 +177,7 @@ public class ReactionEvent : ICurrencyEvent return Task.CompletedTask; } - private readonly object potLock = new object(); + private readonly object potLock = new(); private bool TryTakeFromPot() { if (_isPotLimited) diff --git a/src/NadekoBot/Modules/Gambling/Common/GamblingConfig.cs b/src/NadekoBot/Modules/Gambling/Common/GamblingConfig.cs index 6837f97b8..04de1c666 100644 --- a/src/NadekoBot/Modules/Gambling/Common/GamblingConfig.cs +++ b/src/NadekoBot/Modules/Gambling/Common/GamblingConfig.cs @@ -108,9 +108,9 @@ Doesn't have to be ordered.")] { Pairs = new BetRollPair[] { - new BetRollPair { WhenAbove = 99, MultiplyBy = 10 }, - new BetRollPair { WhenAbove = 90, MultiplyBy = 4 }, - new BetRollPair { WhenAbove = 66, MultiplyBy = 2 } + new() { WhenAbove = 99, MultiplyBy = 10 }, + new() { WhenAbove = 90, MultiplyBy = 4 }, + new() { WhenAbove = 66, MultiplyBy = 2 } }; } } @@ -184,11 +184,11 @@ public sealed partial class WaifuConfig [Comment(@"Minimum price a waifu can have")] public int MinPrice { get; set; } = 50; - public MultipliersData Multipliers { get; set; } = new MultipliersData(); + public MultipliersData Multipliers { get; set; } = new(); [Comment(@"List of items available for gifting. If negative is true, gift will instead reduce waifu value.")] - public List Items { get; set; } = new List(); + public List Items { get; set; } = new(); public WaifuConfig() { diff --git a/src/NadekoBot/Modules/Gambling/Common/RollDuelGame.cs b/src/NadekoBot/Modules/Gambling/Common/RollDuelGame.cs index a54ef451e..eaf3c6296 100644 --- a/src/NadekoBot/Modules/Gambling/Common/RollDuelGame.cs +++ b/src/NadekoBot/Modules/Gambling/Common/RollDuelGame.cs @@ -26,13 +26,13 @@ public class RollDuelGame } private readonly Timer _timeoutTimer; - private readonly NadekoRandom _rng = new NadekoRandom(); - private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1); + private readonly NadekoRandom _rng = new(); + private readonly SemaphoreSlim _locker = new(1, 1); public event Func OnGameTick; public event Func OnEnded; - public List<(int, int)> Rolls { get; } = new List<(int, int)>(); + public List<(int, int)> Rolls { get; } = new(); public State CurrentState { get; private set; } public ulong Winner { get; private set; } @@ -111,7 +111,7 @@ public class RollDuelGame await _cs.AddAsync(Winner, "Roll Duel win", won) .ConfigureAwait(false); - await _cs.AddAsync(_botId, "Roll Duel fee", Amount * 2 - won) + await _cs.AddAsync(_botId, "Roll Duel fee", (Amount * 2) - won) .ConfigureAwait(false); } try { await (OnGameTick?.Invoke(this)).ConfigureAwait(false); } catch { } diff --git a/src/NadekoBot/Modules/Gambling/Common/SlotResponse.cs b/src/NadekoBot/Modules/Gambling/Common/SlotResponse.cs index 57220166f..680bdd980 100644 --- a/src/NadekoBot/Modules/Gambling/Common/SlotResponse.cs +++ b/src/NadekoBot/Modules/Gambling/Common/SlotResponse.cs @@ -4,6 +4,6 @@ public class SlotResponse { public float Multiplier { get; set; } public long Won { get; set; } - public List Rolls { get; set; } = new List(); + public List Rolls { get; set; } = new(); public GamblingError Error { get; set; } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs b/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs index 04f3b84bd..104c781cc 100644 --- a/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs +++ b/src/NadekoBot/Modules/Gambling/Connect4/Connect4.cs @@ -52,7 +52,7 @@ public sealed class Connect4Game : IDisposable public event Func OnGameFailedToStart; public event Func OnGameEnded; - private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim _locker = new(1, 1); private readonly Options _options; private readonly ICurrencyService _cs; private readonly NadekoRandom _rng; @@ -154,8 +154,8 @@ public sealed class Connect4Game : IDisposable if (CurrentPhase == Phase.Ended || CurrentPhase == Phase.Joining) return false; - if (!(_players[0].Value.UserId == userId && CurrentPhase == Phase.P1Move - || _players[1].Value.UserId == userId && CurrentPhase == Phase.P2Move)) + 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 @@ -187,12 +187,12 @@ public sealed class Connect4Game : IDisposable if (CurrentPhase == Phase.Ended) break; - var first = _gameState[i + j * NumberOfRows]; + var first = _gameState[i + (j * NumberOfRows)]; if (first != Field.Empty) { for (var k = 1; k < 4; k++) { - var next = _gameState[i + k + j * NumberOfRows]; + var next = _gameState[i + k + (j * NumberOfRows)]; if (next == first) { if (k == 3) @@ -217,12 +217,12 @@ public sealed class Connect4Game : IDisposable if (CurrentPhase == Phase.Ended) break; - var first = _gameState[j + i * NumberOfRows]; + var first = _gameState[j + (i * NumberOfRows)]; if (first != Field.Empty) { for (var k = 1; k < 4; k++) { - var next = _gameState[j + (i + k) * NumberOfRows]; + var next = _gameState[j + ((i + k) * NumberOfRows)]; if (next == first) if (k == 3) EndGame(Result.CurrentPlayerWon, CurrentPlayer.UserId); @@ -245,7 +245,7 @@ public sealed class Connect4Game : IDisposable if (CurrentPhase == Phase.Ended) break; - var first = _gameState[row + col * NumberOfRows]; + var first = _gameState[row + (col * NumberOfRows)]; if (first != Field.Empty) { @@ -264,7 +264,7 @@ public sealed class Connect4Game : IDisposable if (curCol < 0 || curCol >= NumberOfColumns) break; - var cur = _gameState[curRow + curCol * NumberOfRows]; + var cur = _gameState[curRow + (curCol * NumberOfRows)]; if (cur == first) same++; else break; @@ -291,7 +291,7 @@ public sealed class Connect4Game : IDisposable if (curCol < 0 || curCol >= NumberOfColumns) break; - var cur = _gameState[curRow + curCol * NumberOfRows]; + var cur = _gameState[curRow + (curCol * NumberOfRows)]; if (cur == first) same++; else break; diff --git a/src/NadekoBot/Modules/Gambling/Connect4Commands.cs b/src/NadekoBot/Modules/Gambling/Connect4Commands.cs index d7cf07456..515e7df4a 100644 --- a/src/NadekoBot/Modules/Gambling/Connect4Commands.cs +++ b/src/NadekoBot/Modules/Gambling/Connect4Commands.cs @@ -177,7 +177,7 @@ public partial class Gambling { for (var j = 0; j < Connect4Game.NumberOfColumns; j++) { - var cur = game.GameState[i + j * Connect4Game.NumberOfRows - 1]; + var cur = game.GameState[i + (j * Connect4Game.NumberOfRows) - 1]; if (cur == Connect4Game.Field.Empty) sb.Append("⚫"); //black circle diff --git a/src/NadekoBot/Modules/Gambling/DiceRollCommands.cs b/src/NadekoBot/Modules/Gambling/DiceRollCommands.cs index cddc61dc8..135684b99 100644 --- a/src/NadekoBot/Modules/Gambling/DiceRollCommands.cs +++ b/src/NadekoBot/Modules/Gambling/DiceRollCommands.cs @@ -10,8 +10,8 @@ public partial class Gambling [Group] public class DiceRollCommands : NadekoSubmodule { - private static readonly Regex dndRegex = new Regex(@"^(?\d+)d(?\d+)(?:\+(?\d+))?(?:\-(?\d+))?$", RegexOptions.Compiled); - private static readonly Regex fudgeRegex = new Regex(@"^(?\d+)d(?:F|f)$", RegexOptions.Compiled); + private static readonly Regex dndRegex = new(@"^(?\d+)d(?\d+)(?:\+(?\d+))?(?:\-(?\d+))?$", RegexOptions.Compiled); + private static readonly Regex fudgeRegex = new(@"^(?\d+)d(?:F|f)$", RegexOptions.Compiled); private static readonly char[] _fateRolls = { '-', ' ', '+' }; private readonly IImageCache _images; diff --git a/src/NadekoBot/Modules/Gambling/DrawCommands.cs b/src/NadekoBot/Modules/Gambling/DrawCommands.cs index a98d80f8a..dfc5c055e 100644 --- a/src/NadekoBot/Modules/Gambling/DrawCommands.cs +++ b/src/NadekoBot/Modules/Gambling/DrawCommands.cs @@ -10,7 +10,7 @@ public partial class Gambling [Group] public class DrawCommands : NadekoSubmodule { - private static readonly ConcurrentDictionary _allDecks = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary _allDecks = new(); private readonly IImageCache _images; public DrawCommands(IDataCache data) diff --git a/src/NadekoBot/Modules/Gambling/FlipCoinCommands.cs b/src/NadekoBot/Modules/Gambling/FlipCoinCommands.cs index 12df1b9b1..6a1731037 100644 --- a/src/NadekoBot/Modules/Gambling/FlipCoinCommands.cs +++ b/src/NadekoBot/Modules/Gambling/FlipCoinCommands.cs @@ -13,7 +13,7 @@ public partial class Gambling { private readonly IImageCache _images; private readonly ICurrencyService _cs; - private static readonly NadekoRandom rng = new NadekoRandom(); + private static readonly NadekoRandom rng = new(); public FlipCoinCommands(IDataCache data, ICurrencyService cs, GamblingConfigService gss) : base(gss) { diff --git a/src/NadekoBot/Modules/Gambling/Gambling.cs b/src/NadekoBot/Modules/Gambling/Gambling.cs index 6f1ab9f84..e32078223 100644 --- a/src/NadekoBot/Modules/Gambling/Gambling.cs +++ b/src/NadekoBot/Modules/Gambling/Gambling.cs @@ -574,7 +574,7 @@ public partial class Gambling : GamblingModule var usrStr = x.ToString().TrimTo(20, true); var j = i; - embed.AddField("#" + (9 * curPage + j + 1) + " " + usrStr, n(x.CurrencyAmount), true); + embed.AddField("#" + ((9 * curPage) + j + 1) + " " + usrStr, n(x.CurrencyAmount), true); } return embed; @@ -642,9 +642,9 @@ public partial class Gambling : GamblingModule embed.WithOkColor(); msg = GetText(strs.rps_draw(getRpsPick(pick))); } - else if (pick == RpsPick.Paper && nadekoPick == RpsPick.Rock || - pick == RpsPick.Rock && nadekoPick == RpsPick.Scissors || - pick == RpsPick.Scissors && nadekoPick == RpsPick.Paper) + else if ((pick == RpsPick.Paper && nadekoPick == RpsPick.Rock) || + (pick == RpsPick.Rock && nadekoPick == RpsPick.Scissors) || + (pick == RpsPick.Scissors && nadekoPick == RpsPick.Paper)) { amount = (long)(amount * base._config.BetFlip.Multiplier); await _cs.AddAsync(ctx.User.Id, diff --git a/src/NadekoBot/Modules/Gambling/Services/AnimalRaceService.cs b/src/NadekoBot/Modules/Gambling/Services/AnimalRaceService.cs index 887dc1e22..6e34ff486 100644 --- a/src/NadekoBot/Modules/Gambling/Services/AnimalRaceService.cs +++ b/src/NadekoBot/Modules/Gambling/Services/AnimalRaceService.cs @@ -4,5 +4,5 @@ namespace NadekoBot.Modules.Gambling.Services; public class AnimalRaceService : INService { - public ConcurrentDictionary AnimalRaces { get; } = new ConcurrentDictionary(); + public ConcurrentDictionary AnimalRaces { get; } = new(); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Gambling/Services/BlackJackService.cs b/src/NadekoBot/Modules/Gambling/Services/BlackJackService.cs index 81c4fc8e1..0e0f6dbd4 100644 --- a/src/NadekoBot/Modules/Gambling/Services/BlackJackService.cs +++ b/src/NadekoBot/Modules/Gambling/Services/BlackJackService.cs @@ -4,5 +4,5 @@ namespace NadekoBot.Modules.Gambling.Services; public class BlackJackService : INService { - public ConcurrentDictionary Games { get; } = new ConcurrentDictionary(); + public ConcurrentDictionary Games { get; } = new(); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Gambling/Services/CurrencyEventsService.cs b/src/NadekoBot/Modules/Gambling/Services/CurrencyEventsService.cs index 069d81aa8..04fba6c41 100644 --- a/src/NadekoBot/Modules/Gambling/Services/CurrencyEventsService.cs +++ b/src/NadekoBot/Modules/Gambling/Services/CurrencyEventsService.cs @@ -10,8 +10,7 @@ public class CurrencyEventsService : INService private readonly ICurrencyService _cs; private readonly GamblingConfigService _configService; - private readonly ConcurrentDictionary _events = - new ConcurrentDictionary(); + private readonly ConcurrentDictionary _events = new(); public CurrencyEventsService( diff --git a/src/NadekoBot/Modules/Gambling/Services/CurrencyRaffleService.cs b/src/NadekoBot/Modules/Gambling/Services/CurrencyRaffleService.cs index f68020676..346190c2d 100644 --- a/src/NadekoBot/Modules/Gambling/Services/CurrencyRaffleService.cs +++ b/src/NadekoBot/Modules/Gambling/Services/CurrencyRaffleService.cs @@ -9,11 +9,11 @@ public class CurrencyRaffleService : INService NotEnoughCurrency, AlreadyJoinedOrInvalidAmount } - private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim _locker = new(1, 1); private readonly DbService _db; private readonly ICurrencyService _cs; - public Dictionary Games { get; } = new Dictionary(); + public Dictionary Games { get; } = new(); public CurrencyRaffleService(DbService db, ICurrencyService cs) { diff --git a/src/NadekoBot/Modules/Gambling/Services/GamblingConfigService.cs b/src/NadekoBot/Modules/Gambling/Services/GamblingConfigService.cs index 020ae1c9d..3274e7ecc 100644 --- a/src/NadekoBot/Modules/Gambling/Services/GamblingConfigService.cs +++ b/src/NadekoBot/Modules/Gambling/Services/GamblingConfigService.cs @@ -7,7 +7,7 @@ public sealed class GamblingConfigService : ConfigServiceBase { public override string Name { get; } = "gambling"; private const string FilePath = "data/gambling.yml"; - private static TypedKey changeKey = new TypedKey("config.gambling.updated"); + private static readonly TypedKey changeKey = new("config.gambling.updated"); public GamblingConfigService(IConfigSeria serializer, IPubSub pubSub) diff --git a/src/NadekoBot/Modules/Gambling/Services/GamblingService.cs b/src/NadekoBot/Modules/Gambling/Services/GamblingService.cs index 0da8be086..e4c72df5d 100644 --- a/src/NadekoBot/Modules/Gambling/Services/GamblingService.cs +++ b/src/NadekoBot/Modules/Gambling/Services/GamblingService.cs @@ -17,8 +17,8 @@ public class GamblingService : INService private readonly IDataCache _cache; private readonly GamblingConfigService _gss; - public ConcurrentDictionary<(ulong, ulong), RollDuelGame> Duels { get; } = new ConcurrentDictionary<(ulong, ulong), RollDuelGame>(); - public ConcurrentDictionary Connect4Games { get; } = new ConcurrentDictionary(); + public ConcurrentDictionary<(ulong, ulong), RollDuelGame> Duels { get; } = new(); + public ConcurrentDictionary Connect4Games { get; } = new(); private readonly Timer _decayTimer; diff --git a/src/NadekoBot/Modules/Gambling/Services/PlantPickService.cs b/src/NadekoBot/Modules/Gambling/Services/PlantPickService.cs index b1a71e745..6755de750 100644 --- a/src/NadekoBot/Modules/Gambling/Services/PlantPickService.cs +++ b/src/NadekoBot/Modules/Gambling/Services/PlantPickService.cs @@ -24,10 +24,10 @@ public class PlantPickService : INService private readonly DiscordSocketClient _client; private readonly GamblingConfigService _gss; - public readonly ConcurrentHashSet _generationChannels = new ConcurrentHashSet(); + public readonly ConcurrentHashSet _generationChannels = new(); //channelId/last generation - public ConcurrentDictionary LastGenerations { get; } = new ConcurrentDictionary(); - private readonly SemaphoreSlim pickLock = new SemaphoreSlim(1, 1); + public ConcurrentDictionary LastGenerations { get; } = new(); + private readonly SemaphoreSlim pickLock = new(1, 1); public PlantPickService(DbService db, CommandHandler cmd, IBotStrings strings, IDataCache cache, FontProvider fonts, ICurrencyService cs, @@ -172,7 +172,7 @@ public class PlantPickService : INService if (msg is null || msg.Author.IsBot) return Task.CompletedTask; - if (!(imsg.Channel is ITextChannel channel)) + if (imsg.Channel is not ITextChannel channel) return Task.CompletedTask; if (!_generationChannels.Contains(channel.Id)) @@ -189,7 +189,7 @@ public class PlantPickService : INService if (DateTime.UtcNow - TimeSpan.FromSeconds(config.Generation.GenCooldown) < lastGeneration) //recently generated in this channel, don't generate again return; - var num = rng.Next(1, 101) + config.Generation.Chance * 100; + var num = rng.Next(1, 101) + (config.Generation.Chance * 100); if (num > 100 && LastGenerations.TryUpdate(channel.Id, DateTime.UtcNow, lastGeneration)) { var dropAmount = config.Generation.MinAmount; diff --git a/src/NadekoBot/Modules/Gambling/Services/WaifuService.cs b/src/NadekoBot/Modules/Gambling/Services/WaifuService.cs index 1185ee119..3b3a1f0fe 100644 --- a/src/NadekoBot/Modules/Gambling/Services/WaifuService.cs +++ b/src/NadekoBot/Modules/Gambling/Services/WaifuService.cs @@ -107,7 +107,7 @@ public class WaifuService : INService .Count(); return (int) Math.Ceiling(waifu.Price * 1.25f) + - (divorces + affs + 2) * settings.Waifu.Multipliers.WaifuReset; + ((divorces + affs + 2) * settings.Waifu.Multipliers.WaifuReset); } } @@ -199,7 +199,7 @@ public class WaifuService : INService { var oldClaimer = w.Claimer; w.Claimer = uow.GetOrCreateUser(user); - w.Price = amount + amount / 4; + w.Price = amount + (amount / 4); result = WaifuClaimResult.Success; uow.WaifuUpdates.Add(new() diff --git a/src/NadekoBot/Modules/Gambling/ShopCommands.cs b/src/NadekoBot/Modules/Gambling/ShopCommands.cs index 6475946a8..5a05f4fcd 100644 --- a/src/NadekoBot/Modules/Gambling/ShopCommands.cs +++ b/src/NadekoBot/Modules/Gambling/ShopCommands.cs @@ -56,7 +56,7 @@ public partial class Gambling { var entry = theseEntries[i]; embed.AddField( - $"#{curPage * 9 + i + 1} - {entry.Price}{CurrencySign}", + $"#{(curPage * 9) + i + 1} - {entry.Price}{CurrencySign}", EntryToString(entry), true); } diff --git a/src/NadekoBot/Modules/Gambling/SlotCommands.cs b/src/NadekoBot/Modules/Gambling/SlotCommands.cs index 2503711a8..3bf543478 100644 --- a/src/NadekoBot/Modules/Gambling/SlotCommands.cs +++ b/src/NadekoBot/Modules/Gambling/SlotCommands.cs @@ -20,7 +20,7 @@ public partial class Gambling private static long _totalBet; private static long _totalPaidOut; - private static readonly HashSet _runningUsers = new HashSet(); + private static readonly HashSet _runningUsers = new(); //here is a payout chart //https://lh6.googleusercontent.com/-i1hjAJy_kN4/UswKxmhrbPI/AAAAAAAAB1U/82wq_4ZZc-Y/DE6B0895-6FC1-48BE-AC4F-14D1B91AB75B.jpg @@ -43,7 +43,7 @@ public partial class Gambling { public const int MaxValue = 5; - static readonly List> _winningCombos = new List>() + static readonly List> _winningCombos = new() { //three flowers arr => arr.All(a=>a==MaxValue) ? 30 : 0, @@ -218,7 +218,7 @@ public partial class Gambling { using (var img = Image.Load(_images.SlotEmojis[numbers[i]])) { - bgImage.Mutate(x => x.DrawImage(img, new Point(148 + 105 * i, 217), 1f)); + bgImage.Mutate(x => x.DrawImage(img, new Point(148 + (105 * i), 217), 1f)); } } diff --git a/src/NadekoBot/Modules/Gambling/WaifuClaimCommands.cs b/src/NadekoBot/Modules/Gambling/WaifuClaimCommands.cs index 5aacf76ff..a1e961fea 100644 --- a/src/NadekoBot/Modules/Gambling/WaifuClaimCommands.cs +++ b/src/NadekoBot/Modules/Gambling/WaifuClaimCommands.cs @@ -222,7 +222,7 @@ public partial class Gambling foreach (var w in waifus) { var j = i++; - embed.AddField("#" + (page * 9 + j + 1) + " - " + w.Price + CurrencySign, w.ToString(), false); + embed.AddField("#" + ((page * 9) + j + 1) + " - " + w.Price + CurrencySign, w.ToString(), false); } await ctx.Channel.EmbedAsync(embed); diff --git a/src/NadekoBot/Modules/Games/Common/Acrophobia/Acrophobia.cs b/src/NadekoBot/Modules/Games/Common/Acrophobia/Acrophobia.cs index 2b5f63de5..32b2f2538 100644 --- a/src/NadekoBot/Modules/Games/Common/Acrophobia/Acrophobia.cs +++ b/src/NadekoBot/Modules/Games/Common/Acrophobia/Acrophobia.cs @@ -41,8 +41,8 @@ public sealed class AcrophobiaGame : IDisposable public Phase CurrentPhase { get; private set; } = Phase.Submission; public ImmutableArray StartingLetters { get; private set; } - private readonly Dictionary submissions = new Dictionary(); - private readonly SemaphoreSlim locker = new SemaphoreSlim(1, 1); + private readonly Dictionary submissions = new(); + private readonly SemaphoreSlim locker = new(1, 1); public Options Opts { get; } private readonly NadekoRandom _rng; @@ -51,7 +51,7 @@ public sealed class AcrophobiaGame : IDisposable public event Func OnUserVoted = delegate { return Task.CompletedTask; }; public event Func>, Task> OnEnded = delegate { return Task.CompletedTask; }; - private readonly HashSet _usersWhoVoted = new HashSet(); + private readonly HashSet _usersWhoVoted = new(); public AcrophobiaGame(Options options) { diff --git a/src/NadekoBot/Modules/Games/Common/ChatterBot/ChatterBotSession.cs b/src/NadekoBot/Modules/Games/Common/ChatterBot/ChatterBotSession.cs index bc0dd7e80..d1246c840 100644 --- a/src/NadekoBot/Modules/Games/Common/ChatterBot/ChatterBotSession.cs +++ b/src/NadekoBot/Modules/Games/Common/ChatterBot/ChatterBotSession.cs @@ -4,7 +4,7 @@ namespace NadekoBot.Modules.Games.Common.ChatterBot; public class ChatterBotSession : IChatterBotSession { - private static NadekoRandom Rng { get; } = new NadekoRandom(); + private static NadekoRandom Rng { get; } = new(); private readonly string _chatterBotId; private readonly IHttpClientFactory _httpFactory; diff --git a/src/NadekoBot/Modules/Games/Common/ChatterBot/OfficialCleverbotSession.cs b/src/NadekoBot/Modules/Games/Common/ChatterBot/OfficialCleverbotSession.cs index daf5fb30c..32635a2db 100644 --- a/src/NadekoBot/Modules/Games/Common/ChatterBot/OfficialCleverbotSession.cs +++ b/src/NadekoBot/Modules/Games/Common/ChatterBot/OfficialCleverbotSession.cs @@ -57,7 +57,7 @@ public class CleverbotIOSession : IChatterBotSession this._user = user; this._httpFactory = factory; - _nick = new((Func>)GetNick); + _nick = new(GetNick); } private async Task GetNick() diff --git a/src/NadekoBot/Modules/Games/Common/GamesConfig.cs b/src/NadekoBot/Modules/Games/Common/GamesConfig.cs index 146a66a95..9bade13a8 100644 --- a/src/NadekoBot/Modules/Games/Common/GamesConfig.cs +++ b/src/NadekoBot/Modules/Games/Common/GamesConfig.cs @@ -10,20 +10,20 @@ public sealed partial class GamesConfig : ICloneable public int Version { get; set; } [Comment("Hangman related settings (.hangman command)")] - public HangmanConfig Hangman { get; set; } = new HangmanConfig() + public HangmanConfig Hangman { get; set; } = new() { CurrencyReward = 0 }; [Comment("Trivia related settings (.t command)")] - public TriviaConfig Trivia { get; set; } = new TriviaConfig() + public TriviaConfig Trivia { get; set; } = new() { CurrencyReward = 0, MinimumWinReq = 1, }; [Comment("List of responses for the .8ball command. A random one will be selected every time")] - public List EightBallResponses { get; set; } = new List() + public List EightBallResponses { get; set; } = new() { "Most definitely yes.", "For sure.", @@ -51,16 +51,16 @@ public sealed partial class GamesConfig : ICloneable }; [Comment("List of animals which will be used for the animal race game (.race)")] - public List RaceAnimals { get; set; } = new List() + public List RaceAnimals { get; set; } = new() { - new RaceAnimal { Icon = "🐼", Name = "Panda" }, - new RaceAnimal { Icon = "🐻", Name = "Bear" }, - new RaceAnimal { Icon = "🐧", Name = "Pengu" }, - new RaceAnimal { Icon = "🐨", Name = "Koala" }, - new RaceAnimal { Icon = "🐬", Name = "Dolphin" }, - new RaceAnimal { Icon = "🐞", Name = "Ladybird" }, - new RaceAnimal { Icon = "🦀", Name = "Crab" }, - new RaceAnimal { Icon = "🦄", Name = "Unicorn" } + new() { Icon = "🐼", Name = "Panda" }, + new() { Icon = "🐻", Name = "Bear" }, + new() { Icon = "🐧", Name = "Pengu" }, + new() { Icon = "🐨", Name = "Koala" }, + new() { Icon = "🐬", Name = "Dolphin" }, + new() { Icon = "🐞", Name = "Ladybird" }, + new() { Icon = "🦀", Name = "Crab" }, + new() { Icon = "🦄", Name = "Unicorn" } }; } diff --git a/src/NadekoBot/Modules/Games/Common/GirlRating.cs b/src/NadekoBot/Modules/Games/Common/GirlRating.cs index ddbf28e41..dc1d43106 100644 --- a/src/NadekoBot/Modules/Games/Common/GirlRating.cs +++ b/src/NadekoBot/Modules/Games/Common/GirlRating.cs @@ -36,8 +36,8 @@ public class GirlRating const int miny = 385; const int length = 345; - var pointx = (int)(minx + length * (Hot / 10)); - var pointy = (int)(miny - length * ((Crazy - 4) / 6)); + var pointx = (int)(minx + (length * (Hot / 10))); + var pointy = (int)(miny - (length * ((Crazy - 4) / 6))); using (var pointImg = Image.Load(_images.RategirlDot)) { diff --git a/src/NadekoBot/Modules/Games/Common/Hangman/HangmanGame.cs b/src/NadekoBot/Modules/Games/Common/Hangman/HangmanGame.cs index 2e74379f8..38d57467b 100644 --- a/src/NadekoBot/Modules/Games/Common/Hangman/HangmanGame.cs +++ b/src/NadekoBot/Modules/Games/Common/Hangman/HangmanGame.cs @@ -40,7 +40,7 @@ public sealed class HangmanGame } public State GetState(GuessResult guessResult = GuessResult.NoAction) - => new State(_incorrect.Count, + => new(_incorrect.Count, CurrentPhase, CurrentPhase == Phase.Ended ? _word @@ -64,7 +64,7 @@ public sealed class HangmanGame else output[i*2] = '_'; - output[i * 2 + 1] = ' '; + output[(i * 2) + 1] = ' '; } return new(output); diff --git a/src/NadekoBot/Modules/Games/Common/Nunchi/Nunchi.cs b/src/NadekoBot/Modules/Games/Common/Nunchi/Nunchi.cs index 9f75a6fa6..1640198dd 100644 --- a/src/NadekoBot/Modules/Games/Common/Nunchi/Nunchi.cs +++ b/src/NadekoBot/Modules/Games/Common/Nunchi/Nunchi.cs @@ -21,10 +21,10 @@ public sealed class NunchiGame : IDisposable public event Func OnRoundEnded; // tuple of the user who failed public event Func OnGameEnded; // name of the user who won - private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim _locker = new(1, 1); - private HashSet<(ulong Id, string Name)> _participants = new HashSet<(ulong Id, string Name)>(); - private HashSet<(ulong Id, string Name)> _passed = new HashSet<(ulong Id, string Name)>(); + private HashSet<(ulong Id, string Name)> _participants = new(); + private readonly HashSet<(ulong Id, string Name)> _passed = new(); public ImmutableArray<(ulong Id, string Name)> Participants => _participants.ToImmutableArray(); public int ParticipantCount => _participants.Count; diff --git a/src/NadekoBot/Modules/Games/Common/PollRunner.cs b/src/NadekoBot/Modules/Games/Common/PollRunner.cs index 0e9edbf77..3820c103d 100644 --- a/src/NadekoBot/Modules/Games/Common/PollRunner.cs +++ b/src/NadekoBot/Modules/Games/Common/PollRunner.cs @@ -9,7 +9,7 @@ public class PollRunner public event Func OnVoted; - private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim _locker = new(1, 1); public PollRunner(DbService db, Poll poll) { diff --git a/src/NadekoBot/Modules/Games/Common/TicTacToe.cs b/src/NadekoBot/Modules/Games/Common/TicTacToe.cs index bf01cf75b..fd7f0e238 100644 --- a/src/NadekoBot/Modules/Games/Common/TicTacToe.cs +++ b/src/NadekoBot/Modules/Games/Common/TicTacToe.cs @@ -74,7 +74,7 @@ public class TicTacToe { for (var j = 0; j < _state.GetLength(1); j++) { - sb.Append(_state[i, j] is null ? _numbers[i * 3 + j] : GetIcon(_state[i, j])); + sb.Append(_state[i, j] is null ? _numbers[(i * 3) + j] : GetIcon(_state[i, j])); if (j < _state.GetLength(1) - 1) sb.Append("┃"); } diff --git a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaGame.cs b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaGame.cs index 67a5c9892..abffc9671 100644 --- a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaGame.cs +++ b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaGame.cs @@ -4,7 +4,7 @@ namespace NadekoBot.Modules.Games.Common.Trivia; public class TriviaGame { - private readonly SemaphoreSlim _guessLock = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim _guessLock = new(1, 1); private readonly IDataCache _cache; private readonly IBotStrings _strings; private readonly DiscordSocketClient _client; @@ -18,9 +18,9 @@ public class TriviaGame private CancellationTokenSource _triviaCancelSource; public TriviaQuestion CurrentQuestion { get; private set; } - public HashSet OldQuestions { get; } = new HashSet(); + public HashSet OldQuestions { get; } = new(); - public ConcurrentDictionary Users { get; } = new ConcurrentDictionary(); + public ConcurrentDictionary Users { get; } = new(); public bool GameActive { get; private set; } public bool ShouldStopGame { get; private set; } diff --git a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestion.cs b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestion.cs index 417366d2f..fb4554be9 100644 --- a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestion.cs +++ b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestion.cs @@ -6,11 +6,12 @@ namespace NadekoBot.Modules.Games.Common.Trivia; public class TriviaQuestion { //represents the min size to judge levDistance with - private static readonly HashSet> strictness = new HashSet> { - new Tuple(9, 0), - new Tuple(14, 1), - new Tuple(19, 2), - new Tuple(22, 3), + private static readonly HashSet> strictness = new() + { + new(9, 0), + new(14, 1), + new(19, 2), + new(22, 3), }; public const int maxStringLength = 22; diff --git a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestionPool.cs b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestionPool.cs index 2cb7a4873..8ae3a0ace 100644 --- a/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestionPool.cs +++ b/src/NadekoBot/Modules/Games/Common/Trivia/TriviaQuestionPool.cs @@ -5,7 +5,7 @@ public class TriviaQuestionPool private readonly IDataCache _cache; private readonly int maxPokemonId; - private readonly NadekoRandom _rng = new NadekoRandom(); + private readonly NadekoRandom _rng = new(); private TriviaQuestion[] Pool => _cache.LocalData.TriviaQuestions; private IReadOnlyDictionary Map => _cache.LocalData.PokemonMap; diff --git a/src/NadekoBot/Modules/Games/Games.cs b/src/NadekoBot/Modules/Games/Games.cs index ecfc862e2..ebd7b7fe6 100644 --- a/src/NadekoBot/Modules/Games/Games.cs +++ b/src/NadekoBot/Modules/Games/Games.cs @@ -11,7 +11,7 @@ public partial class Games : NadekoModule { private readonly IImageCache _images; private readonly IHttpClientFactory _httpFactory; - private readonly Random _rng = new Random(); + private readonly Random _rng = new(); public Games(IDataCache data, IHttpClientFactory factory) { @@ -79,7 +79,7 @@ public partial class Games : NadekoModule private double NextDouble(double x, double y) { - return _rng.NextDouble() * (y - x) + x; + return (_rng.NextDouble() * (y - x)) + x; } private GirlRating GetGirl(ulong uid) @@ -102,19 +102,19 @@ public partial class Games : NadekoModule else if (roll < 750) { hot = NextDouble(5, 8); - crazy = NextDouble(4, .6 * hot + 4); + crazy = NextDouble(4, (.6 * hot) + 4); advice = ratings.Fun; } else if (roll < 900) { hot = NextDouble(5, 10); - crazy = NextDouble(.61 * hot + 4, 10); + crazy = NextDouble((.61 * hot) + 4, 10); advice = ratings.Dan; } else if (roll < 951) { hot = NextDouble(8, 10); - crazy = NextDouble(7, .6 * hot + 4); + crazy = NextDouble(7, (.6 * hot) + 4); advice = ratings.Dat; } else if (roll < 990) diff --git a/src/NadekoBot/Modules/Games/Services/ChatterbotService.cs b/src/NadekoBot/Modules/Games/Services/ChatterbotService.cs index 618331425..18633a869 100644 --- a/src/NadekoBot/Modules/Games/Services/ChatterbotService.cs +++ b/src/NadekoBot/Modules/Games/Services/ChatterbotService.cs @@ -96,7 +96,7 @@ public class ChatterBotService : IEarlyBehavior public async Task RunBehavior(IGuild guild, IUserMessage usrMsg) { - if (!(guild is SocketGuild sg)) + if (guild is not SocketGuild sg) return false; try { @@ -113,7 +113,7 @@ public class ChatterBotService : IEarlyBehavior if (pc.Verbose) { var returnMsg = _strings.GetText(strs.perm_prevent(index + 1, - Format.Bold(pc.Permissions[index].GetCommand(_cmd.GetPrefix(guild), (SocketGuild)guild)))); + Format.Bold(pc.Permissions[index].GetCommand(_cmd.GetPrefix(sg), sg)))); try { await usrMsg.Channel.SendErrorAsync(_eb, returnMsg).ConfigureAwait(false); } catch { } Log.Information(returnMsg); diff --git a/src/NadekoBot/Modules/Games/Services/GamesConfigService.cs b/src/NadekoBot/Modules/Games/Services/GamesConfigService.cs index d8138e263..2d6b3ddba 100644 --- a/src/NadekoBot/Modules/Games/Services/GamesConfigService.cs +++ b/src/NadekoBot/Modules/Games/Services/GamesConfigService.cs @@ -7,7 +7,7 @@ public sealed class GamesConfigService : ConfigServiceBase { public override string Name { get; } = "games"; private const string FilePath = "data/games.yml"; - private static TypedKey changeKey = new TypedKey("config.games.updated"); + private static readonly TypedKey changeKey = new("config.games.updated"); public GamesConfigService(IConfigSeria serializer, IPubSub pubSub) : base(FilePath, serializer, pubSub, changeKey) diff --git a/src/NadekoBot/Modules/Games/Services/GamesService.cs b/src/NadekoBot/Modules/Games/Services/GamesService.cs index a597a714e..7f2e70321 100644 --- a/src/NadekoBot/Modules/Games/Services/GamesService.cs +++ b/src/NadekoBot/Modules/Games/Services/GamesService.cs @@ -11,7 +11,7 @@ public class GamesService : INService { private readonly GamesConfigService _gamesConfig; - public ConcurrentDictionary GirlRatings { get; } = new ConcurrentDictionary(); + public ConcurrentDictionary GirlRatings { get; } = new(); public IReadOnlyList EightBallResponses => _gamesConfig.Data.EightBallResponses; @@ -22,14 +22,14 @@ public class GamesService : INService private const string TypingArticlesPath = "data/typing_articles3.json"; - public List TypingArticles { get; } = new List(); + public List TypingArticles { get; } = new(); //channelId, game - public ConcurrentDictionary AcrophobiaGames { get; } = new ConcurrentDictionary(); - public ConcurrentDictionary RunningTrivias { get; } = new ConcurrentDictionary(); - public Dictionary TicTacToeGames { get; } = new Dictionary(); - public ConcurrentDictionary RunningContests { get; } = new ConcurrentDictionary(); - public ConcurrentDictionary NunchiGames { get; } = new ConcurrentDictionary(); + public ConcurrentDictionary AcrophobiaGames { get; } = new(); + public ConcurrentDictionary RunningTrivias { get; } = new(); + public Dictionary TicTacToeGames { get; } = new(); + public ConcurrentDictionary RunningContests { get; } = new(); + public ConcurrentDictionary NunchiGames { get; } = new(); public AsyncLazy Ratings { get; } diff --git a/src/NadekoBot/Modules/Games/Services/PollService.cs b/src/NadekoBot/Modules/Games/Services/PollService.cs index 73268ff6f..7467441b6 100644 --- a/src/NadekoBot/Modules/Games/Services/PollService.cs +++ b/src/NadekoBot/Modules/Games/Services/PollService.cs @@ -8,7 +8,7 @@ namespace NadekoBot.Modules.Games.Services; public class PollService : IEarlyBehavior { - public ConcurrentDictionary ActivePolls { get; } = new ConcurrentDictionary(); + public ConcurrentDictionary ActivePolls { get; } = new(); public int Priority => 5; diff --git a/src/NadekoBot/Modules/Games/TicTacToeCommands.cs b/src/NadekoBot/Modules/Games/TicTacToeCommands.cs index 6a07f12d4..485661104 100644 --- a/src/NadekoBot/Modules/Games/TicTacToeCommands.cs +++ b/src/NadekoBot/Modules/Games/TicTacToeCommands.cs @@ -8,7 +8,7 @@ public partial class Games [Group] public class TicTacToeCommands : NadekoSubmodule { - private readonly SemaphoreSlim _sem = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim _sem = new(1, 1); private readonly DiscordSocketClient _client; public TicTacToeCommands(DiscordSocketClient client) diff --git a/src/NadekoBot/Modules/Help/Services/HelpService.cs b/src/NadekoBot/Modules/Help/Services/HelpService.cs index 8f1c28b28..5c3394a80 100644 --- a/src/NadekoBot/Modules/Help/Services/HelpService.cs +++ b/src/NadekoBot/Modules/Help/Services/HelpService.cs @@ -132,9 +132,9 @@ public class HelpService : ILateExecutor, INService if (userPerm is not null) { if (userPerm.ChannelPermission is { } cPerm) - userPermString = GetPreconditionString((ChannelPerm) cPerm); + userPermString = GetPreconditionString(cPerm); if (userPerm.GuildPermission is { } gPerm) - userPermString = GetPreconditionString((GuildPerm) gPerm); + userPermString = GetPreconditionString(gPerm); } if (overrides is null) diff --git a/src/NadekoBot/Modules/Music/Common/Impl/MusicPlayer.cs b/src/NadekoBot/Modules/Music/Common/Impl/MusicPlayer.cs index afc2b35a9..e321e582d 100644 --- a/src/NadekoBot/Modules/Music/Common/Impl/MusicPlayer.cs +++ b/src/NadekoBot/Modules/Music/Common/Impl/MusicPlayer.cs @@ -12,7 +12,7 @@ public sealed class MusicPlayer : IMusicPlayer { private delegate void AdjustVolumeDelegate(Span data, float volume); - private AdjustVolumeDelegate AdjustVolume; + private readonly AdjustVolumeDelegate AdjustVolume; private readonly VoiceClient _vc; public bool IsKilled { get; private set; } @@ -369,7 +369,7 @@ public sealed class MusicPlayer : IMusicPlayer for (var i = 0; i < samples.Length; i++) { ref var sample = ref samples[i]; - sample = (float) (sample * volume); + sample = sample * volume; } } diff --git a/src/NadekoBot/Modules/Music/Common/Impl/MusicQueue.cs b/src/NadekoBot/Modules/Music/Common/Impl/MusicQueue.cs index 11e65d180..a8ac9c6b0 100644 --- a/src/NadekoBot/Modules/Music/Common/Impl/MusicQueue.cs +++ b/src/NadekoBot/Modules/Music/Common/Impl/MusicQueue.cs @@ -55,7 +55,7 @@ public sealed partial class MusicQueue : IMusicQueue } } - private readonly object locker = new object(); + private readonly object locker = new(); public MusicQueue() { diff --git a/src/NadekoBot/Modules/Music/Common/Impl/SimpleTrackInfo.cs b/src/NadekoBot/Modules/Music/Common/Impl/SimpleTrackInfo.cs index c9190d45d..3eeb8b208 100644 --- a/src/NadekoBot/Modules/Music/Common/Impl/SimpleTrackInfo.cs +++ b/src/NadekoBot/Modules/Music/Common/Impl/SimpleTrackInfo.cs @@ -9,7 +9,7 @@ public sealed class SimpleTrackInfo : ITrackInfo public TimeSpan Duration { get; } public MusicPlatform Platform { get; } public string? StreamUrl { get; } - public ValueTask GetStreamUrl() => new ValueTask(StreamUrl); + public ValueTask GetStreamUrl() => new(StreamUrl); public SimpleTrackInfo(string title, string url, string thumbnail, TimeSpan duration, MusicPlatform platform, string streamUrl) diff --git a/src/NadekoBot/Modules/Music/Common/Resolvers/RadioResolveStrategy.cs b/src/NadekoBot/Modules/Music/Common/Resolvers/RadioResolveStrategy.cs index 10e272430..f88d39b64 100644 --- a/src/NadekoBot/Modules/Music/Common/Resolvers/RadioResolveStrategy.cs +++ b/src/NadekoBot/Modules/Music/Common/Resolvers/RadioResolveStrategy.cs @@ -4,10 +4,10 @@ namespace NadekoBot.Modules.Music.Resolvers; public class RadioResolver : IRadioResolver { - private readonly Regex plsRegex = new Regex("File1=(?.*?)\\n", RegexOptions.Compiled); - private readonly Regex m3uRegex = new Regex("(?^[^#].*)", RegexOptions.Compiled | RegexOptions.Multiline); - private readonly Regex asxRegex = new Regex(".*?)\"", RegexOptions.Compiled); - private readonly Regex xspfRegex = new Regex("(?.*?)", RegexOptions.Compiled); + private readonly Regex plsRegex = new("File1=(?.*?)\\n", RegexOptions.Compiled); + private readonly Regex m3uRegex = new("(?^[^#].*)", RegexOptions.Compiled | RegexOptions.Multiline); + private readonly Regex asxRegex = new(".*?)\"", RegexOptions.Compiled); + private readonly Regex xspfRegex = new("(?.*?)", RegexOptions.Compiled); public RadioResolver() { diff --git a/src/NadekoBot/Modules/Music/Common/Resolvers/YtdlYoutubeResolver.cs b/src/NadekoBot/Modules/Music/Common/Resolvers/YtdlYoutubeResolver.cs index 5e472a7f4..899602ce1 100644 --- a/src/NadekoBot/Modules/Music/Common/Resolvers/YtdlYoutubeResolver.cs +++ b/src/NadekoBot/Modules/Music/Common/Resolvers/YtdlYoutubeResolver.cs @@ -10,7 +10,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver {"ss", "m\\:ss", "mm\\:ss", "h\\:mm\\:ss", "hh\\:mm\\:ss", "hhh\\:mm\\:ss"}; public Regex YtVideoIdRegex { get; } - = new Regex( + = new( @"(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\?(?:\S*?&?v\=))|youtu\.be\/)(?[a-zA-Z0-9_-]{6,11})", RegexOptions.Compiled ); @@ -21,7 +21,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver private readonly YtdlOperation _ytdlIdOperation; private readonly YtdlOperation _ytdlSearchOperation; - private IGoogleApiService _google; + private readonly IGoogleApiService _google; public YtdlYoutubeResolver(ITrackCacher trackCacher, IGoogleApiService google) { @@ -136,7 +136,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver async () => await ExtractNewStreamUrlAsync(id) ); - private static readonly Regex expiryRegex = new Regex(@"(?:[\?\&]expire\=(?\d+))"); + private static readonly Regex expiryRegex = new(@"(?:[\?\&]expire\=(?\d+))"); private static TimeSpan GetExpiry(string streamUrl) { var match = expiryRegex.Match(streamUrl); @@ -205,8 +205,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver ); - private static readonly Regex _simplePlaylistRegex - = new Regex(@"&list=(?[\w\-]{12,})", RegexOptions.Compiled); + private static readonly Regex _simplePlaylistRegex = new(@"&list=(?[\w\-]{12,})", RegexOptions.Compiled); public async IAsyncEnumerable ResolveTracksByPlaylistIdAsync(string playlistId) { diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index c0b41b2c4..f8167d13e 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -36,7 +36,7 @@ public sealed partial class Music : NadekoModule return true; } - private static readonly SemaphoreSlim voiceChannelLock = new SemaphoreSlim(1, 1); + private static readonly SemaphoreSlim voiceChannelLock = new(1, 1); private async Task EnsureBotInVoiceChannelAsync(ulong voiceChannelId, IGuildUser botUser = null) { botUser ??= await ctx.Guild.GetCurrentUserAsync(); @@ -253,7 +253,7 @@ public sealed partial class Music : NadekoModule return; } - await ListQueue(mp.CurrentIndex / LQ_ITEMS_PER_PAGE + 1); + await ListQueue((mp.CurrentIndex / LQ_ITEMS_PER_PAGE) + 1); } // list queue, specify page @@ -319,7 +319,7 @@ public sealed partial class Music : NadekoModule desc = add + "\n" + desc; var embed = _eb.Create() - .WithAuthor(GetText(strs.player_queue(curPage + 1, tracks.Count / LQ_ITEMS_PER_PAGE + 1)), + .WithAuthor(GetText(strs.player_queue(curPage + 1, (tracks.Count / LQ_ITEMS_PER_PAGE) + 1)), MusicIconUrl) .WithDescription(desc) .WithFooter($" {mp.PrettyVolume()} | 🎶 {tracks.Count} | ⌛ {mp.PrettyTotalTime()} ") diff --git a/src/NadekoBot/Modules/Music/PlaylistCommands.cs b/src/NadekoBot/Modules/Music/PlaylistCommands.cs index 1be0d5e31..749ea1b2e 100644 --- a/src/NadekoBot/Modules/Music/PlaylistCommands.cs +++ b/src/NadekoBot/Modules/Music/PlaylistCommands.cs @@ -158,7 +158,7 @@ public sealed partial class Music } - private static readonly SemaphoreSlim _playlistLock = new SemaphoreSlim(1, 1); + private static readonly SemaphoreSlim _playlistLock = new(1, 1); [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs b/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs index 510140df8..9f7dbfc0a 100644 --- a/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs +++ b/src/NadekoBot/Modules/Music/Services/AyuVoiceStateService.cs @@ -8,8 +8,8 @@ public sealed class AyuVoiceStateService : INService // public delegate Task VoiceProxyUpdatedDelegate(ulong guildId, IVoiceProxy proxy); // public event VoiceProxyUpdatedDelegate OnVoiceProxyUpdate = delegate { return Task.CompletedTask; }; - private readonly ConcurrentDictionary _voiceProxies = new ConcurrentDictionary(); - private readonly ConcurrentDictionary _voiceGatewayLocks = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _voiceProxies = new(); + private readonly ConcurrentDictionary _voiceGatewayLocks = new(); private readonly DiscordSocketClient _client; private readonly MethodInfo _sendVoiceStateUpdateMethodInfo; @@ -167,7 +167,7 @@ public sealed class AyuVoiceStateService : INService var voiceServerData = await voiceServerUpdatedSource.Task; VoiceGateway CreateVoiceGatewayLocal() => - new VoiceGateway( + new( guildId, _currentUserId, session, diff --git a/src/NadekoBot/Modules/Nsfw/Common/DapiImageObject.cs b/src/NadekoBot/Modules/Nsfw/Common/DapiImageObject.cs index cb3596931..8738369ee 100644 --- a/src/NadekoBot/Modules/Nsfw/Common/DapiImageObject.cs +++ b/src/NadekoBot/Modules/Nsfw/Common/DapiImageObject.cs @@ -13,5 +13,5 @@ public class DapiImageObject : IImageData public string Rating { get; set; } public ImageData ToCachedImageData(Booru type) - => new ImageData(this.FileUrl, type, this.Tags?.Split(' ') ?? this.TagString?.Split(' '), Score.ToString() ?? Rating); + => new(this.FileUrl, type, this.Tags?.Split(' ') ?? this.TagString?.Split(' '), Score.ToString() ?? Rating); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Nsfw/Common/Downloaders/ImageDownloader.cs b/src/NadekoBot/Modules/Nsfw/Common/Downloaders/ImageDownloader.cs index e83a7f359..c90b98e34 100644 --- a/src/NadekoBot/Modules/Nsfw/Common/Downloaders/ImageDownloader.cs +++ b/src/NadekoBot/Modules/Nsfw/Common/Downloaders/ImageDownloader.cs @@ -8,7 +8,7 @@ public abstract class ImageDownloader : IImageDownloader { protected readonly HttpClient _http; - protected JsonSerializerOptions _serializerOptions = new JsonSerializerOptions() + protected JsonSerializerOptions _serializerOptions = new() { PropertyNameCaseInsensitive = true, NumberHandling = JsonNumberHandling.WriteAsString | JsonNumberHandling.AllowReadingFromString, diff --git a/src/NadekoBot/Modules/Nsfw/Common/SafebooruElement.cs b/src/NadekoBot/Modules/Nsfw/Common/SafebooruElement.cs index 04cb60d72..79b36cbe0 100644 --- a/src/NadekoBot/Modules/Nsfw/Common/SafebooruElement.cs +++ b/src/NadekoBot/Modules/Nsfw/Common/SafebooruElement.cs @@ -9,6 +9,5 @@ public class SafebooruElement : IImageData public string FileUrl => $"https://safebooru.org/images/{Directory}/{Image}"; public string Rating { get; set; } public string Tags { get; set; } - public ImageData ToCachedImageData(Booru type) - => new ImageData(FileUrl, Booru.Safebooru, this.Tags.Split(' '), Rating); + public ImageData ToCachedImageData(Booru type) => new(FileUrl, Booru.Safebooru, this.Tags.Split(' '), Rating); } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Nsfw/Nsfw.cs b/src/NadekoBot/Modules/Nsfw/Nsfw.cs index d59d8c957..112e3db24 100644 --- a/src/NadekoBot/Modules/Nsfw/Nsfw.cs +++ b/src/NadekoBot/Modules/Nsfw/Nsfw.cs @@ -7,7 +7,7 @@ namespace NadekoBot.Modules.Nsfw; [NoPublicBot] public class NSFW : NadekoModule { - private static readonly ConcurrentHashSet _hentaiBombBlacklist = new ConcurrentHashSet(); + private static readonly ConcurrentHashSet _hentaiBombBlacklist = new(); private readonly IHttpClientFactory _httpFactory; private readonly NadekoRandom _rng; diff --git a/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs b/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs index a31d9139c..869ada1ba 100644 --- a/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs +++ b/src/NadekoBot/Modules/Nsfw/SearchImagesService.cs @@ -14,7 +14,7 @@ public record UrlReply public string Url { get; init; } public string Rating { get; init; } public string Provider { get; init; } - public List Tags { get; } = new List(); + public List Tags { get; } = new(); } public class SearchImagesService : ISearchImagesService, INService @@ -26,9 +26,9 @@ public class SearchImagesService : ISearchImagesService, INService private readonly DbService _db; private ConcurrentDictionary> BlacklistedTags { get; } - public ConcurrentDictionary AutoHentaiTimers { get; } = new ConcurrentDictionary(); - public ConcurrentDictionary AutoBoobTimers { get; } = new ConcurrentDictionary(); - public ConcurrentDictionary AutoButtTimers { get; } = new ConcurrentDictionary(); + public ConcurrentDictionary AutoHentaiTimers { get; } = new(); + public ConcurrentDictionary AutoBoobTimers { get; } = new(); + public ConcurrentDictionary AutoButtTimers { get; } = new(); public SearchImagesService(DbService db, IHttpClientFactory http, @@ -219,7 +219,7 @@ public class SearchImagesService : ISearchImagesService, INService } } - private readonly object taglock = new object(); + private readonly object taglock = new(); public ValueTask ToggleBlacklistTag(ulong guildId, string tag) { lock (taglock) diff --git a/src/NadekoBot/Modules/Permissions/Common/PermissionExtensions.cs b/src/NadekoBot/Modules/Permissions/Common/PermissionExtensions.cs index b49466853..6442cb088 100644 --- a/src/NadekoBot/Modules/Permissions/Common/PermissionExtensions.cs +++ b/src/NadekoBot/Modules/Permissions/Common/PermissionExtensions.cs @@ -31,10 +31,10 @@ public static class PermissionExtensions //false = applicable, not allowed public static bool? CheckPermission(this Permissionv2 perm, IUserMessage message, string commandName, string moduleName) { - if (!(perm.SecondaryTarget == SecondaryPermissionType.Command && - perm.SecondaryTargetName.ToLowerInvariant() == commandName.ToLowerInvariant() || - perm.SecondaryTarget == SecondaryPermissionType.Module && - perm.SecondaryTargetName.ToLowerInvariant() == moduleName.ToLowerInvariant() || + if (!((perm.SecondaryTarget == SecondaryPermissionType.Command && + perm.SecondaryTargetName.ToLowerInvariant() == commandName.ToLowerInvariant()) || + (perm.SecondaryTarget == SecondaryPermissionType.Module && + perm.SecondaryTargetName.ToLowerInvariant() == moduleName.ToLowerInvariant()) || perm.SecondaryTarget == SecondaryPermissionType.AllModules)) return null; diff --git a/src/NadekoBot/Modules/Permissions/Common/PermissionsCollection.cs b/src/NadekoBot/Modules/Permissions/Common/PermissionsCollection.cs index 34ce69527..6703f9877 100644 --- a/src/NadekoBot/Modules/Permissions/Common/PermissionsCollection.cs +++ b/src/NadekoBot/Modules/Permissions/Common/PermissionsCollection.cs @@ -5,7 +5,7 @@ namespace NadekoBot.Modules.Permissions.Common; public class PermissionsCollection : IndexedCollection where T : class, IIndexed { - private readonly object _localLocker = new object(); + private readonly object _localLocker = new(); public PermissionsCollection(IEnumerable source) : base(source) { } diff --git a/src/NadekoBot/Modules/Permissions/Services/BlacklistService.cs b/src/NadekoBot/Modules/Permissions/Services/BlacklistService.cs index 15957ed73..378acf246 100644 --- a/src/NadekoBot/Modules/Permissions/Services/BlacklistService.cs +++ b/src/NadekoBot/Modules/Permissions/Services/BlacklistService.cs @@ -13,7 +13,7 @@ public sealed class BlacklistService : IEarlyBehavior private IReadOnlyList _blacklist; public int Priority => int.MaxValue; - private readonly TypedKey blPubKey = new TypedKey("blacklist.reload"); + private readonly TypedKey blPubKey = new("blacklist.reload"); public BlacklistService(DbService db, IPubSub pubSub, IBotCredentials creds) { _db = db; diff --git a/src/NadekoBot/Modules/Permissions/Services/CmdCdService.cs b/src/NadekoBot/Modules/Permissions/Services/CmdCdService.cs index c2ed4f49d..1ac5767e9 100644 --- a/src/NadekoBot/Modules/Permissions/Services/CmdCdService.cs +++ b/src/NadekoBot/Modules/Permissions/Services/CmdCdService.cs @@ -7,7 +7,7 @@ namespace NadekoBot.Modules.Permissions.Services; public class CmdCdService : ILateBlocker, INService { public ConcurrentDictionary> CommandCooldowns { get; } - public ConcurrentDictionary> ActiveCooldowns { get; } = new ConcurrentDictionary>(); + public ConcurrentDictionary> ActiveCooldowns { get; } = new(); public int Priority { get; } = 0; diff --git a/src/NadekoBot/Modules/Permissions/Services/FilterService.cs b/src/NadekoBot/Modules/Permissions/Services/FilterService.cs index b4fb828bc..548f7b547 100644 --- a/src/NadekoBot/Modules/Permissions/Services/FilterService.cs +++ b/src/NadekoBot/Modules/Permissions/Services/FilterService.cs @@ -113,7 +113,7 @@ public sealed class FilterService : IEarlyBehavior public async Task RunBehavior(IGuild guild, IUserMessage msg) { - if (!(msg.Author is IGuildUser gu) || gu.GuildPermissions.Administrator) + if (msg.Author is not IGuildUser gu || gu.GuildPermissions.Administrator) return false; var results = await Task.WhenAll( diff --git a/src/NadekoBot/Modules/Permissions/Services/PermissionsService.cs b/src/NadekoBot/Modules/Permissions/Services/PermissionsService.cs index 7d71baad7..e1b96321d 100644 --- a/src/NadekoBot/Modules/Permissions/Services/PermissionsService.cs +++ b/src/NadekoBot/Modules/Permissions/Services/PermissionsService.cs @@ -16,8 +16,7 @@ public class PermissionService : ILateBlocker, INService private readonly IEmbedBuilderService _eb; //guildid, root permission - public ConcurrentDictionary Cache { get; } = - new ConcurrentDictionary(); + public ConcurrentDictionary Cache { get; } = new(); public PermissionService(DiscordSocketClient client, DbService db, @@ -135,7 +134,7 @@ public class PermissionService : ILateBlocker, INService if (moduleName == nameof(Permissions)) { - if (!(user is IGuildUser guildUser)) + if (user is not IGuildUser guildUser) return true; if (guildUser.GuildPermissions.Administrator) diff --git a/src/NadekoBot/Modules/Searches/Common/LowerCaseNamingPolicy.cs b/src/NadekoBot/Modules/Searches/Common/LowerCaseNamingPolicy.cs index 6fda7b018..48f29e530 100644 --- a/src/NadekoBot/Modules/Searches/Common/LowerCaseNamingPolicy.cs +++ b/src/NadekoBot/Modules/Searches/Common/LowerCaseNamingPolicy.cs @@ -4,7 +4,7 @@ namespace SystemTextJsonSamples; public class LowerCaseNamingPolicy : JsonNamingPolicy { - public static LowerCaseNamingPolicy Default = new LowerCaseNamingPolicy(); + public static LowerCaseNamingPolicy Default = new(); public override string ConvertName(string name) => name.ToLower(); diff --git a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Models/StreamData.cs b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Models/StreamData.cs index 7b3a65e7b..0077ccdfd 100644 --- a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Models/StreamData.cs +++ b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Models/StreamData.cs @@ -15,5 +15,5 @@ public class StreamData public string StreamUrl { get; set; } public string AvatarUrl { get; set; } - public StreamDataKey CreateKey() => new StreamDataKey(StreamType, UniqueName.ToLower()); + public StreamDataKey CreateKey() => new(StreamType, UniqueName.ToLower()); } \ 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 bb9bb2898..613d498fc 100644 --- a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/PicartoProvider.cs +++ b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/PicartoProvider.cs @@ -9,7 +9,7 @@ public class PicartoProvider : Provider { private readonly IHttpClientFactory _httpClientFactory; - private static Regex Regex { get; } = new Regex(@"picarto.tv/(?.+[^/])/?", + private static Regex Regex { get; } = new(@"picarto.tv/(?.+[^/])/?", RegexOptions.Compiled | RegexOptions.IgnoreCase); public override FollowedStream.FType Platform => FollowedStream.FType.Picarto; diff --git a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/Provider.cs b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/Provider.cs index c0ac16e4a..f083f10a0 100644 --- a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/Provider.cs +++ b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/Provider.cs @@ -51,8 +51,7 @@ public abstract class Provider /// /// When was the first time the stream continually had errors while being retrieved /// - protected readonly ConcurrentDictionary _failingStreams = - new ConcurrentDictionary(); + protected readonly ConcurrentDictionary _failingStreams = new(); public void ClearErrorsFor(string login) => _failingStreams.TryRemove(login, out _); diff --git a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/TwitchProvider.cs b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/TwitchProvider.cs index 7a2ad2f03..d41dbdfda 100644 --- a/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/TwitchProvider.cs +++ b/src/NadekoBot/Modules/Searches/Common/StreamNotifications/Providers/TwitchProvider.cs @@ -9,7 +9,7 @@ public class TwitchProvider : Provider { private readonly IHttpClientFactory _httpClientFactory; - private static Regex Regex { get; } = new Regex(@"twitch.tv/(?.+[^/])/?", + private static Regex Regex { get; } = new(@"twitch.tv/(?.+[^/])/?", RegexOptions.Compiled | RegexOptions.IgnoreCase); public override FollowedStream.FType Platform => FollowedStream.FType.Twitch; diff --git a/src/NadekoBot/Modules/Searches/FeedCommands.cs b/src/NadekoBot/Modules/Searches/FeedCommands.cs index 9fc7d99c5..c96bf8f9a 100644 --- a/src/NadekoBot/Modules/Searches/FeedCommands.cs +++ b/src/NadekoBot/Modules/Searches/FeedCommands.cs @@ -9,7 +9,7 @@ public partial class Searches public class FeedCommands : NadekoSubmodule { private static readonly Regex YtChannelRegex = - new Regex(@"youtube\.com\/(?:c\/|channel\/|user\/)?(?[a-zA-Z0-9\-]{1,})"); + new(@"youtube\.com\/(?:c\/|channel\/|user\/)?(?[a-zA-Z0-9\-]{1,})"); [NadekoCommand, Aliases] [RequireContext(ContextType.Guild)] @@ -97,7 +97,7 @@ public partial class Searches var i = 0; var fs = string.Join("\n", feeds.Skip(cur * 10) .Take(10) - .Select(x => $"`{cur * 10 + ++i}.` <#{x.ChannelId}> {x.Url}")); + .Select(x => $"`{(cur * 10) + ++i}.` <#{x.ChannelId}> {x.Url}")); return embed.WithDescription(fs); diff --git a/src/NadekoBot/Modules/Searches/OsuCommands.cs b/src/NadekoBot/Modules/Searches/OsuCommands.cs index 48c1e4733..09b053eb0 100644 --- a/src/NadekoBot/Modules/Searches/OsuCommands.cs +++ b/src/NadekoBot/Modules/Searches/OsuCommands.cs @@ -200,16 +200,16 @@ public partial class Searches double totalHits; if (mode == 0) { - hitPoints = play.Count50 * 50 + - play.Count100 * 100 + - play.Count300 * 300; + hitPoints = (play.Count50 * 50) + + (play.Count100 * 100) + + (play.Count300 * 300); totalHits = play.Count50 + play.Count100 + play.Count300 + play.Countmiss; totalHits *= 300; } else if (mode == 1) { - hitPoints = play.Countmiss * 0 + play.Count100 * 0.5 + play.Count300; + hitPoints = (play.Countmiss * 0) + (play.Count100 * 0.5) + play.Count300; totalHits = (play.Countmiss + play.Count100 + play.Count300) * 300; hitPoints *= 300; } @@ -221,10 +221,10 @@ public partial class Searches } else { - hitPoints = play.Count50 * 50 + - play.Count100 * 100 + - play.Countkatu * 200 + - (play.Count300 + play.Countgeki) * 300; + hitPoints = (play.Count50 * 50) + + (play.Count100 * 100) + + (play.Countkatu * 200) + + ((play.Count300 + play.Countgeki) * 300); totalHits = (play.Countmiss + play.Count50 + play.Count100 + play.Countkatu + play.Count300 + play.Countgeki) * 300; diff --git a/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs b/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs index efad2f432..deda7c760 100644 --- a/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs +++ b/src/NadekoBot/Modules/Searches/PathOfExileCommands.cs @@ -84,7 +84,7 @@ public partial class Searches { var character = tempList[i]; - sb.AppendLine($"#{i + 1 + curPage * 9,-4}{character.Name,-23}{ShortLeagueName(character.League),-10}{character.Class,-13}{character.Level,-3}"); + sb.AppendLine($"#{i + 1 + (curPage * 9),-4}{character.Name,-23}{ShortLeagueName(character.League),-10}{character.Class,-13}{character.Level,-3}"); } sb.AppendLine("```"); @@ -212,7 +212,7 @@ public partial class Searches } } - private Dictionary currencyDictionary = new Dictionary(StringComparer.OrdinalIgnoreCase) + private Dictionary currencyDictionary = new(StringComparer.OrdinalIgnoreCase) { {"Chaos Orb", "Chaos Orb" }, {"Orb of Alchemy", "Orb of Alchemy" }, diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index 1a5311d37..8076ec7f8 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -267,7 +267,7 @@ public partial class Searches : NadekoModule public string ResultUrl { get; set; } } - private static readonly ConcurrentDictionary cachedShortenedLinks = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary cachedShortenedLinks = new(); [NadekoCommand, Aliases] public async Task Shorten([Leftover] string query) @@ -491,7 +491,7 @@ public partial class Searches : NadekoModule var data = JsonConvert.DeserializeObject(res); var datas = data.Results - .Where(x => !(x.Senses is null) && x.Senses.Count > 0 && !(x.Senses[0].Definition is null)) + .Where(x => x.Senses is not null && x.Senses.Count > 0 && x.Senses[0].Definition is not null) .Select(x => (Sense: x.Senses[0], x.PartOfSpeech)); if (!datas.Any()) @@ -611,10 +611,10 @@ public partial class Searches : NadekoModule { var x = i * 50; img.Mutate(m => m.FillPolygon(colorObjects[i], new PointF[] { - new PointF(x, 0), - new PointF(x + 50, 0), - new PointF(x + 50, 50), - new PointF(x, 50) + new(x, 0), + new(x + 50, 0), + new(x + 50, 50), + new(x, 50) })); } diff --git a/src/NadekoBot/Modules/Searches/Services/CryptoService.cs b/src/NadekoBot/Modules/Searches/Services/CryptoService.cs index 2e2df9d51..202984d36 100644 --- a/src/NadekoBot/Modules/Searches/Services/CryptoService.cs +++ b/src/NadekoBot/Modules/Searches/Services/CryptoService.cs @@ -53,7 +53,7 @@ public class CryptoService : INService return (crypto, null); } - private readonly SemaphoreSlim getCryptoLock = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim getCryptoLock = new(1, 1); public async Task> CryptoData() { await getCryptoLock.WaitAsync(); diff --git a/src/NadekoBot/Modules/Searches/Services/FeedsService.cs b/src/NadekoBot/Modules/Searches/Services/FeedsService.cs index c9acfa789..f205a9e01 100644 --- a/src/NadekoBot/Modules/Searches/Services/FeedsService.cs +++ b/src/NadekoBot/Modules/Searches/Services/FeedsService.cs @@ -12,8 +12,7 @@ public class FeedsService : INService private readonly DiscordSocketClient _client; private readonly IEmbedBuilderService _eb; - private readonly ConcurrentDictionary _lastPosts = - new ConcurrentDictionary(); + private readonly ConcurrentDictionary _lastPosts = new(); public FeedsService(Bot bot, DbService db, DiscordSocketClient client, IEmbedBuilderService eb) { @@ -59,7 +58,7 @@ public class FeedsService : INService .Select(item => (Item: item, LastUpdate: item.PublishingDate?.ToUniversalTime() ?? (item.SpecificItem as AtomFeedItem)?.UpdatedDate ?.ToUniversalTime())) - .Where(data => !(data.LastUpdate is null)) + .Where(data => data.LastUpdate is not null) .Select(data => (data.Item, LastUpdate: (DateTime) data.LastUpdate)) .OrderByDescending(data => data.LastUpdate) .Reverse() // start from the oldest diff --git a/src/NadekoBot/Modules/Searches/Services/SearchesService.cs b/src/NadekoBot/Modules/Searches/Services/SearchesService.cs index fe37e8f7d..b795c4873 100644 --- a/src/NadekoBot/Modules/Searches/Services/SearchesService.cs +++ b/src/NadekoBot/Modules/Searches/Services/SearchesService.cs @@ -23,8 +23,8 @@ public class SearchesService : INService private readonly IBotCredentials _creds; private readonly NadekoRandom _rng; - public List WowJokes { get; } = new List(); - public List MagicItems { get; } = new List(); + public List WowJokes { get; } = new(); + public List MagicItems { get; } = new(); private readonly List _yomamaJokes; public SearchesService(IGoogleApiService google, @@ -282,7 +282,7 @@ public class SearchesService : INService _rng.Next(1, max).ToString("000") + ".png"; } - private readonly object yomamaLock = new object(); + private readonly object yomamaLock = new(); private int yomamaJokeIndex = 0; public Task GetYomamaJoke() { @@ -567,7 +567,7 @@ public class SearchesService : INService } } - private static readonly HtmlParser _googleParser = new HtmlParser(new() + private static readonly HtmlParser _googleParser = new(new() { IsScripting = false, IsEmbedded = false, diff --git a/src/NadekoBot/Modules/Searches/Services/StreamNotificationService.cs b/src/NadekoBot/Modules/Searches/Services/StreamNotificationService.cs index 22a41c741..e3c96391e 100644 --- a/src/NadekoBot/Modules/Searches/Services/StreamNotificationService.cs +++ b/src/NadekoBot/Modules/Searches/Services/StreamNotificationService.cs @@ -17,10 +17,9 @@ public sealed class StreamNotificationService : INService private readonly DiscordSocketClient _client; private readonly NotifChecker _streamTracker; - private readonly object _shardLock = new object(); + private readonly object _shardLock = new(); - private readonly Dictionary> _trackCounter = - new Dictionary>(); + private readonly Dictionary> _trackCounter = new(); private readonly Dictionary>> _shardTrackedStreams; private readonly ConcurrentHashSet _offlineNotificationServers; diff --git a/src/NadekoBot/Modules/Searches/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/StreamNotificationCommands.cs index 72e07387c..cb22f0c07 100644 --- a/src/NadekoBot/Modules/Searches/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/StreamNotificationCommands.cs @@ -118,7 +118,7 @@ public partial class Searches { var elem = elements[index]; eb.AddField( - $"**#{index + 1 + 12 * cur}** {elem.Username.ToLower()}", + $"**#{index + 1 + (12 * cur)}** {elem.Username.ToLower()}", $"【{elem.Type}】\n<#{elem.ChannelId}>\n{elem.Message?.TrimTo(50)}", true); } diff --git a/src/NadekoBot/Modules/Utility/QuoteCommands.cs b/src/NadekoBot/Modules/Utility/QuoteCommands.cs index 35492333d..bdaecc606 100644 --- a/src/NadekoBot/Modules/Utility/QuoteCommands.cs +++ b/src/NadekoBot/Modules/Utility/QuoteCommands.cs @@ -204,7 +204,7 @@ public partial class Utility { var q = uow.Quotes.GetById(id); - if (q?.GuildId != ctx.Guild.Id || !hasManageMessages && q.AuthorId != ctx.Message.Author.Id) + if (q?.GuildId != ctx.Guild.Id || (!hasManageMessages && q.AuthorId != ctx.Message.Author.Id)) { response = GetText(strs.quotes_remove_none); } @@ -245,7 +245,7 @@ public partial class Utility public class ExportedQuote { public static ExportedQuote FromModel(Quote quote) - => new ExportedQuote() + => new() { Id = ((kwum)quote.Id).ToString(), An = quote.AuthorName, diff --git a/src/NadekoBot/Modules/Utility/RemindCommands.cs b/src/NadekoBot/Modules/Utility/RemindCommands.cs index 4af38ebfe..845e63990 100644 --- a/src/NadekoBot/Modules/Utility/RemindCommands.cs +++ b/src/NadekoBot/Modules/Utility/RemindCommands.cs @@ -126,7 +126,7 @@ public partial class Utility var when = rem.When; var diff = when - DateTime.UtcNow; embed.AddField( - $"#{++i + page * 10} {rem.When:HH:mm yyyy-MM-dd} UTC " + + $"#{++i + (page * 10)} {rem.When:HH:mm yyyy-MM-dd} UTC " + $"(in {diff.Humanize(2, minUnit: TimeUnit.Minute, culture: _cultureInfo)})", $@"`Target:` {(rem.IsPrivate ? "DM" : "Channel")} `TargetId:` {rem.ChannelId} diff --git a/src/NadekoBot/Modules/Utility/RepeatCommands.cs b/src/NadekoBot/Modules/Utility/RepeatCommands.cs index 324cff601..75e16b5e5 100644 --- a/src/NadekoBot/Modules/Utility/RepeatCommands.cs +++ b/src/NadekoBot/Modules/Utility/RepeatCommands.cs @@ -111,8 +111,8 @@ public partial class Utility : TimeSpan.FromDays(1)); if (string.IsNullOrWhiteSpace(message) - || interval != null && - (interval.Time > TimeSpan.FromMinutes(25000) || interval.Time < TimeSpan.FromMinutes(1))) + || (interval != null && + (interval.Time > TimeSpan.FromMinutes(25000) || interval.Time < TimeSpan.FromMinutes(1)))) { return; } diff --git a/src/NadekoBot/Modules/Utility/Services/CommandMapService.cs b/src/NadekoBot/Modules/Utility/Services/CommandMapService.cs index 005ee02ac..929b1c085 100644 --- a/src/NadekoBot/Modules/Utility/Services/CommandMapService.cs +++ b/src/NadekoBot/Modules/Utility/Services/CommandMapService.cs @@ -9,7 +9,7 @@ public class CommandMapService : IInputTransformer, INService { private readonly IEmbedBuilderService _eb; - public ConcurrentDictionary> AliasMaps { get; } = new ConcurrentDictionary>(); + public ConcurrentDictionary> AliasMaps { get; } = new(); private readonly DbService _db; diff --git a/src/NadekoBot/Modules/Utility/Services/ConverterService.cs b/src/NadekoBot/Modules/Utility/Services/ConverterService.cs index 6ca560b4f..e697a7fce 100644 --- a/src/NadekoBot/Modules/Utility/Services/ConverterService.cs +++ b/src/NadekoBot/Modules/Utility/Services/ConverterService.cs @@ -12,7 +12,7 @@ public class ConverterService : INService .MapJson(); private readonly Timer _currencyUpdater; - private readonly TimeSpan _updateInterval = new TimeSpan(12, 0, 0); + private readonly TimeSpan _updateInterval = new(12, 0, 0); private readonly DbService _db; private readonly IDataCache _cache; private readonly IHttpClientFactory _httpFactory; diff --git a/src/NadekoBot/Modules/Utility/Services/PatreonRewardsService.cs b/src/NadekoBot/Modules/Utility/Services/PatreonRewardsService.cs index 1ba4936f3..966596f11 100644 --- a/src/NadekoBot/Modules/Utility/Services/PatreonRewardsService.cs +++ b/src/NadekoBot/Modules/Utility/Services/PatreonRewardsService.cs @@ -11,10 +11,10 @@ namespace NadekoBot.Modules.Utility.Services; public class PatreonRewardsService : INService { - private readonly SemaphoreSlim getPledgesLocker = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim getPledgesLocker = new(1, 1); private readonly Timer _updater; - private readonly SemaphoreSlim claimLockJustInCase = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim claimLockJustInCase = new(1, 1); public TimeSpan Interval { get; } = TimeSpan.FromMinutes(3); private readonly DbService _db; diff --git a/src/NadekoBot/Modules/Utility/Services/RemindService.cs b/src/NadekoBot/Modules/Utility/Services/RemindService.cs index 33c6a23a8..993077a95 100644 --- a/src/NadekoBot/Modules/Utility/Services/RemindService.cs +++ b/src/NadekoBot/Modules/Utility/Services/RemindService.cs @@ -6,7 +6,7 @@ namespace NadekoBot.Modules.Utility.Services; public class RemindService : INService { - private readonly Regex _regex = new Regex(@"^(?:in\s?)?\s*(?:(?\d+)(?:\s?(?:months?|mos?),?))?(?:(?:\sand\s|\s*)?(?\d+)(?:\s?(?:weeks?|w),?))?(?:(?:\sand\s|\s*)?(?\d+)(?:\s?(?:days?|d),?))?(?:(?:\sand\s|\s*)?(?\d+)(?:\s?(?:hours?|h),?))?(?:(?:\sand\s|\s*)?(?\d+)(?:\s?(?:minutes?|mins?|m),?))?\s+(?:to:?\s+)?(?(?:\r\n|[\r\n]|.)+)", + private readonly Regex _regex = new(@"^(?:in\s?)?\s*(?:(?\d+)(?:\s?(?:months?|mos?),?))?(?:(?:\sand\s|\s*)?(?\d+)(?:\s?(?:weeks?|w),?))?(?:(?:\sand\s|\s*)?(?\d+)(?:\s?(?:days?|d),?))?(?:(?:\sand\s|\s*)?(?\d+)(?:\s?(?:hours?|h),?))?(?:(?:\sand\s|\s*)?(?\d+)(?:\s?(?:minutes?|mins?|m),?))?\s+(?:to:?\s+)?(?(?:\r\n|[\r\n]|.)+)", RegexOptions.Compiled | RegexOptions.Multiline); private readonly DiscordSocketClient _client; @@ -126,7 +126,7 @@ public class RemindService : INService var ts = new TimeSpan ( - 30 * values["mo"] + 7 * values["w"] + values["d"], + (30 * values["mo"]) + (7 * values["w"]) + values["d"], values["h"], values["m"], 0 diff --git a/src/NadekoBot/Modules/Utility/Services/RepeaterService.cs b/src/NadekoBot/Modules/Utility/Services/RepeaterService.cs index e3211b2b3..b881f4fb3 100644 --- a/src/NadekoBot/Modules/Utility/Services/RepeaterService.cs +++ b/src/NadekoBot/Modules/Utility/Services/RepeaterService.cs @@ -16,10 +16,10 @@ public sealed class RepeaterService : IReadyExecutor, INService private readonly IBotCredentials _creds; private readonly IEmbedBuilderService _eb; private readonly DiscordSocketClient _client; - private LinkedList _repeaterQueue; - private ConcurrentHashSet _noRedundant; + private readonly LinkedList _repeaterQueue; + private readonly ConcurrentHashSet _noRedundant; - private readonly object _queueLocker = new object(); + private readonly object _queueLocker = new(); public RepeaterService(DiscordSocketClient client, DbService db, IBotCredentials creds, IEmbedBuilderService eb) { diff --git a/src/NadekoBot/Modules/Utility/Services/RunningRepeater.cs b/src/NadekoBot/Modules/Utility/Services/RunningRepeater.cs index e03057afb..7ee62f1bd 100644 --- a/src/NadekoBot/Modules/Utility/Services/RunningRepeater.cs +++ b/src/NadekoBot/Modules/Utility/Services/RunningRepeater.cs @@ -89,7 +89,7 @@ public sealed class RunningRepeater // interval (2.4h) * 0.834 is 2.0016 and that is the initial interval var initialIntervalMultiplier = 1 - (triggerCount - Math.Truncate(triggerCount)); - return DateTime.UtcNow + Repeater.Interval * initialIntervalMultiplier; + return DateTime.UtcNow + (Repeater.Interval * initialIntervalMultiplier); } public override bool Equals(object obj) diff --git a/src/NadekoBot/Modules/Utility/UnitConversionCommands.cs b/src/NadekoBot/Modules/Utility/UnitConversionCommands.cs index 0d506f7c2..86faccf1b 100644 --- a/src/NadekoBot/Modules/Utility/UnitConversionCommands.cs +++ b/src/NadekoBot/Modules/Utility/UnitConversionCommands.cs @@ -66,7 +66,7 @@ public partial class Utility res = res - 273.15m; //celcius! break; case "F": - res = res * (9m / 5m) - 459.67m; + res = (res * (9m / 5m)) - 459.67m; break; } } diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index 3083ad52f..4c3a8b419 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -58,7 +58,7 @@ public partial class Utility : NadekoModule if (string.IsNullOrWhiteSpace(game)) return; - if (!(ctx.Guild is SocketGuild socketGuild)) + if (ctx.Guild is not SocketGuild socketGuild) { Log.Warning("Can't cast guild to socket guild."); return; @@ -360,7 +360,7 @@ public partial class Utility : NadekoModule public Task ShowEmbed(ulong messageId) => ShowEmbed((ITextChannel)ctx.Channel, messageId); - private static readonly JsonSerializerOptions _showEmbedSerializerOptions = new JsonSerializerOptions() + private static readonly JsonSerializerOptions _showEmbedSerializerOptions = new() { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, @@ -436,7 +436,7 @@ public partial class Utility : NadekoModule await ctx.User.SendFileAsync(stream, title, title, false).ConfigureAwait(false); } } - private static SemaphoreSlim sem = new SemaphoreSlim(1, 1); + private static SemaphoreSlim sem = new(1, 1); [NadekoCommand, Aliases] #if GLOBAL_NADEKO diff --git a/src/NadekoBot/Modules/Xp/Club.cs b/src/NadekoBot/Modules/Xp/Club.cs index 3a3170ddc..dc9f4ee7b 100644 --- a/src/NadekoBot/Modules/Xp/Club.cs +++ b/src/NadekoBot/Modules/Xp/Club.cs @@ -68,7 +68,7 @@ public partial class Xp [NadekoCommand, Aliases] public async Task ClubIcon([Leftover] string url = null) { - if (!Uri.IsWellFormedUriString(url, UriKind.Absolute) && url != null + if ((!Uri.IsWellFormedUriString(url, UriKind.Absolute) && url != null) || !await _service.SetClubIcon(ctx.User.Id, url is null ? null : new Uri(url))) { await ReplyErrorLocalizedAsync(strs.club_icon_error).ConfigureAwait(false); @@ -117,7 +117,7 @@ public partial class Xp if (club.OwnerId == x.Id) return int.MaxValue; else if (x.IsClubAdmin) - return int.MaxValue / 2 + l; + return (int.MaxValue / 2) + l; else return l; }); diff --git a/src/NadekoBot/Modules/Xp/Common/LevelStats.cs b/src/NadekoBot/Modules/Xp/Common/LevelStats.cs index 3b7bf41cf..e747d54e0 100644 --- a/src/NadekoBot/Modules/Xp/Common/LevelStats.cs +++ b/src/NadekoBot/Modules/Xp/Common/LevelStats.cs @@ -23,7 +23,7 @@ public class LevelStats var lvl = 1; while (true) { - required = (int)(baseXp + baseXp / 4.0 * (lvl - 1)); + required = (int)(baseXp + (baseXp / 4.0 * (lvl - 1))); if (required + totalXp > xp) break; diff --git a/src/NadekoBot/Modules/Xp/Common/XpTemplate.cs b/src/NadekoBot/Modules/Xp/Common/XpTemplate.cs index 6c73f6efd..bdfa20e62 100644 --- a/src/NadekoBot/Modules/Xp/Common/XpTemplate.cs +++ b/src/NadekoBot/Modules/Xp/Common/XpTemplate.cs @@ -6,12 +6,12 @@ namespace NadekoBot.Modules.Xp; public class XpTemplate { [JsonProperty("output_size")] - public XpTemplatePos OutputSize { get; set; } = new XpTemplatePos + public XpTemplatePos OutputSize { get; set; } = new() { X = 450, Y = 220, }; - public XpTemplateUser User { get; set; } = new XpTemplateUser + public XpTemplateUser User { get; set; } = new() { Name = new() { @@ -171,7 +171,7 @@ public class XpTemplate } } }; - public XpTemplateClub Club { get; set; } = new XpTemplateClub + public XpTemplateClub Club { get; set; } = new() { Icon = new() { diff --git a/src/NadekoBot/Modules/Xp/Extensions/Extensions.cs b/src/NadekoBot/Modules/Xp/Extensions/Extensions.cs index fccc8f45b..5dd9ce587 100644 --- a/src/NadekoBot/Modules/Xp/Extensions/Extensions.cs +++ b/src/NadekoBot/Modules/Xp/Extensions/Extensions.cs @@ -14,7 +14,7 @@ public static class Extensions var lvl = 1; while (true) { - required = (int)(baseXp + baseXp / 4.0 * (lvl - 1)); + required = (int)(baseXp + (baseXp / 4.0 * (lvl - 1))); if (required + totalXp > stats.Xp) break; diff --git a/src/NadekoBot/Modules/Xp/Services/ClubService.cs b/src/NadekoBot/Modules/Xp/Services/ClubService.cs index 48b789dd5..bb51c640e 100644 --- a/src/NadekoBot/Modules/Xp/Services/ClubService.cs +++ b/src/NadekoBot/Modules/Xp/Services/ClubService.cs @@ -289,7 +289,7 @@ public class ClubService : INService if (usr is null) return false; - if (club.OwnerId == usr.Id || usr.IsClubAdmin && club.Owner.UserId != bannerId) // can't ban the owner kek, whew + if (club.OwnerId == usr.Id || (usr.IsClubAdmin && club.Owner.UserId != bannerId)) // can't ban the owner kek, whew return false; club.Bans.Add(new() @@ -340,7 +340,7 @@ public class ClubService : INService if (usr is null) return false; - if (club.OwnerId == usr.Id || usr.IsClubAdmin && club.Owner.UserId != kickerId) + if (club.OwnerId == usr.Id || (usr.IsClubAdmin && club.Owner.UserId != kickerId)) return false; club.Users.Remove(usr); diff --git a/src/NadekoBot/Modules/Xp/Services/XpConfigService.cs b/src/NadekoBot/Modules/Xp/Services/XpConfigService.cs index 889318f5e..a2d7e37ca 100644 --- a/src/NadekoBot/Modules/Xp/Services/XpConfigService.cs +++ b/src/NadekoBot/Modules/Xp/Services/XpConfigService.cs @@ -6,7 +6,7 @@ public sealed class XpConfigService : ConfigServiceBase { public override string Name { get; } = "xp"; private const string FilePath = "data/xp.yml"; - private static TypedKey changeKey = new TypedKey("config.xp.updated"); + private static readonly TypedKey changeKey = new("config.xp.updated"); public XpConfigService(IConfigSeria serializer, IPubSub pubSub) : base(FilePath, serializer, pubSub, changeKey) diff --git a/src/NadekoBot/Modules/Xp/Services/XpService.cs b/src/NadekoBot/Modules/Xp/Services/XpService.cs index 56dbcafa2..2e542b8e0 100644 --- a/src/NadekoBot/Modules/Xp/Services/XpService.cs +++ b/src/NadekoBot/Modules/Xp/Services/XpService.cs @@ -46,8 +46,7 @@ public class XpService : INService private readonly ConcurrentHashSet _excludedServers; - private readonly ConcurrentQueue _addMessageXp - = new ConcurrentQueue(); + private readonly ConcurrentQueue _addMessageXp = new(); private XpTemplate _template; private readonly DiscordSocketClient _client; @@ -485,7 +484,7 @@ public class XpService : INService private Task _client_OnUserVoiceStateUpdated(SocketUser socketUser, SocketVoiceState before, SocketVoiceState after) { - if (!(socketUser is SocketGuildUser user) || user.IsBot) + if (socketUser is not SocketGuildUser user || user.IsBot) return Task.CompletedTask; var _ = Task.Run(() => @@ -608,7 +607,7 @@ public class XpService : INService private Task _cmd_OnMessageNoTrigger(IUserMessage arg) { - if (!(arg.Author is SocketGuildUser user) || user.IsBot) + if (arg.Author is not SocketGuildUser user || user.IsBot) return Task.CompletedTask; var _ = Task.Run(() => @@ -955,7 +954,7 @@ public class XpService : INService ? "+ " : ""; var awX = _template.User.Xp.Awarded.Pos.X - - Math.Max(0, stats.FullGuildStats.AwardedXp.ToString().Length - 2) * 5; + (Math.Max(0, stats.FullGuildStats.AwardedXp.ToString().Length - 2) * 5); var awY = _template.User.Xp.Awarded.Pos.Y; img.Mutate(x => x.DrawText($"({sign}{stats.FullGuildStats.AwardedXp})", _fonts.NotoSans.CreateFont(_template.User.Xp.Awarded.FontSize, FontStyle.Bold), diff --git a/src/NadekoBot/Modules/Xp/Xp.cs b/src/NadekoBot/Modules/Xp/Xp.cs index b4bf94c20..d3e184589 100644 --- a/src/NadekoBot/Modules/Xp/Xp.cs +++ b/src/NadekoBot/Modules/Xp/Xp.cs @@ -339,7 +339,7 @@ public partial class Xp : NadekoModule await _tracker.EnsureUsersDownloadedAsync(ctx.Guild).ConfigureAwait(false); allUsers = _service.GetTopUserXps(ctx.Guild.Id, 1000) - .Where(user => !(socketGuild.GetUser(user.UserId) is null)) + .Where(user => socketGuild.GetUser(user.UserId) is not null) .ToList(); } @@ -377,7 +377,7 @@ public partial class Xp : NadekoModule awardStr = $"({userXpData.AwardedXp})"; embed.AddField( - $"#{i + 1 + curPage * 9} {user?.ToString() ?? users[i].UserId.ToString()}", + $"#{i + 1 + (curPage * 9)} {user?.ToString() ?? users[i].UserId.ToString()}", $"{GetText(strs.level_x(levelStats.Level))} - {levelStats.TotalXp}xp {awardStr}"); } return embed; @@ -405,7 +405,7 @@ public partial class Xp : NadekoModule { var user = users[i]; embed.AddField( - $"#{i + 1 + page * 9} {user.ToString()}", + $"#{i + 1 + (page * 9)} {user.ToString()}", $"{GetText(strs.level_x(new LevelStats(users[i].TotalXp).Level))} - {users[i].TotalXp}xp"); } } diff --git a/src/NadekoBot/Services/CommandHandler.cs b/src/NadekoBot/Services/CommandHandler.cs index c784a47d9..f05ccd696 100644 --- a/src/NadekoBot/Services/CommandHandler.cs +++ b/src/NadekoBot/Services/CommandHandler.cs @@ -8,7 +8,7 @@ namespace NadekoBot.Services; public class CommandHandler : INService { - public const int GlobalCommandsCooldown = 750; + private const int GlobalCommandsCooldown = 750; private readonly DiscordSocketClient _client; private readonly CommandService _commandService; @@ -24,9 +24,9 @@ public class CommandHandler : INService public event Func OnMessageNoTrigger = delegate { return Task.CompletedTask; }; //userid/msg count - public ConcurrentDictionary UserMessagesSent { get; } = new ConcurrentDictionary(); + public ConcurrentDictionary UserMessagesSent { get; } = new(); - public ConcurrentHashSet UsersOnShortCooldown { get; } = new ConcurrentHashSet(); + public ConcurrentHashSet UsersOnShortCooldown { get; } = new(); private readonly Timer _clearUsersOnShortCooldown; public CommandHandler( @@ -105,9 +105,9 @@ public class CommandHandler : INService if (guildId != null) { var guild = _client.GetGuild(guildId.Value); - if (!(guild?.GetChannel(channelId) is SocketTextChannel channel)) + if (guild?.GetChannel(channelId) is not SocketTextChannel channel) { - Log.Warning("Channel for external execution not found."); + Log.Warning("Channel for external execution not found"); return; } @@ -143,15 +143,16 @@ public class CommandHandler : INService { if (_bss.Data.ConsoleOutputType == ConsoleOutputType.Normal) { - Log.Information($"Command Executed after " + string.Join("/", execPoints.Select(x => (x * _oneThousandth).ToString("F3"))) + "s\n\t" + - "User: {0}\n\t" + - "Server: {1}\n\t" + - "Channel: {2}\n\t" + - "Message: {3}", - usrMsg.Author + " [" + usrMsg.Author.Id + "]", // {0} - channel is null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]", // {1} - channel is null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]", // {2} - usrMsg.Content // {3} + Log.Information(@"Command Executed after {ExecTime}s + User: {User} + Server: {Server} + Channel: {Channel} + Message: {MessageContent}", + string.Join("/", execPoints.Select(x => (x * _oneThousandth).ToString("F3"))), + usrMsg.Author + " [" + usrMsg.Author.Id + "]", + channel is null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]", + channel is null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]", + usrMsg.Content ); } else @@ -169,18 +170,18 @@ public class CommandHandler : INService { if (_bss.Data.ConsoleOutputType == ConsoleOutputType.Normal) { - Log.Warning($"Command Errored after " + string.Join("/", execPoints.Select(x => (x * _oneThousandth).ToString("F3"))) + "s\n\t" + - "User: {0}\n\t" + - "Server: {1}\n\t" + - "Channel: {2}\n\t" + - "Message: {3}\n\t" + - "Error: {4}", - usrMsg.Author + " [" + usrMsg.Author.Id + "]", // {0} - channel is null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]", // {1} - channel is null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]", // {2} - usrMsg.Content,// {3} + Log.Warning(@"Command Errored after {ExecTime}s + User: {User} + Server: {Server} + Channel: {Channel} + Message: {MessageContent} + Error: {ErrorMessage}", + string.Join("/", execPoints.Select(x => (x * _oneThousandth).ToString("F3"))), + usrMsg.Author + " [" + usrMsg.Author.Id + "]", + channel is null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]", + channel is null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]", + usrMsg.Content, errorMessage - //exec.Result.ErrorReason // {4} ); } else @@ -196,19 +197,20 @@ public class CommandHandler : INService private async Task MessageReceivedHandler(SocketMessage msg) { + try { if (msg.Author.IsBot || !_bot.IsReady) //no bots, wait until bot connected and initialized return; - if (!(msg is SocketUserMessage usrMsg)) + if (msg is not SocketUserMessage usrMsg) return; #if !GLOBAL_NADEKO // track how many messagges each user is sending UserMessagesSent.AddOrUpdate(usrMsg.Author.Id, 1, (key, old) => ++old); #endif - var channel = msg.Channel as ISocketMessageChannel; + var channel = msg.Channel; var guild = (msg.Channel as SocketTextChannel)?.Guild; await TryRunCommand(guild, channel, usrMsg).ConfigureAwait(false); @@ -240,20 +242,20 @@ public class CommandHandler : INService // execute the command and measure the time it took if (messageContent.StartsWith(prefix, StringComparison.InvariantCulture) || isPrefixCommand) { - var (Success, Error, Info) = await ExecuteCommandAsync(new(_client, usrMsg), messageContent, isPrefixCommand ? 1 : prefix.Length, _services, MultiMatchHandling.Best).ConfigureAwait(false); + var (success, error, info) = await ExecuteCommandAsync(new(_client, usrMsg), messageContent, isPrefixCommand ? 1 : prefix.Length, _services, MultiMatchHandling.Best).ConfigureAwait(false); startTime = Environment.TickCount - startTime; - if (Success) + if (success) { await LogSuccessfulExecution(usrMsg, channel as ITextChannel, blockTime, startTime).ConfigureAwait(false); - await CommandExecuted(usrMsg, Info).ConfigureAwait(false); + await CommandExecuted(usrMsg, info).ConfigureAwait(false); return; } - else if (Error != null) + else if (error != null) { - LogErroredExecution(Error, usrMsg, channel as ITextChannel, blockTime, startTime); + LogErroredExecution(error, usrMsg, channel as ITextChannel, blockTime, startTime); if (guild != null) - await CommandErrored(Info, channel as ITextChannel, Error).ConfigureAwait(false); + await CommandErrored(info, channel as ITextChannel, error).ConfigureAwait(false); } } else @@ -330,12 +332,13 @@ public class CommandHandler : INService } var totalArgsScore = (argValuesScore + paramValuesScore) / 2; - return match.Command.Priority + totalArgsScore * 0.99f; + return match.Command.Priority + (totalArgsScore * 0.99f); } //Order the parse results by their score so that we choose the most likely result to execute var parseResults = parseResultsDict - .OrderByDescending(x => CalculateScore(x.Key, x.Value)); + .OrderByDescending(x => CalculateScore(x.Key, x.Value)) + .ToList(); var successfulParses = parseResults .Where(x => x.Value.IsSuccess) @@ -365,7 +368,7 @@ public class CommandHandler : INService var chosenOverload = successfulParses[0]; var execResult = (Discord.Commands.ExecuteResult)await chosenOverload.Key.ExecuteAsync(context, chosenOverload.Value, services).ConfigureAwait(false); - if (execResult.Exception != null && (!(execResult.Exception is HttpException he) || he.DiscordCode != DiscordErrorCode.InsufficientPermissions)) + if (execResult.Exception != null && (execResult.Exception is not HttpException he || he.DiscordCode != DiscordErrorCode.InsufficientPermissions)) { Log.Warning(execResult.Exception, "Command Error"); } diff --git a/src/NadekoBot/Services/Common/GreetGrouper.cs b/src/NadekoBot/Services/Common/GreetGrouper.cs index 9323d7926..18ab816a4 100644 --- a/src/NadekoBot/Services/Common/GreetGrouper.cs +++ b/src/NadekoBot/Services/Common/GreetGrouper.cs @@ -3,7 +3,7 @@ public class GreetGrouper { private readonly Dictionary> group; - private readonly object locker = new object(); + private readonly object locker = new(); public GreetGrouper() { diff --git a/src/NadekoBot/Services/GreetSettingsService.cs b/src/NadekoBot/Services/GreetSettingsService.cs index 4ef84f2a2..3ef10a5bb 100644 --- a/src/NadekoBot/Services/GreetSettingsService.cs +++ b/src/NadekoBot/Services/GreetSettingsService.cs @@ -10,8 +10,8 @@ public class GreetSettingsService : INService public ConcurrentDictionary GuildConfigsCache { get; } private readonly DiscordSocketClient _client; - private GreetGrouper greets = new GreetGrouper(); - private GreetGrouper byes = new GreetGrouper(); + private readonly GreetGrouper greets = new(); + private readonly GreetGrouper byes = new(); private readonly BotConfigService _bss; private readonly IEmbedBuilderService _eb; public bool GroupGreets => _bss.Data.GroupGreets; @@ -634,7 +634,7 @@ public class GreetSettings public int BoostMessageDeleteAfter { get; set; } public ulong BoostMessageChannelId { get; set; } - public static GreetSettings Create(GuildConfig g) => new GreetSettings() + public static GreetSettings Create(GuildConfig g) => new() { AutoDeleteByeMessagesTimer = g.AutoDeleteByeMessagesTimer, AutoDeleteGreetMessagesTimer = g.AutoDeleteGreetMessagesTimer, diff --git a/src/NadekoBot/Services/Impl/BotCredsProvider.cs b/src/NadekoBot/Services/Impl/BotCredsProvider.cs index b66ff38d8..877271ddc 100644 --- a/src/NadekoBot/Services/Impl/BotCredsProvider.cs +++ b/src/NadekoBot/Services/Impl/BotCredsProvider.cs @@ -24,11 +24,11 @@ public sealed class BotCredsProvider : IBotCredsProvider private string OldCredsJsonBackupPath => Path.Combine(Directory.GetCurrentDirectory(), "credentials.json.bak"); - private Creds _creds = new Creds(); - private IConfigurationRoot _config; + private readonly Creds _creds = new(); + private readonly IConfigurationRoot _config; - private readonly object reloadLock = new object(); + private readonly object reloadLock = new(); public void Reload() { lock (reloadLock) diff --git a/src/NadekoBot/Services/Impl/CurrencyService.cs b/src/NadekoBot/Services/Impl/CurrencyService.cs index 9e1036df1..438649df9 100644 --- a/src/NadekoBot/Services/Impl/CurrencyService.cs +++ b/src/NadekoBot/Services/Impl/CurrencyService.cs @@ -21,7 +21,7 @@ public class CurrencyService : ICurrencyService, INService } private CurrencyTransaction GetCurrencyTransaction(ulong userId, string reason, long amount) => - new CurrencyTransaction + new() { Amount = amount, UserId = userId, diff --git a/src/NadekoBot/Services/Impl/GoogleApiService.cs b/src/NadekoBot/Services/Impl/GoogleApiService.cs index 1e5b9062c..2bcece9d2 100644 --- a/src/NadekoBot/Services/Impl/GoogleApiService.cs +++ b/src/NadekoBot/Services/Impl/GoogleApiService.cs @@ -13,9 +13,9 @@ public class GoogleApiService : IGoogleApiService, INService { private const string SearchEngineId = "018084019232060951019:hs5piey28-e"; - private YouTubeService yt; - private UrlshortenerService sh; - private CustomsearchService cs; + private readonly YouTubeService yt; + private readonly UrlshortenerService sh; + private readonly CustomsearchService cs; public GoogleApiService(IBotCredentials creds, IHttpClientFactory factory) { @@ -32,7 +32,7 @@ public class GoogleApiService : IGoogleApiService, INService sh = new(bcs); cs = new(bcs); } - private static readonly Regex plRegex = new Regex("(?:youtu\\.be\\/|list=)(?[\\da-zA-Z\\-_]*)", RegexOptions.Compiled); + private static readonly Regex plRegex = new("(?:youtu\\.be\\/|list=)(?[\\da-zA-Z\\-_]*)", RegexOptions.Compiled); public async Task> GetPlaylistIdsByKeywordsAsync(string keywords, int count = 1) { await Task.Yield(); diff --git a/src/NadekoBot/Services/Impl/RedisCache.cs b/src/NadekoBot/Services/Impl/RedisCache.cs index 95ac49329..755ea3580 100644 --- a/src/NadekoBot/Services/Impl/RedisCache.cs +++ b/src/NadekoBot/Services/Impl/RedisCache.cs @@ -67,7 +67,7 @@ public class RedisCache : IDataCache return _db.StringSetAsync("novel_" + key, data, expiry: TimeSpan.FromHours(3)); } - private readonly object timelyLock = new object(); + private readonly object timelyLock = new(); public TimeSpan? AddTimelyClaim(ulong id, int period) { if (period == 0) diff --git a/src/NadekoBot/Services/Impl/SoundCloudApiService.cs b/src/NadekoBot/Services/Impl/SoundCloudApiService.cs index ca0fa4ff0..723a6bd7a 100644 --- a/src/NadekoBot/Services/Impl/SoundCloudApiService.cs +++ b/src/NadekoBot/Services/Impl/SoundCloudApiService.cs @@ -55,7 +55,7 @@ public class SoundCloudVideo { public string Kind { get; set; } = string.Empty; public long Id { get; set; } = 0; - public SoundCloudUser User { get; set; } = new SoundCloudUser(); + public SoundCloudUser User { get; set; } = new(); public string Title { get; set; } = string.Empty; public string FullName => User.Name + " - " + Title; public bool? Streamable { get; set; } = false; diff --git a/src/NadekoBot/Services/Settings/BotConfigService.cs b/src/NadekoBot/Services/Settings/BotConfigService.cs index d8e4e1c0b..dd1952650 100644 --- a/src/NadekoBot/Services/Settings/BotConfigService.cs +++ b/src/NadekoBot/Services/Settings/BotConfigService.cs @@ -11,7 +11,7 @@ public sealed class BotConfigService : ConfigServiceBase public override string Name { get; } = "bot"; private const string FilePath = "data/bot.yml"; - private static TypedKey changeKey = new TypedKey("config.bot.updated"); + private static readonly TypedKey changeKey = new("config.bot.updated"); public BotConfigService(IConfigSeria serializer, IPubSub pubSub) : base(FilePath, serializer, pubSub, changeKey) diff --git a/src/NadekoBot/Services/Settings/ConfigParsers.cs b/src/NadekoBot/Services/Settings/ConfigParsers.cs index 9890d5d7e..870cabc64 100644 --- a/src/NadekoBot/Services/Settings/ConfigParsers.cs +++ b/src/NadekoBot/Services/Settings/ConfigParsers.cs @@ -41,5 +41,5 @@ public static class ConfigPrinters => culture.Name; public static string Color(Rgba32 color) - => ((uint) (color.B << 0 | color.G << 8 | color.R << 16)).ToString("X6"); + => ((uint) ((color.B << 0) | (color.G << 8) | (color.R << 16))).ToString("X6"); } \ No newline at end of file diff --git a/src/NadekoBot/Services/Settings/ConfigServiceBase.cs b/src/NadekoBot/Services/Settings/ConfigServiceBase.cs index e1943db06..0dd4c035a 100644 --- a/src/NadekoBot/Services/Settings/ConfigServiceBase.cs +++ b/src/NadekoBot/Services/Settings/ConfigServiceBase.cs @@ -95,10 +95,10 @@ public abstract class ConfigServiceBase : IConfigService File.WriteAllText(_filePath, strData); } - private readonly Dictionary> _propSetters = new Dictionary>(); - private readonly Dictionary> _propSelectors = new Dictionary>(); - private readonly Dictionary> _propPrinters = new Dictionary>(); - private readonly Dictionary _propComments = new Dictionary(); + private readonly Dictionary> _propSetters = new(); + private readonly Dictionary> _propSelectors = new(); + private readonly Dictionary> _propPrinters = new(); + private readonly Dictionary _propComments = new(); protected void AddParsedProp( string key, diff --git a/src/NadekoBot/Services/StandardConversions.cs b/src/NadekoBot/Services/StandardConversions.cs index dd412eae2..c1f4d9514 100644 --- a/src/NadekoBot/Services/StandardConversions.cs +++ b/src/NadekoBot/Services/StandardConversions.cs @@ -4,6 +4,6 @@ public static class StandardConversions { public static double CelsiusToFahrenheit(double cel) { - return cel * 1.8f + 32; + return (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 99b5f4489..f8b398aaf 100644 --- a/src/NadekoBot/Services/strings/impl/BotStrings.cs +++ b/src/NadekoBot/Services/strings/impl/BotStrings.cs @@ -8,7 +8,7 @@ public class BotStrings : IBotStrings /// /// Used as failsafe in case response key doesn't exist in the selected or default language. /// - private readonly CultureInfo _usCultureInfo = new CultureInfo("en-US"); + private readonly CultureInfo _usCultureInfo = new("en-US"); private readonly ILocalization _localization; private readonly IBotStringsProvider _stringsProvider; diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index a63bd2fab..4cdab1d67 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -20,7 +20,7 @@ namespace NadekoBot.Extensions; public static class Extensions { - public static Regex UrlRegex = new Regex(@"^(https?|ftp)://(?[^\s/$.?#].[^\s]*)$", RegexOptions.Compiled); + public static Regex UrlRegex = new(@"^(https?|ftp)://(?[^\s/$.?#].[^\s]*)$", RegexOptions.Compiled); public static Task EditAsync(this IUserMessage msg, SmartText text) @@ -69,7 +69,7 @@ public static class Extensions public static IEmote ToIEmote(this string emojiStr) => Emote.TryParse(emojiStr, out var maybeEmote) - ? (IEmote)maybeEmote + ? maybeEmote : new Emoji(emojiStr); // https://github.com/SixLabors/Samples/blob/master/ImageSharp/AvatarWithRoundedCorner/Program.cs @@ -171,8 +171,7 @@ public static class Extensions return embed.WithFooter(curPage.ToString()); } - public static Color ToDiscordColor(this Rgba32 color) - => new Color(color.R, color.G, color.B); + 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); diff --git a/src/NadekoBot/_Extensions/IEnumerableExtensions.cs b/src/NadekoBot/_Extensions/IEnumerableExtensions.cs index 629584198..4759b9419 100644 --- a/src/NadekoBot/_Extensions/IEnumerableExtensions.cs +++ b/src/NadekoBot/_Extensions/IEnumerableExtensions.cs @@ -33,7 +33,7 @@ public static class IEnumerableExtensions var n = list.Count; while (n > 1) { - var box = new byte[n / Byte.MaxValue + 1]; + var box = new byte[(n / Byte.MaxValue) + 1]; int boxSum; do { @@ -62,12 +62,11 @@ public static class IEnumerableExtensions return realElems; } - public static ConcurrentDictionary ToConcurrent(this IEnumerable> dict) - => new ConcurrentDictionary(dict); + public static ConcurrentDictionary ToConcurrent( + this IEnumerable> dict) => new(dict); - public static IndexedCollection ToIndexed(this IEnumerable enumerable) - where T : class, IIndexed - => new IndexedCollection(enumerable); + public static IndexedCollection ToIndexed(this IEnumerable enumerable) where T : class, IIndexed => + new(enumerable); public static Task WhenAll(this IEnumerable> items) => Task.WhenAll(items); diff --git a/src/NadekoBot/_Extensions/StringExtensions.cs b/src/NadekoBot/_Extensions/StringExtensions.cs index eb045b4a1..72fecad45 100644 --- a/src/NadekoBot/_Extensions/StringExtensions.cs +++ b/src/NadekoBot/_Extensions/StringExtensions.cs @@ -10,14 +10,14 @@ public static class StringExtensions public static string PadBoth(this string str, int length) { var spaces = length - str.Length; - var padLeft = spaces / 2 + str.Length; + 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 HashSet(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)); @@ -102,7 +102,7 @@ public static class StringExtensions return ms; } - private static readonly Regex filterRegex = new Regex(@"discord(?:\.gg|\.io|\.me|\.li|(?:app)?\.com\/invite)\/(\w+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); + 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); @@ -137,7 +137,7 @@ public static class StringExtensions txt.All(c => lettersAndDigits.Contains(c)); private static readonly Regex CodePointRegex - = new Regex(@"(\\U(?[a-zA-Z0-9]{8})|\\u(?[a-zA-Z0-9]{4})|\\x(?[a-zA-Z0-9]{2}))", + = 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)