Kotz's editorconfig styles slightly modified. Target typed new usage. Brackets in expressions used for clarity.

This commit is contained in:
Kwoth
2021-12-26 02:52:09 +01:00
parent 68741ec484
commit d18f9429c6
172 changed files with 921 additions and 494 deletions

111
.editorconfig Normal file
View File

@@ -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

View File

@@ -0,0 +1,8 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/MAX_INVOCATION_ARGUMENTS_ON_LINE/@EntryValue">3</s:Int64>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/NESTED_TERNARY_STYLE/@EntryValue">EXPANDED</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_AFTER_INVOCATION_LPAR/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_ARGUMENTS_STYLE/@EntryValue">CHOP_IF_LONG</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_BEFORE_INVOCATION_RPAR/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_CHAINED_METHOD_CALLS/@EntryValue">CHOP_IF_LONG</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_LINQ_EXPRESSIONS/@EntryValue">CHOP_ALWAYS</s:String></wpf:ResourceDictionary>

328
src/NadekoBot/.editorconfig Normal file
View File

@@ -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

View File

@@ -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;

View File

@@ -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<Dictionary<string, string[]>> LazyCommandAliases
= new Lazy<Dictionary<string, string[]>>(() => LoadCommandNames());
public static Lazy<Dictionary<string, string[]>> LazyCommandAliases = new(() => LoadCommandNames());
public static Dictionary<string, string[]> LoadCommandNames(string aliasesFilePath = "data/aliases.yml")
{
var text = File.ReadAllText(aliasesFilePath);

View File

@@ -344,7 +344,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
Node previous = null;
for (var current = tables.Buckets[bucketNo]; current != null; current = current.Next)
{
Debug.Assert(previous is null && current == tables.Buckets[bucketNo] || previous.Next == current);
Debug.Assert((previous is null && current == tables.Buckets[bucketNo]) || previous.Next == current);
if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
{
@@ -470,7 +470,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
Node previous = null;
for (var current = tables.Buckets[bucketNo]; current != null; current = current.Next)
{
Debug.Assert(previous is null && current == tables.Buckets[bucketNo] || previous.Next == current);
Debug.Assert((previous is null && current == tables.Buckets[bucketNo]) || previous.Next == current);
if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
{
return false;
@@ -581,7 +581,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
checked
{
// Double the size of the buckets table and add one, so that we have an odd integer.
newLength = tables.Buckets.Length * 2 + 1;
newLength = (tables.Buckets.Length * 2) + 1;
// Now, we only need to check odd integers, and find the first that is not divisible
// by 3, 5 or 7.

View File

@@ -6,7 +6,7 @@ namespace NadekoBot.Common.Collections;
public class IndexedCollection<T> : IList<T> where T : class, IIndexed
{
public List<T> Source { get; }
private readonly object _locker = new object();
private readonly object _locker = new();
public int Count => Source.Count;
public bool IsReadOnly => false;

View File

@@ -2,8 +2,8 @@
public class DownloadTracker : INService
{
private ConcurrentDictionary<ulong, DateTime> LastDownloads { get; } = new ConcurrentDictionary<ulong, DateTime>();
private SemaphoreSlim downloadUsersSemaphore = new SemaphoreSlim(1, 1);
private ConcurrentDictionary<ulong, DateTime> LastDownloads { get; } = new();
private readonly SemaphoreSlim downloadUsersSemaphore = new(1, 1);
/// <summary>
/// Ensures all users on the specified guild were downloaded within the last hour.

View File

@@ -49,7 +49,7 @@ public readonly struct kwum : IEquatable<kwum>
}
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<kwum>
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<kwum>
while (localValue > 0)
{
localValue = Math.DivRem(localValue, count, out var rem);
chars[--arrSize] = ValidCharacters[(int)rem];
chars[--arrSize] = ValidCharacters[rem];
}
return new(chars);

View File

@@ -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)
{

View File

@@ -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()

View File

@@ -2,9 +2,8 @@
public class EventPubSub : IPubSub
{
private readonly Dictionary<string, Dictionary<Delegate, List<Func<object, ValueTask>>>> _actions
= new Dictionary<string, Dictionary<Delegate, List<Func<object, ValueTask>>>>();
private readonly object locker = new object();
private readonly Dictionary<string, Dictionary<Delegate, List<Func<object, ValueTask>>>> _actions = new();
private readonly object locker = new();
public Task Sub<TData>(in TypedKey<TData> key, Func<TData, ValueTask> action)
{

View File

@@ -5,7 +5,7 @@ namespace NadekoBot.Common;
public class JsonSeria : ISeria
{
private JsonSerializerOptions serializerOptions = new JsonSerializerOptions()
private readonly JsonSerializerOptions serializerOptions = new()
{
Converters =
{

View File

@@ -10,7 +10,7 @@ public readonly struct TypedKey<TData>
}
public static implicit operator TypedKey<TData>(in string input)
=> new TypedKey<TData>(input);
=> new(input);
public static implicit operator string(in TypedKey<TData> input)
=> input.Key;

View File

@@ -11,7 +11,7 @@ public class YamlSeria : IConfigSeria
private readonly IDeserializer _deserializer;
private static readonly Regex CodePointRegex
= new Regex(@"(\\U(?<code>[a-zA-Z0-9]{8})|\\u(?<code>[a-zA-Z0-9]{4})|\\x(?<code>[a-zA-Z0-9]{2}))",
= new(@"(\\U(?<code>[a-zA-Z0-9]{8})|\\u(?<code>[a-zA-Z0-9]{4})|\\x(?<code>[a-zA-Z0-9]{2}))",
RegexOptions.Compiled);
public YamlSeria()

View File

@@ -5,9 +5,9 @@ namespace NadekoBot.Common;
public class ReplacementBuilder
{
private static readonly Regex rngRegex = new Regex("%rng(?:(?<from>(?:-)?\\d+)-(?<to>(?:-)?\\d+))?%", RegexOptions.Compiled);
private ConcurrentDictionary<string, Func<string>> _reps = new ConcurrentDictionary<string, Func<string>>();
private ConcurrentDictionary<Regex, Func<Match, string>> _regex = new ConcurrentDictionary<Regex, Func<Match, string>>();
private static readonly Regex rngRegex = new("%rng(?:(?<from>(?:-)?\\d+)-(?<to>(?:-)?\\d+))?%", RegexOptions.Compiled);
private readonly ConcurrentDictionary<string, Func<string>> _reps = new();
private readonly ConcurrentDictionary<Regex, Func<Match, string>> _regex = new();
public ReplacementBuilder()
{

View File

@@ -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)

View File

@@ -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;

View File

@@ -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; }

View File

@@ -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(
@"^(?:(?<months>\d)mo)?(?:(?<weeks>\d{1,2})w)?(?:(?<days>\d{1,2})d)?(?:(?<hours>\d{1,4})h)?(?:(?<minutes>\d{1,5})m)?(?:(?<seconds>\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"],

View File

@@ -68,7 +68,7 @@ public sealed class ShmartNumberTypeReader : NadekoTypeReader<ShmartNumber>
}
}
private static readonly Regex percentRegex = new Regex(@"^((?<num>100|\d{1,2})%)$", RegexOptions.Compiled);
private static readonly Regex percentRegex = new(@"^((?<num>100|\d{1,2})%)$", RegexOptions.Compiled);
private long Cur(ICommandContext ctx)
{

View File

@@ -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()));
}
}

View File

@@ -32,12 +32,12 @@ public static class GuildConfigExtensions
}
private static List<WarningPunishment> DefaultWarnPunishments =>
new List<WarningPunishment>() {
new WarningPunishment() {
new() {
new() {
Count = 3,
Punishment = PunishmentAction.Kick
},
new WarningPunishment() {
new() {
Count = 5,
Punishment = PunishmentAction.Ban
}

View File

@@ -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<AntiSpamIgnore> IgnoredChannels { get; set; } = new HashSet<AntiSpamIgnore>();
public HashSet<AntiSpamIgnore> IgnoredChannels { get; set; } = new();
}
public class AntiAltSetting

View File

@@ -16,10 +16,10 @@ public class ClubInfo : DbEntity
public int OwnerId { get; set; }
public DiscordUser Owner { get; set; }
public List<DiscordUser> Users { get; set; } = new List<DiscordUser>();
public List<DiscordUser> Users { get; set; } = new();
public List<ClubApplicants> Applicants { get; set; } = new List<ClubApplicants>();
public List<ClubBans> Bans { get; set; } = new List<ClubBans>();
public List<ClubApplicants> Applicants { get; set; } = new();
public List<ClubBans> Bans { get; set; } = new();
public string Description { get; set; }
public override string ToString()

View File

@@ -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,

View File

@@ -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());
}

View File

@@ -10,7 +10,7 @@ public class GuildConfig : DbEntity
public string Prefix { get; set; } = null;
public bool DeleteMessageOnCommand { get; set; }
public HashSet<DelMsgOnCmdChannel> DelMsgOnCmdChannels { get; set; } = new HashSet<DelMsgOnCmdChannel>();
public HashSet<DelMsgOnCmdChannel> 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<FollowedStream> FollowedStreams { get; set; } = new HashSet<FollowedStream>();
public HashSet<FollowedStream> FollowedStreams { get; set; } = new();
//currencyGeneration
public HashSet<GCChannelId> GenerateCurrencyChannelIds { get; set; } = new HashSet<GCChannelId>();
public HashSet<GCChannelId> GenerateCurrencyChannelIds { get; set; } = new();
public List<Permissionv2> Permissions { get; set; }
public bool VerbosePermissions { get; set; } = true;
public string PermissionRole { get; set; } = null;
public HashSet<CommandCooldown> CommandCooldowns { get; set; } = new HashSet<CommandCooldown>();
public HashSet<CommandCooldown> CommandCooldowns { get; set; } = new();
//filtering
public bool FilterInvites { get; set; }
public bool FilterLinks { get; set; }
public HashSet<FilterChannelId> FilterInvitesChannelIds { get; set; } = new HashSet<FilterChannelId>();
public HashSet<FilterLinksChannelId> FilterLinksChannelIds { get; set; } = new HashSet<FilterLinksChannelId>();
public HashSet<FilterChannelId> FilterInvitesChannelIds { get; set; } = new();
public HashSet<FilterLinksChannelId> FilterLinksChannelIds { get; set; } = new();
//public bool FilterLinks { get; set; }
//public HashSet<FilterLinksChannelId> FilterLinksChannels { get; set; } = new HashSet<FilterLinksChannelId>();
public bool FilterWords { get; set; }
public HashSet<FilteredWord> FilteredWords { get; set; } = new HashSet<FilteredWord>();
public HashSet<FilterChannelId> FilterWordsChannelIds { get; set; } = new HashSet<FilterChannelId>();
public HashSet<FilteredWord> FilteredWords { get; set; } = new();
public HashSet<FilterChannelId> FilterWordsChannelIds { get; set; } = new();
public HashSet<MutedUserId> MutedUsers { get; set; } = new HashSet<MutedUserId>();
public HashSet<MutedUserId> 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<UnmuteTimer> UnmuteTimers { get; set; } = new HashSet<UnmuteTimer>();
public HashSet<UnbanTimer> UnbanTimer { get; set; } = new HashSet<UnbanTimer>();
public HashSet<UnroleTimer> UnroleTimer { get; set; } = new HashSet<UnroleTimer>();
public HashSet<UnmuteTimer> UnmuteTimers { get; set; } = new();
public HashSet<UnbanTimer> UnbanTimer { get; set; } = new();
public HashSet<UnroleTimer> UnroleTimer { get; set; } = new();
public HashSet<VcRoleInfo> VcRoleInfos { get; set; }
public HashSet<CommandAlias> CommandAliases { get; set; } = new HashSet<CommandAlias>();
public List<WarningPunishment> WarnPunishments { get; set; } = new List<WarningPunishment>();
public HashSet<CommandAlias> CommandAliases { get; set; } = new();
public List<WarningPunishment> WarnPunishments { get; set; } = new();
public bool WarningsInitialized { get; set; }
public HashSet<SlowmodeIgnoredUser> SlowmodeIgnoredUsers { get; set; }
public HashSet<SlowmodeIgnoredRole> SlowmodeIgnoredRoles { get; set; }
@@ -97,8 +97,8 @@ public class GuildConfig : DbEntity
public StreamRoleSettings StreamRole { get; set; }
public XpSettings XpSettings { get; set; }
public List<FeedSub> FeedSubs { get; set; } = new List<FeedSub>();
public IndexedCollection<ReactionRoleMessage> ReactionRoleMessages { get; set; } = new IndexedCollection<ReactionRoleMessage>();
public List<FeedSub> FeedSubs { get; set; } = new();
public IndexedCollection<ReactionRoleMessage> ReactionRoleMessages { get; set; } = new();
public bool NotifyStreamOffline { get; set; }
public List<GroupName> SelfAssignableRoleGroupNames { get; set; }
public int WarnExpireHours { get; set; } = 0;

View File

@@ -2,7 +2,7 @@
public class LogSetting : DbEntity
{
public List<IgnoredLogItem> LogIgnores { get; set; } = new List<IgnoredLogItem>();
public List<IgnoredLogItem> LogIgnores { get; set; } = new();
public ulong GuildId { get; set; }
public ulong? LogOtherId { get; set; }

View File

@@ -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<PlaylistSong> Songs { get; set; } = new List<PlaylistSong>();
public List<PlaylistSong> Songs { get; set; } = new();
}

View File

@@ -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<Permissionv2> GetDefaultPermlist =>
new List<Permissionv2>
new()
{
AllowAllPerm
};

View File

@@ -8,7 +8,7 @@ public class Poll : DbEntity
public ulong ChannelId { get; set; }
public string Question { get; set; }
public IndexedCollection<PollAnswer> Answers { get; set; }
public HashSet<PollVote> Votes { get; set; } = new HashSet<PollVote>();
public HashSet<PollVote> Votes { get; set; } = new();
}
public class PollAnswer : DbEntity, IIndexed

View File

@@ -21,7 +21,7 @@ public class ShopEntry : DbEntity, IIndexed
public ulong RoleId { get; set; }
//list
public HashSet<ShopEntryItem> Items { get; set; } = new HashSet<ShopEntryItem>();
public HashSet<ShopEntryItem> Items { get; set; } = new();
}
public class ShopEntryItem : DbEntity

View File

@@ -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.
/// </summary>
public HashSet<StreamRoleWhitelistedUser> Whitelist { get; set; } = new HashSet<StreamRoleWhitelistedUser>();
public HashSet<StreamRoleWhitelistedUser> Whitelist { get; set; } = new();
/// <summary>
/// A collection of blacklisted users' IDs. Blacklisted useres will never get the stream role.
/// </summary>
public HashSet<StreamRoleBlacklistedUser> Blacklist { get; set; } = new HashSet<StreamRoleBlacklistedUser>();
public HashSet<StreamRoleBlacklistedUser> 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;

View File

@@ -14,7 +14,7 @@ public class WaifuInfo : DbEntity
public DiscordUser Affinity { get; set; }
public int Price { get; set; }
public List<WaifuItem> Items { get; set; } = new List<WaifuItem>();
public List<WaifuItem> Items { get; set; } = new();
public override string ToString()
{

View File

@@ -5,9 +5,9 @@ public class XpSettings : DbEntity
public int GuildConfigId { get; set; }
public GuildConfig GuildConfig { get; set; }
public HashSet<XpRoleReward> RoleRewards { get; set; } = new HashSet<XpRoleReward>();
public HashSet<XpCurrencyReward> CurrencyRewards { get; set; } = new HashSet<XpCurrencyReward>();
public HashSet<ExcludedItem> ExclusionList { get; set; } = new HashSet<ExcludedItem>();
public HashSet<XpRoleReward> RoleRewards { get; set; } = new();
public HashSet<XpCurrencyReward> CurrencyRewards { get; set; } = new();
public HashSet<ExcludedItem> ExclusionList { get; set; } = new();
public bool ServerExcluded { get; set; }
}

View File

@@ -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<WaifuUpdate>();
#endregion
#region DiscordUser

View File

@@ -14,14 +14,13 @@ public class AntiRaidStats
{
public AntiRaidSetting AntiRaidSettings { get; set; }
public int UsersCount { get; set; }
public ConcurrentHashSet<IGuildUser> RaidUsers { get; set; } = new ConcurrentHashSet<IGuildUser>();
public ConcurrentHashSet<IGuildUser> RaidUsers { get; set; } = new();
}
public class AntiSpamStats
{
public AntiSpamSetting AntiSpamSettings { get; set; }
public ConcurrentDictionary<ulong, UserSpamStats> UserStats { get; set; }
= new ConcurrentDictionary<ulong, UserSpamStats>();
public ConcurrentDictionary<ulong, UserSpamStats> UserStats { get; set; } = new();
}
public class AntiAltStats

View File

@@ -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))

View File

@@ -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
{

View File

@@ -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)}

View File

@@ -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()

View File

@@ -14,7 +14,7 @@ public sealed class AutoAssignRoleService : INService
//guildid/roleid
private readonly ConcurrentDictionary<ulong, IReadOnlyList<ulong>> _autoAssignableRoles;
private Channel<SocketGuildUser> _assignQueue = Channel.CreateBounded<SocketGuildUser>(
private readonly Channel<SocketGuildUser> _assignQueue = Channel.CreateBounded<SocketGuildUser>(
new BoundedChannelOptions(100)
{
FullMode = BoundedChannelFullMode.DropOldest,

View File

@@ -41,7 +41,7 @@ public class DiscordPermOverrideService : INService, ILateBlocker
public Task<PreconditionResult> 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);
}

View File

@@ -6,7 +6,7 @@ namespace NadekoBot.Modules.Administration.Services;
// todo if any activity...
public class GameVoiceChannelService : INService
{
public ConcurrentHashSet<ulong> GameVoiceChannels { get; } = new ConcurrentHashSet<ulong>();
public ConcurrentHashSet<ulong> 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;

View File

@@ -5,7 +5,7 @@ namespace NadekoBot.Modules.Administration.Services;
public class GuildTimezoneService : INService
{
public static ConcurrentDictionary<ulong, GuildTimezoneService> AllServices { get; } = new ConcurrentDictionary<ulong, GuildTimezoneService>();
public static ConcurrentDictionary<ulong, GuildTimezoneService> AllServices { get; } = new();
private readonly ConcurrentDictionary<ulong, TimeZoneInfo> _timezones;
private readonly DbService _db;

View File

@@ -14,7 +14,7 @@ public sealed class ImageOnlyChannelService : IEarlyBehavior
private readonly DbService _db;
private readonly ConcurrentDictionary<ulong, ConcurrentHashSet<ulong>> _enabledOn;
private Channel<IUserMessage> _deleteQueue = Channel.CreateBounded<IUserMessage>(new BoundedChannelOptions(100)
private readonly Channel<IUserMessage> _deleteQueue = Channel.CreateBounded<IUserMessage>(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);
}

View File

@@ -49,8 +49,7 @@ public sealed class LogCommandService : ILogCommandService
public ConcurrentDictionary<ulong, LogSetting> GuildLogSettings { get; }
private ConcurrentDictionary<ITextChannel, List<string>> PresenceUpdates { get; } =
new ConcurrentDictionary<ITextChannel, List<string>>();
private ConcurrentDictionary<ITextChannel, List<string>> 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<ulong> _ignoreMessageIds = new ConcurrentHashSet<ulong>();
private readonly ConcurrentHashSet<ulong> _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)

View File

@@ -17,14 +17,13 @@ public class MuteService : INService
public ConcurrentDictionary<ulong, string> GuildMuteRoles { get; }
public ConcurrentDictionary<ulong, ConcurrentHashSet<ulong>> MutedUsers { get; }
public ConcurrentDictionary<ulong, ConcurrentDictionary<(ulong, TimerType), Timer>> Un_Timers { get; }
= new ConcurrentDictionary<ulong, ConcurrentDictionary<(ulong, TimerType), Timer>>();
public ConcurrentDictionary<ulong, ConcurrentDictionary<(ulong, TimerType), Timer>> Un_Timers { get; } = new();
public event Action<IGuildUser, IUser, MuteType, string> UserMuted = delegate { };
public event Action<IGuildUser, IUser, MuteType, string> 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;

View File

@@ -8,14 +8,11 @@ namespace NadekoBot.Modules.Administration.Services;
public class ProtectionService : INService
{
private readonly ConcurrentDictionary<ulong, AntiRaidStats> _antiRaidGuilds
= new ConcurrentDictionary<ulong, AntiRaidStats>();
private readonly ConcurrentDictionary<ulong, AntiRaidStats> _antiRaidGuilds = new();
private readonly ConcurrentDictionary<ulong, AntiSpamStats> _antiSpamGuilds
= new ConcurrentDictionary<ulong, AntiSpamStats>();
private readonly ConcurrentDictionary<ulong, AntiSpamStats> _antiSpamGuilds = new();
private readonly ConcurrentDictionary<ulong, AntiAltStats> _antiAltGuilds
= new ConcurrentDictionary<ulong, AntiAltStats>();
private readonly ConcurrentDictionary<ulong, AntiAltStats> _antiAltGuilds = new();
public event Func<PunishmentAction, ProtectionType, IGuildUser[], Task> 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 () =>
{

View File

@@ -5,7 +5,7 @@ namespace NadekoBot.Modules.Administration.Services;
public class PruneService : INService
{
//channelids where prunes are currently occuring
private ConcurrentHashSet<ulong> _pruningGuilds = new ConcurrentHashSet<ulong>();
private readonly ConcurrentHashSet<ulong> _pruningGuilds = new();
private readonly TimeSpan twoWeeks = TimeSpan.FromDays(14);
private readonly ILogCommandService _logService;

View File

@@ -17,8 +17,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
private ImmutableDictionary<ulong, IDMChannel> ownerChannels =
new Dictionary<ulong, IDMChannel>().ToImmutableDictionary();
private ConcurrentDictionary<ulong?, ConcurrentDictionary<int, Timer>> _autoCommands =
new ConcurrentDictionary<ulong?, ConcurrentDictionary<int, Timer>>();
private ConcurrentDictionary<ulong?, ConcurrentDictionary<int, Timer>> _autoCommands = new();
private readonly IImageCache _imgs;
private readonly IHttpClientFactory _httpFactory;

View File

@@ -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())

View File

@@ -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;

View File

@@ -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(),

View File

@@ -13,8 +13,8 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
_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<CustomReactionsService>
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<CustomReactionsService>
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<CustomReactionsService>
[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<CustomReactionsService>
return;
}
var cr = await _service.DeleteAsync(ctx.Guild?.Id, (int)id);
var cr = await _service.DeleteAsync(ctx.Guild?.Id, id);
if (cr != null)
{

View File

@@ -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<CustomReaction> _gcrAddedKey = new TypedKey<CustomReaction>("gcr.added");
private readonly TypedKey<int> _gcrDeletedkey = new TypedKey<int>("gcr.deleted");
private readonly TypedKey<CustomReaction> _gcrEditedKey = new TypedKey<CustomReaction>("gcr.edited");
private readonly TypedKey<bool> _crsReloadedKey = new TypedKey<bool>("crs.reloaded");
private readonly TypedKey<CustomReaction> _gcrAddedKey = new("gcr.added");
private readonly TypedKey<int> _gcrDeletedkey = new("gcr.deleted");
private readonly TypedKey<CustomReaction> _gcrEditedKey = new("gcr.edited");
private readonly TypedKey<bool> _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();

View File

@@ -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
{

View File

@@ -20,10 +20,10 @@ public sealed class AnimalRace : IDisposable
public event Func<AnimalRace, Task> OnEnded = delegate { return Task.CompletedTask; };
public IReadOnlyCollection<AnimalRacingUser> Users => _users.ToList();
public List<AnimalRacingUser> FinishedUsers { get; } = new List<AnimalRacingUser>();
public List<AnimalRacingUser> FinishedUsers { get; } = new();
private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1);
private readonly HashSet<AnimalRacingUser> _users = new HashSet<AnimalRacingUser>();
private readonly SemaphoreSlim _locker = new(1, 1);
private readonly HashSet<AnimalRacingUser> _users = new();
private readonly ICurrencyService _currency;
private readonly RaceOptions _options;
private readonly Queue<RaceAnimal> _animalsQueue;

View File

@@ -13,7 +13,7 @@ public class Blackjack
public Dealer Dealer { get; set; }
public List<User> Players { get; set; } = new List<User>();
public List<User> 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<Blackjack, Task> StateUpdated;
public event Func<Blackjack, Task> 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

View File

@@ -2,7 +2,7 @@
public abstract class Player
{
public List<Deck.Card> Cards { get; } = new List<Deck.Card>();
public List<Deck.Card> Cards { get; } = new();
public int GetHandValue()
{

View File

@@ -25,7 +25,7 @@ public class CurrencyRaffleGame
}
}
private readonly HashSet<User> _users = new HashSet<User>();
private readonly HashSet<User> _users = new();
public IEnumerable<User> Users => _users;
public Type GameType { get; }

View File

@@ -20,7 +20,7 @@ public class QuadDeck : Deck
public class Deck
{
private static readonly Dictionary<int, string> cardNames = new Dictionary<int, string>() {
private static readonly Dictionary<int, string> _cardNames = new() {
{ 1, "Ace" },
{ 2, "Two" },
{ 3, "Three" },
@@ -35,7 +35,7 @@ public class Deck
{ 12, "Queen" },
{ 13, "King" }
};
private static Dictionary<string, Func<List<Card>, bool>> handValues;
private static Dictionary<string, Func<List<Card>, 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<string, CardSuit> _suitCharToSuit = new Dictionary<string, CardSuit>
private static readonly IReadOnlyDictionary<string, CardSuit> _suitCharToSuit = new Dictionary<string, CardSuit>
{
{"♦", CardSuit.Diamonds },
{"d", CardSuit.Diamonds },
@@ -144,7 +143,7 @@ public class Deck
{"♥", CardSuit.Hearts },
{"h", CardSuit.Hearts },
};
private static IReadOnlyDictionary<char, int> _numberCharToNumber = new Dictionary<char, int>()
private static readonly IReadOnlyDictionary<char, int> _numberCharToNumber = new Dictionary<char, int>()
{
{'a', 1 },
{'2', 2 },
@@ -200,7 +199,7 @@ public class Deck
}
}
}
private Random r = new NadekoRandom();
private readonly Random _r = new NadekoRandom();
/// <summary>
/// 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.
/// </summary>
@@ -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<Card> ?? 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<Card> cards) => cards.GroupBy(card => card.Number)
bool HasPair(List<Card> cards) => cards.GroupBy(card => card.Number)
.Count(group => group.Count() == 2) == 1;
bool isPair(List<Card> cards) => cards.GroupBy(card => card.Number)
bool IsPair(List<Card> cards) => cards.GroupBy(card => card.Number)
.Count(group => group.Count() == 3) == 0
&& hasPair(cards);
&& HasPair(cards);
bool isTwoPair(List<Card> cards) => cards.GroupBy(card => card.Number)
bool IsTwoPair(List<Card> cards) => cards.GroupBy(card => card.Number)
.Count(group => group.Count() == 2) == 2;
bool isStraight(List<Card> cards)
bool IsStraight(List<Card> 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<Card> cards) => cards.GroupBy(card => card.Number)
bool HasThreeOfKind(List<Card> cards) => cards.GroupBy(card => card.Number)
.Any(group => group.Count() == 3);
bool isThreeOfKind(List<Card> cards) => hasThreeOfKind(cards) && !hasPair(cards);
bool IsThreeOfKind(List<Card> cards) => HasThreeOfKind(cards) && !HasPair(cards);
bool isFlush(List<Card> cards) => cards.GroupBy(card => card.Suit).Count() == 1;
bool IsFlush(List<Card> cards) => cards.GroupBy(card => card.Suit).Count() == 1;
bool isFourOfKind(List<Card> cards) => cards.GroupBy(card => card.Number)
bool IsFourOfKind(List<Card> cards) => cards.GroupBy(card => card.Number)
.Any(group => group.Count() == 4);
bool isFullHouse(List<Card> cards) => hasPair(cards) && hasThreeOfKind(cards);
bool IsFullHouse(List<Card> cards) => HasPair(cards) && HasThreeOfKind(cards);
bool hasStraightFlush(List<Card> cards) => isFlush(cards) && isStraight(cards);
bool HasStraightFlush(List<Card> cards) => IsFlush(cards) && IsStraight(cards);
bool isRoyalFlush(List<Card> cards) => cards.Min(card => card.Number) == 1 &&
bool IsRoyalFlush(List<Card> cards) => cards.Min(card => card.Number) == 1 &&
cards.Max(card => card.Number) == 13
&& hasStraightFlush(cards);
&& HasStraightFlush(cards);
bool isStraightFlush(List<Card> cards) => hasStraightFlush(cards) && !isRoyalFlush(cards);
bool IsStraightFlush(List<Card> 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<Card> 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;
}

View File

@@ -18,8 +18,8 @@ public class GameStatusEvent : ICurrencyEvent
private readonly Func<CurrencyEvent.Type, EventOptions, long, IEmbedBuilder> _embedFunc;
private readonly bool _isPotLimited;
private readonly ITextChannel _channel;
private readonly ConcurrentHashSet<ulong> _awardedUsers = new ConcurrentHashSet<ulong>();
private readonly ConcurrentQueue<ulong> _toAward = new ConcurrentQueue<ulong>();
private readonly ConcurrentHashSet<ulong> _awardedUsers = new();
private readonly ConcurrentQueue<ulong> _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)

View File

@@ -19,8 +19,8 @@ public class ReactionEvent : ICurrencyEvent
private readonly Func<CurrencyEvent.Type, EventOptions, long, IEmbedBuilder> _embedFunc;
private readonly bool _isPotLimited;
private readonly ITextChannel _channel;
private readonly ConcurrentHashSet<ulong> _awardedUsers = new ConcurrentHashSet<ulong>();
private readonly ConcurrentQueue<ulong> _toAward = new ConcurrentQueue<ulong>();
private readonly ConcurrentHashSet<ulong> _awardedUsers = new();
private readonly ConcurrentQueue<ulong> _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)

View File

@@ -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<WaifuItemModel> Items { get; set; } = new List<WaifuItemModel>();
public List<WaifuItemModel> Items { get; set; } = new();
public WaifuConfig()
{

View File

@@ -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<RollDuelGame, Task> OnGameTick;
public event Func<RollDuelGame, Reason, Task> 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 { }

View File

@@ -4,6 +4,6 @@ public class SlotResponse
{
public float Multiplier { get; set; }
public long Won { get; set; }
public List<int> Rolls { get; set; } = new List<int>();
public List<int> Rolls { get; set; } = new();
public GamblingError Error { get; set; }
}

View File

@@ -52,7 +52,7 @@ public sealed class Connect4Game : IDisposable
public event Func<Connect4Game, Task> OnGameFailedToStart;
public event Func<Connect4Game, Result, Task> 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;

View File

@@ -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

View File

@@ -10,8 +10,8 @@ public partial class Gambling
[Group]
public class DiceRollCommands : NadekoSubmodule
{
private static readonly Regex dndRegex = new Regex(@"^(?<n1>\d+)d(?<n2>\d+)(?:\+(?<add>\d+))?(?:\-(?<sub>\d+))?$", RegexOptions.Compiled);
private static readonly Regex fudgeRegex = new Regex(@"^(?<n1>\d+)d(?:F|f)$", RegexOptions.Compiled);
private static readonly Regex dndRegex = new(@"^(?<n1>\d+)d(?<n2>\d+)(?:\+(?<add>\d+))?(?:\-(?<sub>\d+))?$", RegexOptions.Compiled);
private static readonly Regex fudgeRegex = new(@"^(?<n1>\d+)d(?:F|f)$", RegexOptions.Compiled);
private static readonly char[] _fateRolls = { '-', ' ', '+' };
private readonly IImageCache _images;

View File

@@ -10,7 +10,7 @@ public partial class Gambling
[Group]
public class DrawCommands : NadekoSubmodule
{
private static readonly ConcurrentDictionary<IGuild, Deck> _allDecks = new ConcurrentDictionary<IGuild, Deck>();
private static readonly ConcurrentDictionary<IGuild, Deck> _allDecks = new();
private readonly IImageCache _images;
public DrawCommands(IDataCache data)

View File

@@ -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)
{

View File

@@ -574,7 +574,7 @@ public partial class Gambling : GamblingModule<GamblingService>
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<GamblingService>
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,

View File

@@ -4,5 +4,5 @@ namespace NadekoBot.Modules.Gambling.Services;
public class AnimalRaceService : INService
{
public ConcurrentDictionary<ulong, AnimalRace> AnimalRaces { get; } = new ConcurrentDictionary<ulong, AnimalRace>();
public ConcurrentDictionary<ulong, AnimalRace> AnimalRaces { get; } = new();
}

View File

@@ -4,5 +4,5 @@ namespace NadekoBot.Modules.Gambling.Services;
public class BlackJackService : INService
{
public ConcurrentDictionary<ulong, Blackjack> Games { get; } = new ConcurrentDictionary<ulong, Blackjack>();
public ConcurrentDictionary<ulong, Blackjack> Games { get; } = new();
}

View File

@@ -10,8 +10,7 @@ public class CurrencyEventsService : INService
private readonly ICurrencyService _cs;
private readonly GamblingConfigService _configService;
private readonly ConcurrentDictionary<ulong, ICurrencyEvent> _events =
new ConcurrentDictionary<ulong, ICurrencyEvent>();
private readonly ConcurrentDictionary<ulong, ICurrencyEvent> _events = new();
public CurrencyEventsService(

View File

@@ -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<ulong, CurrencyRaffleGame> Games { get; } = new Dictionary<ulong, CurrencyRaffleGame>();
public Dictionary<ulong, CurrencyRaffleGame> Games { get; } = new();
public CurrencyRaffleService(DbService db, ICurrencyService cs)
{

View File

@@ -7,7 +7,7 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
{
public override string Name { get; } = "gambling";
private const string FilePath = "data/gambling.yml";
private static TypedKey<GamblingConfig> changeKey = new TypedKey<GamblingConfig>("config.gambling.updated");
private static readonly TypedKey<GamblingConfig> changeKey = new("config.gambling.updated");
public GamblingConfigService(IConfigSeria serializer, IPubSub pubSub)

View File

@@ -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<ulong, Connect4Game> Connect4Games { get; } = new ConcurrentDictionary<ulong, Connect4Game>();
public ConcurrentDictionary<(ulong, ulong), RollDuelGame> Duels { get; } = new();
public ConcurrentDictionary<ulong, Connect4Game> Connect4Games { get; } = new();
private readonly Timer _decayTimer;

View File

@@ -24,10 +24,10 @@ public class PlantPickService : INService
private readonly DiscordSocketClient _client;
private readonly GamblingConfigService _gss;
public readonly ConcurrentHashSet<ulong> _generationChannels = new ConcurrentHashSet<ulong>();
public readonly ConcurrentHashSet<ulong> _generationChannels = new();
//channelId/last generation
public ConcurrentDictionary<ulong, DateTime> LastGenerations { get; } = new ConcurrentDictionary<ulong, DateTime>();
private readonly SemaphoreSlim pickLock = new SemaphoreSlim(1, 1);
public ConcurrentDictionary<ulong, DateTime> 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;

View File

@@ -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()

View File

@@ -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);
}

View File

@@ -20,7 +20,7 @@ public partial class Gambling
private static long _totalBet;
private static long _totalPaidOut;
private static readonly HashSet<ulong> _runningUsers = new HashSet<ulong>();
private static readonly HashSet<ulong> _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<Func<int[], int>> _winningCombos = new List<Func<int[], int>>()
static readonly List<Func<int[], int>> _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));
}
}

View File

@@ -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);

View File

@@ -41,8 +41,8 @@ public sealed class AcrophobiaGame : IDisposable
public Phase CurrentPhase { get; private set; } = Phase.Submission;
public ImmutableArray<char> StartingLetters { get; private set; }
private readonly Dictionary<AcrophobiaUser, int> submissions = new Dictionary<AcrophobiaUser, int>();
private readonly SemaphoreSlim locker = new SemaphoreSlim(1, 1);
private readonly Dictionary<AcrophobiaUser, int> 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<string, Task> OnUserVoted = delegate { return Task.CompletedTask; };
public event Func<AcrophobiaGame, ImmutableArray<KeyValuePair<AcrophobiaUser, int>>, Task> OnEnded = delegate { return Task.CompletedTask; };
private readonly HashSet<ulong> _usersWhoVoted = new HashSet<ulong>();
private readonly HashSet<ulong> _usersWhoVoted = new();
public AcrophobiaGame(Options options)
{

View File

@@ -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;

View File

@@ -57,7 +57,7 @@ public class CleverbotIOSession : IChatterBotSession
this._user = user;
this._httpFactory = factory;
_nick = new((Func<Task<string>>)GetNick);
_nick = new(GetNick);
}
private async Task<string> GetNick()

View File

@@ -10,20 +10,20 @@ public sealed partial class GamesConfig : ICloneable<GamesConfig>
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<string> EightBallResponses { get; set; } = new List<string>()
public List<string> EightBallResponses { get; set; } = new()
{
"Most definitely yes.",
"For sure.",
@@ -51,16 +51,16 @@ public sealed partial class GamesConfig : ICloneable<GamesConfig>
};
[Comment("List of animals which will be used for the animal race game (.race)")]
public List<RaceAnimal> RaceAnimals { get; set; } = new List<RaceAnimal>()
public List<RaceAnimal> 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" }
};
}

View File

@@ -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))
{

View File

@@ -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);

View File

@@ -21,10 +21,10 @@ public sealed class NunchiGame : IDisposable
public event Func<NunchiGame, (ulong Id, string Name)?, Task> OnRoundEnded; // tuple of the user who failed
public event Func<NunchiGame, string, Task> 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;

View File

@@ -9,7 +9,7 @@ public class PollRunner
public event Func<IUserMessage, IGuildUser, Task> OnVoted;
private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim _locker = new(1, 1);
public PollRunner(DbService db, Poll poll)
{

View File

@@ -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("┃");
}

View File

@@ -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<TriviaQuestion> OldQuestions { get; } = new HashSet<TriviaQuestion>();
public HashSet<TriviaQuestion> OldQuestions { get; } = new();
public ConcurrentDictionary<IGuildUser, int> Users { get; } = new ConcurrentDictionary<IGuildUser, int>();
public ConcurrentDictionary<IGuildUser, int> Users { get; } = new();
public bool GameActive { get; private set; }
public bool ShouldStopGame { get; private set; }

View File

@@ -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<Tuple<int, int>> strictness = new HashSet<Tuple<int, int>> {
new Tuple<int, int>(9, 0),
new Tuple<int, int>(14, 1),
new Tuple<int, int>(19, 2),
new Tuple<int, int>(22, 3),
private static readonly HashSet<Tuple<int, int>> strictness = new()
{
new(9, 0),
new(14, 1),
new(19, 2),
new(22, 3),
};
public const int maxStringLength = 22;

View File

@@ -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<int, string> Map => _cache.LocalData.PokemonMap;

View File

@@ -11,7 +11,7 @@ public partial class Games : NadekoModule<GamesService>
{
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<GamesService>
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<GamesService>
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)

View File

@@ -96,7 +96,7 @@ public class ChatterBotService : IEarlyBehavior
public async Task<bool> 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);

View File

@@ -7,7 +7,7 @@ public sealed class GamesConfigService : ConfigServiceBase<GamesConfig>
{
public override string Name { get; } = "games";
private const string FilePath = "data/games.yml";
private static TypedKey<GamesConfig> changeKey = new TypedKey<GamesConfig>("config.games.updated");
private static readonly TypedKey<GamesConfig> changeKey = new("config.games.updated");
public GamesConfigService(IConfigSeria serializer, IPubSub pubSub)
: base(FilePath, serializer, pubSub, changeKey)

Some files were not shown because too many files have changed in this diff Show More