- More code cleanup and codestyle updates

- Fixed some possible nullref exceptions
- Methods signatures now have up to 3 parameters before breakaing down each parameter in a separate line
- Method invocations have the same rule, except the first parameter will be in the same line as the invocation to prevent some ugliness when passing lambas as arguments
- Applied many more codestyles
- Extensions folder fully reformatted
This commit is contained in:
Kwoth
2021-12-26 17:28:39 +01:00
parent b85ba177cd
commit d5fd6aae8e
217 changed files with 1017 additions and 1494 deletions

View File

@@ -1,4 +1,4 @@

[*] [*]
charset = utf-8-bom charset = utf-8-bom
end_of_line = crlf end_of_line = crlf
@@ -109,3 +109,14 @@ resharper_unused_method_return_value_local_highlighting = suggestion
resharper_web_config_module_not_resolved_highlighting = warning resharper_web_config_module_not_resolved_highlighting = warning
resharper_web_config_type_not_resolved_highlighting = warning resharper_web_config_type_not_resolved_highlighting = warning
resharper_web_config_wrong_module_highlighting = warning resharper_web_config_wrong_module_highlighting = warning
resharper_convert_to_using_declaration_highlighting = warning
# Expression-bodied members
csharp_style_expression_bodied_accessors = true:warning
csharp_style_expression_bodied_constructors = true:warning
csharp_style_expression_bodied_indexers = true:warning
csharp_style_expression_bodied_lambdas = true:warning
csharp_style_expression_bodied_local_functions = true:warning
csharp_style_expression_bodied_methods = true:warning
csharp_style_expression_bodied_operators = when_on_single_line:suggestion
csharp_style_expression_bodied_properties = true:warning

View File

@@ -1,5 +1,5 @@
# Remove the line below if you want to inherit .editorconfig settings from higher directories
root = true root = true
# Remove the line below if you want to inherit .editorconfig settings from higher directories
# C# files # C# files
[*.cs] [*.cs]
@@ -20,7 +20,6 @@ insert_final_newline = false
# Organize usings # Organize usings
dotnet_separate_import_directive_groups = false dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = false dotnet_sort_system_directives_first = false
file_header_template = unset
# this. and Me. preferences # this. and Me. preferences
dotnet_style_qualification_for_event = false dotnet_style_qualification_for_event = false
@@ -51,8 +50,8 @@ dotnet_style_object_initializer = true
dotnet_style_operator_placement_when_wrapping = beginning_of_line dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_auto_properties = true:warning dotnet_style_prefer_auto_properties = true:warning
dotnet_style_prefer_compound_assignment = true dotnet_style_prefer_compound_assignment = true
dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion dotnet_style_prefer_conditional_expression_over_assignment = false:suggestion
dotnet_style_prefer_conditional_expression_over_return = true:suggestion dotnet_style_prefer_conditional_expression_over_return = false:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true dotnet_style_prefer_inferred_anonymous_type_member_names = true
dotnet_style_prefer_inferred_tuple_names = true dotnet_style_prefer_inferred_tuple_names = true
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:error dotnet_style_prefer_is_null_check_over_reference_equality_method = true:error
@@ -65,13 +64,6 @@ dotnet_style_readonly_field = true:suggestion
# Parameter preferences # Parameter preferences
dotnet_code_quality_unused_parameters = all:warning 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 #### #### C# Coding Conventions ####
# var preferences # var preferences
@@ -85,8 +77,8 @@ csharp_style_expression_bodied_constructors = when_on_single_line:suggestion
csharp_style_expression_bodied_indexers = true:suggestion csharp_style_expression_bodied_indexers = true:suggestion
csharp_style_expression_bodied_lambdas = true:suggestion csharp_style_expression_bodied_lambdas = true:suggestion
csharp_style_expression_bodied_local_functions = true:suggestion csharp_style_expression_bodied_local_functions = true:suggestion
csharp_style_expression_bodied_methods = when_on_single_line:suggestion csharp_style_expression_bodied_methods = when_on_single_line:warning
csharp_style_expression_bodied_operators = when_on_single_line:suggestion csharp_style_expression_bodied_operators = when_on_single_line:warning
csharp_style_expression_bodied_properties = true:suggestion csharp_style_expression_bodied_properties = true:suggestion
# Pattern matching preferences # Pattern matching preferences
@@ -123,7 +115,7 @@ csharp_style_unused_value_expression_statement_preference = discard_variable
csharp_using_directive_placement = outside_namespace:error csharp_using_directive_placement = outside_namespace:error
# Enforce file-scoped namespaces # Enforce file-scoped namespaces
csharp_style_namespace_declarations=file_scoped:error csharp_style_namespace_declarations = file_scoped:error
# New line preferences # New line preferences
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true
@@ -236,6 +228,7 @@ dotnet_naming_rule.public_anything_should_be_pascal_case.style = pascal_case
# Symbol specifications # Symbol specifications
dotnet_naming_symbols.const_fields.required_modifiers = const dotnet_naming_symbols.const_fields.required_modifiers = const
dotnet_naming_symbols.const_fields.applicable_kinds = field
dotnet_naming_symbols.class.applicable_kinds = class dotnet_naming_symbols.class.applicable_kinds = class
dotnet_naming_symbols.class.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected dotnet_naming_symbols.class.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
@@ -316,13 +309,24 @@ dotnet_naming_style.camel_case.word_separator =
dotnet_naming_style.camel_case.capitalization = camel_case dotnet_naming_style.camel_case.capitalization = camel_case
# CA1822: Mark members as static # CA1822: Mark members as static
dotnet_diagnostic.CA1822.severity = suggestion dotnet_diagnostic.ca1822.severity = suggestion
# IDE0004: Cast is redundant # IDE0004: Cast is redundant
dotnet_diagnostic.IDE0004.severity = error dotnet_diagnostic.ide0004.severity = error
# IDE0058: Expression value is never used # IDE0058: Expression value is never used
dotnet_diagnostic.IDE0058.severity = none dotnet_diagnostic.ide0058.severity = none
# IDE0011: Add braces to 'if'/'else' statement # IDE0011: Add braces to 'if'/'else' statement
dotnet_diagnostic.IDE0011.severity = none dotnet_diagnostic.ide0011.severity = none
resharper_wrap_after_invocation_lpar = false
resharper_wrap_before_invocation_rpar = false
# ReSharper properties
resharper_csharp_wrap_after_declaration_lpar = true
resharper_csharp_wrap_before_invocation_rpar = true
resharper_csharp_wrap_parameters_style = chop_if_long
resharper_force_chop_compound_if_expression = true
resharper_keep_existing_linebreaks = false
resharper_max_formal_parameters_on_line = 3

View File

@@ -70,9 +70,7 @@ public sealed class Bot
} }
public List<ulong> GetCurrentGuildIds() public List<ulong> GetCurrentGuildIds()
{ => Client.Guilds.Select(x => x.Id).ToList();
return Client.Guilds.Select(x => x.Id).ToList();
}
private void AddServices() private void AddServices()
{ {

View File

@@ -12,5 +12,6 @@ public class AsyncLazy<T> : Lazy<Task<T>>
base(() => Task.Run(taskFactory)) base(() => Task.Run(taskFactory))
{ } { }
public TaskAwaiter<T> GetAwaiter() { return Value.GetAwaiter(); } public TaskAwaiter<T> GetAwaiter()
=> Value.GetAwaiter();
} }

View File

@@ -7,9 +7,7 @@ public sealed class NadekoCommandAttribute : CommandAttribute
{ {
public NadekoCommandAttribute([CallerMemberName] string memberName="") public NadekoCommandAttribute([CallerMemberName] string memberName="")
: base(CommandNameLoadHelper.GetCommandNameFor(memberName)) : base(CommandNameLoadHelper.GetCommandNameFor(memberName))
{ => this.MethodName = memberName.ToLowerInvariant();
this.MethodName = memberName.ToLowerInvariant();
}
public string MethodName { get; } public string MethodName { get; }
} }

View File

@@ -6,7 +6,5 @@ public sealed class NadekoOptionsAttribute : Attribute
public Type OptionType { get; set; } public Type OptionType { get; set; }
public NadekoOptionsAttribute(Type t) public NadekoOptionsAttribute(Type t)
{ => this.OptionType = t;
this.OptionType = t;
}
} }

View File

@@ -1,10 +1,9 @@
// License MIT // License MIT
// Source: https://github.com/i3arnon/ConcurrentHashSet // Source: https://github.com/i3arnon/ConcurrentHashSet
using System.Collections;
using System.Diagnostics; using System.Diagnostics;
namespace NadekoBot.Common.Collections; namespace System.Collections.Generic;
/// <summary> /// <summary>
/// Represents a thread-safe hash-based unique collection. /// Represents a thread-safe hash-based unique collection.
@@ -26,7 +25,8 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
private int _budget; private int _budget;
private volatile Tables _tables; private volatile Tables _tables;
private static int DefaultConcurrencyLevel => PlatformHelper.ProcessorCount; private static int DefaultConcurrencyLevel
=> PlatformHelper.ProcessorCount;
/// <summary> /// <summary>
/// Gets the number of items contained in the <see /// Gets the number of items contained in the <see
@@ -99,7 +99,10 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
/// uses the default comparer for the item type. /// uses the default comparer for the item type.
/// </summary> /// </summary>
public ConcurrentHashSet() public ConcurrentHashSet()
: this(DefaultConcurrencyLevel, DefaultCapacity, true, EqualityComparer<T>.Default) : this(DefaultConcurrencyLevel,
DefaultCapacity,
true,
EqualityComparer<T>.Default)
{ {
} }
@@ -119,7 +122,10 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
/// <exception cref="T:System.ArgumentOutOfRangeException"> <paramref name="capacity"/> is less than /// <exception cref="T:System.ArgumentOutOfRangeException"> <paramref name="capacity"/> is less than
/// 0.</exception> /// 0.</exception>
public ConcurrentHashSet(int concurrencyLevel, int capacity) public ConcurrentHashSet(int concurrencyLevel, int capacity)
: this(concurrencyLevel, capacity, false, EqualityComparer<T>.Default) : this(concurrencyLevel,
capacity,
false,
EqualityComparer<T>.Default)
{ {
} }
@@ -148,7 +154,10 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
/// implementation to use when comparing items.</param> /// implementation to use when comparing items.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference.</exception> /// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference.</exception>
public ConcurrentHashSet(IEqualityComparer<T> comparer) public ConcurrentHashSet(IEqualityComparer<T> comparer)
: this(DefaultConcurrencyLevel, DefaultCapacity, true, comparer) : this(DefaultConcurrencyLevel,
DefaultCapacity,
true,
comparer)
{ {
} }
@@ -199,7 +208,10 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
/// <paramref name="concurrencyLevel"/> is less than 1. /// <paramref name="concurrencyLevel"/> is less than 1.
/// </exception> /// </exception>
public ConcurrentHashSet(int concurrencyLevel, IEnumerable<T> collection, IEqualityComparer<T> comparer) public ConcurrentHashSet(int concurrencyLevel, IEnumerable<T> collection, IEqualityComparer<T> comparer)
: this(concurrencyLevel, DefaultCapacity, false, comparer) : this(concurrencyLevel,
DefaultCapacity,
false,
comparer)
{ {
if (collection is null) throw new ArgumentNullException(nameof(collection)); if (collection is null) throw new ArgumentNullException(nameof(collection));
if (comparer is null) throw new ArgumentNullException(nameof(comparer)); if (comparer is null) throw new ArgumentNullException(nameof(comparer));
@@ -225,7 +237,10 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
/// </exception> /// </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference.</exception> /// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference.</exception>
public ConcurrentHashSet(int concurrencyLevel, int capacity, IEqualityComparer<T> comparer) public ConcurrentHashSet(int concurrencyLevel, int capacity, IEqualityComparer<T> comparer)
: this(concurrencyLevel, capacity, false, comparer) : this(concurrencyLevel,
capacity,
false,
comparer)
{ {
} }
@@ -264,8 +279,8 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
/// successfully; false if it already exists.</returns> /// successfully; false if it already exists.</returns>
/// <exception cref="T:System.OverflowException">The <see cref="ConcurrentHashSet{T}"/> /// <exception cref="T:System.OverflowException">The <see cref="ConcurrentHashSet{T}"/>
/// contains too many items.</exception> /// contains too many items.</exception>
public bool Add(T item) => public bool Add(T item)
AddInternal(item, _comparer.GetHashCode(item), true); => AddInternal(item, _comparer.GetHashCode(item), true);
/// <summary> /// <summary>
/// Removes all items from the <see cref="ConcurrentHashSet{T}"/>. /// Removes all items from the <see cref="ConcurrentHashSet{T}"/>.
@@ -308,10 +323,12 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
while (current != null) while (current != null)
{ {
if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item)) if (hashcode == current.Hashcode &&
_comparer.Equals(current.Item, item))
{ {
return true; return true;
} }
current = current.Next; current = current.Next;
} }
@@ -330,7 +347,11 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
{ {
var tables = _tables; var tables = _tables;
GetBucketAndLockNo(hashcode, out var bucketNo, out var lockNo, tables.Buckets.Length, tables.Locks.Length); GetBucketAndLockNo(hashcode,
out var bucketNo,
out var lockNo,
tables.Buckets.Length,
tables.Locks.Length);
lock (tables.Locks[lockNo]) lock (tables.Locks[lockNo])
{ {
@@ -346,7 +367,8 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
{ {
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)) if (hashcode == current.Hashcode &&
_comparer.Equals(current.Item, item))
{ {
if (previous is null) if (previous is null)
{ {
@@ -360,6 +382,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
tables.CountPerLock[lockNo]--; tables.CountPerLock[lockNo]--;
return true; return true;
} }
previous = current; previous = current;
} }
} }
@@ -368,7 +391,8 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
} }
} }
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator()
=> GetEnumerator();
/// <summary>Returns an enumerator that iterates through the <see /// <summary>Returns an enumerator that iterates through the <see
/// cref="ConcurrentHashSet{T}"/>.</summary> /// cref="ConcurrentHashSet{T}"/>.</summary>
@@ -396,9 +420,11 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
} }
} }
void ICollection<T>.Add(T item) => Add(item); void ICollection<T>.Add(T item)
=> Add(item);
bool ICollection<T>.IsReadOnly => false; bool ICollection<T>.IsReadOnly
=> false;
void ICollection<T>.CopyTo(T[] array, int arrayIndex) void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{ {
@@ -417,9 +443,11 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
count += _tables.CountPerLock[i]; count += _tables.CountPerLock[i];
} }
if (array.Length - count < arrayIndex || count < 0) //"count" itself or "count + arrayIndex" can overflow if (array.Length - count < arrayIndex ||
count < 0) //"count" itself or "count + arrayIndex" can overflow
{ {
throw new ArgumentException("The index is equal to or greater than the length of the array, or the number of elements in the set is greater than the available space from index to the end of the destination array."); throw new ArgumentException(
"The index is equal to or greater than the length of the array, or the number of elements in the set is greater than the available space from index to the end of the destination array.");
} }
CopyToItems(array, arrayIndex); CopyToItems(array, arrayIndex);
@@ -430,7 +458,8 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
} }
} }
bool ICollection<T>.Remove(T item) => TryRemove(item); bool ICollection<T>.Remove(T item)
=> TryRemove(item);
private void InitializeFromCollection(IEnumerable<T> collection) private void InitializeFromCollection(IEnumerable<T> collection)
{ {
@@ -450,7 +479,11 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
while (true) while (true)
{ {
var tables = _tables; var tables = _tables;
GetBucketAndLockNo(hashcode, out var bucketNo, out var lockNo, tables.Buckets.Length, tables.Locks.Length); GetBucketAndLockNo(hashcode,
out var bucketNo,
out var lockNo,
tables.Buckets.Length,
tables.Locks.Length);
var resizeDesired = false; var resizeDesired = false;
var lockTaken = false; var lockTaken = false;
@@ -471,10 +504,12 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
for (var current = tables.Buckets[bucketNo]; current != null; current = current.Next) 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)) if (hashcode == current.Hashcode &&
_comparer.Equals(current.Item, item))
{ {
return false; return false;
} }
previous = current; previous = current;
} }
@@ -525,7 +560,8 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
return bucketNo; return bucketNo;
} }
private static void GetBucketAndLockNo(int hashcode, out int bucketNo, out int lockNo, int bucketCount, int lockCount) private static void GetBucketAndLockNo(int hashcode, out int bucketNo, out int lockNo, int bucketCount,
int lockCount)
{ {
bucketNo = (hashcode & 0x7fffffff) % bucketCount; bucketNo = (hashcode & 0x7fffffff) % bucketCount;
lockNo = bucketNo % lockCount; lockNo = bucketNo % lockCount;
@@ -569,6 +605,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
{ {
_budget = int.MaxValue; _budget = int.MaxValue;
} }
return; return;
} }
@@ -624,7 +661,11 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
if (_growLockArray && tables.Locks.Length < MaxLockNumber) if (_growLockArray && tables.Locks.Length < MaxLockNumber)
{ {
newLocks = new object[tables.Locks.Length * 2]; newLocks = new object[tables.Locks.Length * 2];
Array.Copy(tables.Locks, 0, newLocks, 0, tables.Locks.Length); Array.Copy(tables.Locks,
0,
newLocks,
0,
tables.Locks.Length);
for (var i = tables.Locks.Length; i < newLocks.Length; i++) for (var i = tables.Locks.Length; i < newLocks.Length; i++)
{ {
newLocks[i] = new(); newLocks[i] = new();
@@ -641,7 +682,11 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
while (current != null) while (current != null)
{ {
var next = current.Next; var next = current.Next;
GetBucketAndLockNo(current.Hashcode, out var newBucketNo, out var newLockNo, newBuckets.Length, newLocks.Length); GetBucketAndLockNo(current.Hashcode,
out var newBucketNo,
out var newLockNo,
newBuckets.Length,
newLocks.Length);
newBuckets[newBucketNo] = new(current.Item, current.Hashcode, newBuckets[newBucketNo]); newBuckets[newBucketNo] = new(current.Item, current.Hashcode, newBuckets[newBucketNo]);
@@ -676,6 +721,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
if (this.TryRemove(elem)) if (this.TryRemove(elem))
removed++; removed++;
} }
return removed; return removed;
} }

View File

@@ -13,10 +13,8 @@ public class IndexedCollection<T> : IList<T> where T : class, IIndexed
public int IndexOf(T item) => item.Index; public int IndexOf(T item) => item.Index;
public IndexedCollection() public IndexedCollection()
{ => Source = new();
Source = new();
}
public IndexedCollection(IEnumerable<T> source) public IndexedCollection(IEnumerable<T> source)
{ {
lock (_locker) lock (_locker)
@@ -125,7 +123,7 @@ public class IndexedCollection<T> : IList<T> where T : class, IIndexed
public virtual T this[int index] public virtual T this[int index]
{ {
get { return Source[index]; } get => Source[index];
set set
{ {
lock (_locker) lock (_locker)

View File

@@ -8,25 +8,17 @@ namespace NadekoBot.Common.JsonConverters;
public class Rgba32Converter : JsonConverter<Rgba32> public class Rgba32Converter : JsonConverter<Rgba32>
{ {
public override Rgba32 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) public override Rgba32 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{ => Rgba32.ParseHex(reader.GetString());
return Rgba32.ParseHex(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, Rgba32 value, JsonSerializerOptions options) public override void Write(Utf8JsonWriter writer, Rgba32 value, JsonSerializerOptions options)
{ => writer.WriteStringValue(value.ToHex());
writer.WriteStringValue(value.ToHex());
}
} }
public class CultureInfoConverter : JsonConverter<CultureInfo> public class CultureInfoConverter : JsonConverter<CultureInfo>
{ {
public override CultureInfo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) public override CultureInfo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{ => new(reader.GetString());
return new(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, CultureInfo value, JsonSerializerOptions options) public override void Write(Utf8JsonWriter writer, CultureInfo value, JsonSerializerOptions options)
{ => writer.WriteStringValue(value.Name);
writer.WriteStringValue(value.Name);
}
} }

View File

@@ -90,7 +90,5 @@ public readonly struct kwum : IEquatable<kwum>
=> other == this; => other == this;
public override int GetHashCode() public override int GetHashCode()
{ => _value.GetHashCode();
return _value.GetHashCode();
}
} }

View File

@@ -7,10 +7,8 @@ public class LoginErrorHandler
{ {
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Handle(Exception ex) public static void Handle(Exception ex)
{ => Log.Fatal(ex, "A fatal error has occurred while attempting to connect to Discord");
Log.Fatal(ex, "A fatal error has occurred while attempting to connect to Discord");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Handle(HttpException ex) public static void Handle(HttpException ex)
{ {

View File

@@ -22,10 +22,8 @@ public abstract class NadekoModule : ModuleBase
} }
protected override void BeforeExecute(CommandInfo cmd) protected override void BeforeExecute(CommandInfo cmd)
{ => _cultureInfo = Localization.GetCultureInfo(ctx.Guild?.Id);
_cultureInfo = Localization.GetCultureInfo(ctx.Guild?.Id);
}
protected string GetText(in LocStr data) => protected string GetText(in LocStr data) =>
Strings.GetText(data, _cultureInfo); Strings.GetText(data, _cultureInfo);

View File

@@ -7,9 +7,7 @@ public class NadekoRandom : Random
private readonly RandomNumberGenerator _rng; private readonly RandomNumberGenerator _rng;
public NadekoRandom() : base() public NadekoRandom() : base()
{ => _rng = RandomNumberGenerator.Create();
_rng = RandomNumberGenerator.Create();
}
public override int Next() public override int Next()
{ {
@@ -52,9 +50,7 @@ public class NadekoRandom : Random
} }
public override void NextBytes(byte[] buffer) public override void NextBytes(byte[] buffer)
{ => _rng.GetBytes(buffer);
_rng.GetBytes(buffer);
}
protected override double Sample() protected override double Sample()
{ {

View File

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

View File

@@ -10,17 +10,13 @@ public class ReplacementBuilder
private readonly ConcurrentDictionary<Regex, Func<Match, string>> _regex = new(); private readonly ConcurrentDictionary<Regex, Func<Match, string>> _regex = new();
public ReplacementBuilder() public ReplacementBuilder()
{ => WithRngRegex();
WithRngRegex();
}
public ReplacementBuilder WithDefault(IUser usr, IMessageChannel ch, SocketGuild g, DiscordSocketClient client) public ReplacementBuilder WithDefault(IUser usr, IMessageChannel ch, SocketGuild g, DiscordSocketClient client)
{ => this.WithUser(usr)
return this.WithUser(usr)
.WithChannel(ch) .WithChannel(ch)
.WithServer(client, g) .WithServer(client, g)
.WithClient(client); .WithClient(client);
}
public ReplacementBuilder WithDefault(ICommandContext ctx) => public ReplacementBuilder WithDefault(ICommandContext ctx) =>
WithDefault(ctx.User, ctx.Channel, ctx.Guild as SocketGuild, (DiscordSocketClient)ctx.Client); WithDefault(ctx.User, ctx.Channel, ctx.Guild as SocketGuild, (DiscordSocketClient)ctx.Client);
@@ -139,9 +135,7 @@ public class ReplacementBuilder
} }
public Replacer Build() public Replacer Build()
{ => new(_reps.Select(x => (x.Key, x.Value)).ToArray(), _regex.Select(x => (x.Key, x.Value)).ToArray());
return new(_reps.Select(x => (x.Key, x.Value)).ToArray(), _regex.Select(x => (x.Key, x.Value)).ToArray());
}
public ReplacementBuilder WithProviders(IEnumerable<IPlaceholderProvider> phProviders) public ReplacementBuilder WithProviders(IEnumerable<IPlaceholderProvider> phProviders)
{ {

View File

@@ -12,49 +12,31 @@ public struct ShmartNumber : IEquatable<ShmartNumber>
} }
public static implicit operator ShmartNumber(long num) public static implicit operator ShmartNumber(long num)
{ => new(num);
return new(num);
}
public static implicit operator long(ShmartNumber num) public static implicit operator long(ShmartNumber num)
{ => num.Value;
return num.Value;
}
public static implicit operator ShmartNumber(int num) public static implicit operator ShmartNumber(int num)
{ => new(num);
return new(num);
}
public override string ToString() public override string ToString()
{ => Value.ToString();
return Value.ToString();
}
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is ShmartNumber sn
return obj is ShmartNumber sn
? Equals(sn) ? Equals(sn)
: false; : false;
}
public bool Equals(ShmartNumber other) public bool Equals(ShmartNumber other)
{ => other.Value == Value;
return other.Value == Value;
}
public override int GetHashCode() public override int GetHashCode()
{ => Value.GetHashCode() ^ Input.GetHashCode(StringComparison.InvariantCulture);
return Value.GetHashCode() ^ Input.GetHashCode(StringComparison.InvariantCulture);
}
public static bool operator ==(ShmartNumber left, ShmartNumber right) public static bool operator ==(ShmartNumber left, ShmartNumber right)
{ => left.Equals(right);
return left.Equals(right);
}
public static bool operator !=(ShmartNumber left, ShmartNumber right) public static bool operator !=(ShmartNumber left, ShmartNumber right)
{ => !(left == right);
return !(left == right);
}
} }

View File

@@ -5,9 +5,7 @@ public sealed record SmartPlainText : SmartText
public string Text { get; init; } public string Text { get; init; }
public SmartPlainText(string text) public SmartPlainText(string text)
{ => Text = text;
Text = text;
}
public static implicit operator SmartPlainText(string input) public static implicit operator SmartPlainText(string input)
=> new(input); => new(input);
@@ -16,7 +14,5 @@ public sealed record SmartPlainText : SmartText
=> input.Text; => input.Text;
public override string ToString() public override string ToString()
{ => Text;
return Text;
}
} }

View File

@@ -20,7 +20,7 @@ public sealed class CommandTypeReader : NadekoTypeReader<CommandInfo>
if (!input.StartsWith(prefix.ToUpperInvariant(), StringComparison.InvariantCulture)) if (!input.StartsWith(prefix.ToUpperInvariant(), StringComparison.InvariantCulture))
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No such command found.")); return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No such command found."));
input = input.Substring(prefix.Length); input = input[prefix.Length..];
var cmd = _cmds.Commands.FirstOrDefault(c => c.Aliases.Select(a => a.ToUpperInvariant()).Contains(input)); var cmd = _cmds.Commands.FirstOrDefault(c => c.Aliases.Select(a => a.ToUpperInvariant()).Contains(input));
if (cmd is null) if (cmd is null)

View File

@@ -7,10 +7,8 @@ public sealed class GuildDateTimeTypeReader : NadekoTypeReader<GuildDateTime>
private readonly GuildTimezoneService _gts; private readonly GuildTimezoneService _gts;
public GuildDateTimeTypeReader(GuildTimezoneService gts) public GuildDateTimeTypeReader(GuildTimezoneService gts)
{ => _gts = gts;
_gts = gts;
}
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input) public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input)
{ {
var gdt = Parse(context.Guild.Id, input); var gdt = Parse(context.Guild.Id, input);

View File

@@ -5,9 +5,7 @@ public sealed class GuildTypeReader : NadekoTypeReader<IGuild>
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
public GuildTypeReader(DiscordSocketClient client) public GuildTypeReader(DiscordSocketClient client)
{ => _client = client;
_client = client;
}
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input) public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input)
{ {

View File

@@ -14,7 +14,5 @@ public sealed class KwumTypeReader : NadekoTypeReader<kwum>
public sealed class SmartTextTypeReader : NadekoTypeReader<SmartText> public sealed class SmartTextTypeReader : NadekoTypeReader<SmartText>
{ {
public override Task<TypeReaderResult> ReadAsync(ICommandContext ctx, string input) public override Task<TypeReaderResult> ReadAsync(ICommandContext ctx, string input)
{ => Task.FromResult(TypeReaderResult.FromSuccess(SmartText.CreateFrom(input)));
return Task.FromResult(TypeReaderResult.FromSuccess(SmartText.CreateFrom(input)));
}
} }

View File

@@ -8,9 +8,7 @@ public class PermissionAction
public bool Value { get; } public bool Value { get; }
public PermissionAction(bool value) public PermissionAction(bool value)
{ => this.Value = value;
this.Value = value;
}
public override bool Equals(object obj) public override bool Equals(object obj)
{ {

View File

@@ -5,9 +5,7 @@ public sealed class ModuleTypeReader : NadekoTypeReader<ModuleInfo>
private readonly CommandService _cmds; private readonly CommandService _cmds;
public ModuleTypeReader(CommandService cmds) public ModuleTypeReader(CommandService cmds)
{ => _cmds = cmds;
_cmds = cmds;
}
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input) public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input)
{ {
@@ -25,9 +23,7 @@ public sealed class ModuleOrCrTypeReader : NadekoTypeReader<ModuleOrCrInfo>
private readonly CommandService _cmds; private readonly CommandService _cmds;
public ModuleOrCrTypeReader(CommandService cmds) public ModuleOrCrTypeReader(CommandService cmds)
{ => _cmds = cmds;
_cmds = cmds;
}
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input) public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input)
{ {

View File

@@ -5,7 +5,5 @@ public class CommentAttribute : Attribute
public string Comment { get; } public string Comment { get; }
public CommentAttribute(string comment) public CommentAttribute(string comment)
{ => Comment = comment;
Comment = comment;
}
} }

View File

@@ -9,16 +9,12 @@ public class CommentGatheringTypeInspector : TypeInspectorSkeleton
private readonly ITypeInspector innerTypeDescriptor; private readonly ITypeInspector innerTypeDescriptor;
public CommentGatheringTypeInspector(ITypeInspector innerTypeDescriptor) public CommentGatheringTypeInspector(ITypeInspector innerTypeDescriptor)
{ => this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor");
this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor");
}
public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object container) public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object container)
{ => innerTypeDescriptor
return innerTypeDescriptor
.GetProperties(type, container) .GetProperties(type, container)
.Select(d => new CommentsPropertyDescriptor(d)); .Select(d => new CommentsPropertyDescriptor(d));
}
private sealed class CommentsPropertyDescriptor : IPropertyDescriptor private sealed class CommentsPropertyDescriptor : IPropertyDescriptor
{ {
@@ -32,31 +28,29 @@ public class CommentGatheringTypeInspector : TypeInspectorSkeleton
public string Name { get; set; } public string Name { get; set; }
public Type Type { get { return baseDescriptor.Type; } } public Type Type
=> baseDescriptor.Type;
public Type TypeOverride { public Type TypeOverride {
get { return baseDescriptor.TypeOverride; } get => baseDescriptor.TypeOverride;
set { baseDescriptor.TypeOverride = value; } set => baseDescriptor.TypeOverride = value;
} }
public int Order { get; set; } public int Order { get; set; }
public ScalarStyle ScalarStyle { public ScalarStyle ScalarStyle {
get { return baseDescriptor.ScalarStyle; } get => baseDescriptor.ScalarStyle;
set { baseDescriptor.ScalarStyle = value; } set => baseDescriptor.ScalarStyle = value;
} }
public bool CanWrite { get { return baseDescriptor.CanWrite; } } public bool CanWrite
=> baseDescriptor.CanWrite;
public void Write(object target, object value) public void Write(object target, object value)
{ => baseDescriptor.Write(target, value);
baseDescriptor.Write(target, value);
}
public T GetCustomAttribute<T>() where T : Attribute public T GetCustomAttribute<T>() where T : Attribute
{ => baseDescriptor.GetCustomAttribute<T>();
return baseDescriptor.GetCustomAttribute<T>();
}
public IObjectDescriptor Read(object target) public IObjectDescriptor Read(object target)
{ {

View File

@@ -15,8 +15,15 @@ public sealed class CommentsObjectDescriptor : IObjectDescriptor
public string Comment { get; private set; } public string Comment { get; private set; }
public object Value { get { return innerDescriptor.Value; } } public object Value
public Type Type { get { return innerDescriptor.Type; } } => innerDescriptor.Value;
public Type StaticType { get { return innerDescriptor.StaticType; } }
public ScalarStyle ScalarStyle { get { return innerDescriptor.ScalarStyle; } } public Type Type
=> innerDescriptor.Type;
public Type StaticType
=> innerDescriptor.StaticType;
public ScalarStyle ScalarStyle
=> innerDescriptor.ScalarStyle;
} }

View File

@@ -9,9 +9,7 @@ namespace NadekoBot.Common.Yml;
public class Rgba32Converter : IYamlTypeConverter public class Rgba32Converter : IYamlTypeConverter
{ {
public bool Accepts(Type type) public bool Accepts(Type type)
{ => type == typeof(Rgba32);
return type == typeof(Rgba32);
}
public object ReadYaml(IParser parser, Type type) public object ReadYaml(IParser parser, Type type)
{ {
@@ -31,9 +29,7 @@ public class Rgba32Converter : IYamlTypeConverter
public class CultureInfoConverter : IYamlTypeConverter public class CultureInfoConverter : IYamlTypeConverter
{ {
public bool Accepts(Type type) public bool Accepts(Type type)
{ => type == typeof(CultureInfo);
return type == typeof(CultureInfo);
}
public object ReadYaml(IParser parser, Type type) public object ReadYaml(IParser parser, Type type)
{ {

View File

@@ -7,9 +7,7 @@ namespace NadekoBot.Common.Yml;
public class UriConverter : IYamlTypeConverter public class UriConverter : IYamlTypeConverter
{ {
public bool Accepts(Type type) public bool Accepts(Type type)
{ => type == typeof(Uri);
return type == typeof(Uri);
}
public object ReadYaml(IParser parser, Type type) public object ReadYaml(IParser parser, Type type)
{ {

View File

@@ -26,7 +26,7 @@ public class YamlHelper
// Check the value and write the character. // Check the value and write the character.
if (character is >= 0xD800 and <= 0xDFFF || character > 0x10FFFF) if (character is >= 0xD800 and <= 0xDFFF or > 0x10FFFF)
{ {
return point; return point;
} }
@@ -35,13 +35,8 @@ public class YamlHelper
} }
public static bool IsHex(char c) public static bool IsHex(char c)
{ => c is >= '0' and <= '9' or >= 'A' and <= 'F' or >= 'a' and <= 'f';
return
c is >= '0' and <= '9' ||
c is >= 'A' and <= 'F' ||
c is >= 'a' and <= 'f';
}
public static int AsHex(char c) public static int AsHex(char c)
{ {
if (c <= '9') if (c <= '9')

View File

@@ -34,12 +34,10 @@ public static class ClubExtensions
.Max() + 1; .Max() + 1;
public static List<ClubInfo> GetClubLeaderboardPage(this DbSet<ClubInfo> clubs, int page) public static List<ClubInfo> GetClubLeaderboardPage(this DbSet<ClubInfo> clubs, int page)
{ => clubs
return clubs
.AsNoTracking() .AsNoTracking()
.OrderByDescending(x => x.Xp) .OrderByDescending(x => x.Xp)
.Skip(page * 9) .Skip(page * 9)
.Take(9) .Take(9)
.ToList(); .ToList();
}
} }

View File

@@ -6,13 +6,11 @@ namespace NadekoBot.Db;
public static class CurrencyTransactionExtensions public static class CurrencyTransactionExtensions
{ {
public static List<CurrencyTransaction> GetPageFor(this DbSet<CurrencyTransaction> set, ulong userId, int page) public static List<CurrencyTransaction> GetPageFor(this DbSet<CurrencyTransaction> set, ulong userId, int page)
{ => set.AsQueryable()
return set.AsQueryable()
.AsNoTracking() .AsNoTracking()
.Where(x => x.UserId == userId) .Where(x => x.UserId == userId)
.OrderByDescending(x => x.DateAdded) .OrderByDescending(x => x.DateAdded)
.Skip(15 * page) .Skip(15 * page)
.Take(15) .Take(15)
.ToList(); .ToList();
}
} }

View File

@@ -7,21 +7,15 @@ namespace NadekoBot.Db;
public static class CustomReactionsExtensions public static class CustomReactionsExtensions
{ {
public static int ClearFromGuild(this DbSet<CustomReaction> crs, ulong guildId) public static int ClearFromGuild(this DbSet<CustomReaction> crs, ulong guildId)
{ => crs.Delete(x => x.GuildId == guildId);
return crs.Delete(x => x.GuildId == guildId);
}
public static IEnumerable<CustomReaction> ForId(this DbSet<CustomReaction> crs, ulong id) public static IEnumerable<CustomReaction> ForId(this DbSet<CustomReaction> crs, ulong id)
{ => crs
return crs
.AsNoTracking() .AsNoTracking()
.AsQueryable() .AsQueryable()
.Where(x => x.GuildId == id) .Where(x => x.GuildId == id)
.ToArray(); .ToArray();
}
public static CustomReaction GetByGuildIdAndInput(this DbSet<CustomReaction> crs, ulong? guildId, string input) public static CustomReaction GetByGuildIdAndInput(this DbSet<CustomReaction> crs, ulong? guildId, string input)
{ => crs.FirstOrDefault(x => x.GuildId == guildId && x.Trigger.ToUpper() == input);
return crs.FirstOrDefault(x => x.GuildId == guildId && x.Trigger.ToUpper() == input);
}
} }

View File

@@ -9,8 +9,7 @@ namespace NadekoBot.Db;
public static class DiscordUserExtensions public static class DiscordUserExtensions
{ {
public static void EnsureUserCreated(this NadekoContext ctx, ulong userId, string username, string discrim, string avatarId) public static void EnsureUserCreated(this NadekoContext ctx, ulong userId, string username, string discrim, string avatarId)
{ => ctx.DiscordUser
ctx.DiscordUser
.ToLinqToDBTable() .ToLinqToDBTable()
.InsertOrUpdate(() => new() .InsertOrUpdate(() => new()
{ {
@@ -30,7 +29,6 @@ public static class DiscordUserExtensions
{ {
UserId = userId UserId = userId
}); });
}
//temp is only used in updatecurrencystate, so that i don't overwrite real usernames/discrims with Unknown //temp is only used in updatecurrencystate, so that i don't overwrite real usernames/discrims with Unknown
public static DiscordUser GetOrCreateUser(this NadekoContext ctx, ulong userId, string username, string discrim, string avatarId) public static DiscordUser GetOrCreateUser(this NadekoContext ctx, ulong userId, string username, string discrim, string avatarId)
@@ -45,44 +43,36 @@ public static class DiscordUserExtensions
=> ctx.GetOrCreateUser(original.Id, original.Username, original.Discriminator, original.AvatarId); => ctx.GetOrCreateUser(original.Id, original.Username, original.Discriminator, original.AvatarId);
public static int GetUserGlobalRank(this DbSet<DiscordUser> users, ulong id) public static int GetUserGlobalRank(this DbSet<DiscordUser> users, ulong id)
{ => users.AsQueryable()
return users.AsQueryable()
.Where(x => x.TotalXp > users .Where(x => x.TotalXp > users
.AsQueryable() .AsQueryable()
.Where(y => y.UserId == id) .Where(y => y.UserId == id)
.Select(y => y.TotalXp) .Select(y => y.TotalXp)
.FirstOrDefault()) .FirstOrDefault())
.Count() + 1; .Count() + 1;
}
public static DiscordUser[] GetUsersXpLeaderboardFor(this DbSet<DiscordUser> users, int page) public static DiscordUser[] GetUsersXpLeaderboardFor(this DbSet<DiscordUser> users, int page)
{ => users.AsQueryable()
return users.AsQueryable()
.OrderByDescending(x => x.TotalXp) .OrderByDescending(x => x.TotalXp)
.Skip(page * 9) .Skip(page * 9)
.Take(9) .Take(9)
.AsEnumerable() .AsEnumerable()
.ToArray(); .ToArray();
}
public static List<DiscordUser> GetTopRichest(this DbSet<DiscordUser> users, ulong botId, int count, int page = 0) public static List<DiscordUser> GetTopRichest(this DbSet<DiscordUser> users, ulong botId, int count, int page = 0)
{ => users.AsQueryable()
return users.AsQueryable()
.Where(c => c.CurrencyAmount > 0 && botId != c.UserId) .Where(c => c.CurrencyAmount > 0 && botId != c.UserId)
.OrderByDescending(c => c.CurrencyAmount) .OrderByDescending(c => c.CurrencyAmount)
.Skip(page * 9) .Skip(page * 9)
.Take(count) .Take(count)
.ToList(); .ToList();
}
public static List<DiscordUser> GetTopRichest(this DbSet<DiscordUser> users, ulong botId, int count) public static List<DiscordUser> GetTopRichest(this DbSet<DiscordUser> users, ulong botId, int count)
{ => users.AsQueryable()
return users.AsQueryable()
.Where(c => c.CurrencyAmount > 0 && botId != c.UserId) .Where(c => c.CurrencyAmount > 0 && botId != c.UserId)
.OrderByDescending(c => c.CurrencyAmount) .OrderByDescending(c => c.CurrencyAmount)
.Take(count) .Take(count)
.ToList(); .ToList();
}
public static long GetUserCurrency(this DbSet<DiscordUser> users, ulong userId) => public static long GetUserCurrency(this DbSet<DiscordUser> users, ulong userId) =>
users.AsNoTracking() users.AsNoTracking()
@@ -163,17 +153,13 @@ VALUES ({userId}, {name}, {discrim}, {avatarId}, {amount}, 0);
} }
public static decimal GetTotalCurrency(this DbSet<DiscordUser> users) public static decimal GetTotalCurrency(this DbSet<DiscordUser> users)
{ => users
return users
.Sum((Func<DiscordUser, decimal>)(x => x.CurrencyAmount)); .Sum((Func<DiscordUser, decimal>)(x => x.CurrencyAmount));
}
public static decimal GetTopOnePercentCurrency(this DbSet<DiscordUser> users, ulong botId) public static decimal GetTopOnePercentCurrency(this DbSet<DiscordUser> users, ulong botId)
{ => users.AsQueryable()
return users.AsQueryable()
.Where(x => x.UserId != botId) .Where(x => x.UserId != botId)
.OrderByDescending(x => x.CurrencyAmount) .OrderByDescending(x => x.CurrencyAmount)
.Take(users.Count() / 100 == 0 ? 1 : users.Count() / 100) .Take(users.Count() / 100 == 0 ? 1 : users.Count() / 100)
.Sum(x => x.CurrencyAmount); .Sum(x => x.CurrencyAmount);
}
} }

View File

@@ -44,20 +44,17 @@ public static class GuildConfigExtensions
}; };
private static IQueryable<GuildConfig> IncludeEverything(this DbSet<GuildConfig> configs) private static IQueryable<GuildConfig> IncludeEverything(this DbSet<GuildConfig> configs)
{ => configs
return configs .AsQueryable()
.AsQueryable() .AsSplitQuery()
.AsSplitQuery() .Include(gc => gc.CommandCooldowns)
.Include(gc => gc.CommandCooldowns) .Include(gc => gc.FollowedStreams)
.Include(gc => gc.FollowedStreams) .Include(gc => gc.StreamRole)
.Include(gc => gc.StreamRole) .Include(gc => gc.XpSettings)
.Include(gc => gc.XpSettings) .ThenInclude(x => x.ExclusionList)
.ThenInclude(x => x.ExclusionList) .Include(gc => gc.DelMsgOnCmdChannels)
.Include(gc => gc.DelMsgOnCmdChannels) .Include(gc => gc.ReactionRoleMessages)
.Include(gc => gc.ReactionRoleMessages) .ThenInclude(x => x.ReactionRoles);
.ThenInclude(x => x.ReactionRoles)
;
}
public static IEnumerable<GuildConfig> GetAllGuildConfigs(this DbSet<GuildConfig> configs, List<ulong> availableGuilds) public static IEnumerable<GuildConfig> GetAllGuildConfigs(this DbSet<GuildConfig> configs, List<ulong> availableGuilds)
=> configs => configs
@@ -168,22 +165,18 @@ public static class GuildConfigExtensions
} }
public static IEnumerable<FollowedStream> GetFollowedStreams(this DbSet<GuildConfig> configs) public static IEnumerable<FollowedStream> GetFollowedStreams(this DbSet<GuildConfig> configs)
{ => configs
return configs
.AsQueryable() .AsQueryable()
.Include(x => x.FollowedStreams) .Include(x => x.FollowedStreams)
.SelectMany(gc => gc.FollowedStreams) .SelectMany(gc => gc.FollowedStreams)
.ToArray(); .ToArray();
}
public static IEnumerable<FollowedStream> GetFollowedStreams(this DbSet<GuildConfig> configs, List<ulong> included) public static IEnumerable<FollowedStream> GetFollowedStreams(this DbSet<GuildConfig> configs, List<ulong> included)
{ => configs.AsQueryable()
return configs.AsQueryable()
.Where(gc => included.Contains(gc.GuildId)) .Where(gc => included.Contains(gc.GuildId))
.Include(gc => gc.FollowedStreams) .Include(gc => gc.FollowedStreams)
.SelectMany(gc => gc.FollowedStreams) .SelectMany(gc => gc.FollowedStreams)
.ToList(); .ToList();
}
public static void SetCleverbotEnabled(this DbSet<GuildConfig> configs, ulong id, bool cleverbotEnabled) public static void SetCleverbotEnabled(this DbSet<GuildConfig> configs, ulong id, bool cleverbotEnabled)
{ {
@@ -212,8 +205,7 @@ public static class GuildConfigExtensions
} }
public static IEnumerable<GeneratingChannel> GetGeneratingChannels(this DbSet<GuildConfig> configs) public static IEnumerable<GeneratingChannel> GetGeneratingChannels(this DbSet<GuildConfig> configs)
{ => configs
return configs
.AsQueryable() .AsQueryable()
.Include(x => x.GenerateCurrencyChannelIds) .Include(x => x.GenerateCurrencyChannelIds)
.Where(x => x.GenerateCurrencyChannelIds.Any()) .Where(x => x.GenerateCurrencyChannelIds.Any())
@@ -224,5 +216,4 @@ public static class GuildConfigExtensions
GuildId = x.GuildConfig.GuildId GuildId = x.GuildConfig.GuildId
}) })
.ToArray(); .ToArray();
}
} }

View File

@@ -7,11 +7,9 @@ namespace NadekoBot.Db;
public static class PollExtensions public static class PollExtensions
{ {
public static IEnumerable<Poll> GetAllPolls(this DbSet<Poll> polls) public static IEnumerable<Poll> GetAllPolls(this DbSet<Poll> polls)
{ => polls.Include(x => x.Answers)
return polls.Include(x => x.Answers)
.Include(x => x.Votes) .Include(x => x.Votes)
.ToArray(); .ToArray();
}
public static void RemovePoll(this NadekoContext ctx, int id) public static void RemovePoll(this NadekoContext ctx, int id)
{ {

View File

@@ -6,10 +6,8 @@ namespace NadekoBot.Db;
public static class QuoteExtensions public static class QuoteExtensions
{ {
public static IEnumerable<Quote> GetForGuild(this DbSet<Quote> quotes, ulong guildId) public static IEnumerable<Quote> GetForGuild(this DbSet<Quote> quotes, ulong guildId)
{ => quotes.AsQueryable().Where(x => x.GuildId == guildId);
return quotes.AsQueryable().Where(x => x.GuildId == guildId);
}
public static IEnumerable<Quote> GetGroup(this DbSet<Quote> quotes, ulong guildId, int page, OrderType order) public static IEnumerable<Quote> GetGroup(this DbSet<Quote> quotes, ulong guildId, int page, OrderType order)
{ {
var q = quotes.AsQueryable().Where(x => x.GuildId == guildId); var q = quotes.AsQueryable().Where(x => x.GuildId == guildId);
@@ -46,8 +44,5 @@ public static class QuoteExtensions
} }
public static void RemoveAllByKeyword(this DbSet<Quote> quotes, ulong guildId, string keyword) public static void RemoveAllByKeyword(this DbSet<Quote> quotes, ulong guildId, string keyword)
{ => quotes.RemoveRange(quotes.AsQueryable().Where(x => x.GuildId == guildId && x.Keyword.ToUpper() == keyword));
quotes.RemoveRange(quotes.AsQueryable().Where(x => x.GuildId == guildId && x.Keyword.ToUpper() == keyword));
}
} }

View File

@@ -26,8 +26,7 @@ public static class UserXpExtensions
} }
public static List<UserXpStats> GetUsersFor(this DbSet<UserXpStats> xps, ulong guildId, int page) public static List<UserXpStats> GetUsersFor(this DbSet<UserXpStats> xps, ulong guildId, int page)
{ => xps
return xps
.AsQueryable() .AsQueryable()
.AsNoTracking() .AsNoTracking()
.Where(x => x.GuildId == guildId) .Where(x => x.GuildId == guildId)
@@ -35,29 +34,24 @@ public static class UserXpExtensions
.Skip(page * 9) .Skip(page * 9)
.Take(9) .Take(9)
.ToList(); .ToList();
}
public static List<UserXpStats> GetTopUserXps(this DbSet<UserXpStats> xps, ulong guildId, int count) public static List<UserXpStats> GetTopUserXps(this DbSet<UserXpStats> xps, ulong guildId, int count)
{ => xps
return xps
.AsQueryable() .AsQueryable()
.AsNoTracking() .AsNoTracking()
.Where(x => x.GuildId == guildId) .Where(x => x.GuildId == guildId)
.OrderByDescending(x => x.Xp + x.AwardedXp) .OrderByDescending(x => x.Xp + x.AwardedXp)
.Take(count) .Take(count)
.ToList(); .ToList();
}
public static int GetUserGuildRanking(this DbSet<UserXpStats> xps, ulong userId, ulong guildId) public static int GetUserGuildRanking(this DbSet<UserXpStats> xps, ulong userId, ulong guildId)
{
// @"SELECT COUNT(*) + 1 // @"SELECT COUNT(*) + 1
//FROM UserXpStats //FROM UserXpStats
//WHERE GuildId = @p1 AND ((Xp + AwardedXp) > (SELECT Xp + AwardedXp //WHERE GuildId = @p1 AND ((Xp + AwardedXp) > (SELECT Xp + AwardedXp
// FROM UserXpStats // FROM UserXpStats
// WHERE UserId = @p2 AND GuildId = @p1 // WHERE UserId = @p2 AND GuildId = @p1
// LIMIT 1));"; // LIMIT 1));";
=> xps
return xps
.AsQueryable() .AsQueryable()
.AsNoTracking() .AsNoTracking()
.Where(x => x.GuildId == guildId && x.Xp + x.AwardedXp > .Where(x => x.GuildId == guildId && x.Xp + x.AwardedXp >
@@ -66,15 +60,10 @@ public static class UserXpExtensions
.Select(y => y.Xp + y.AwardedXp) .Select(y => y.Xp + y.AwardedXp)
.FirstOrDefault()) .FirstOrDefault())
.Count() + 1; .Count() + 1;
}
public static void ResetGuildUserXp(this DbSet<UserXpStats> xps, ulong userId, ulong guildId) public static void ResetGuildUserXp(this DbSet<UserXpStats> xps, ulong userId, ulong guildId)
{ => xps.Delete(x => x.UserId == userId && x.GuildId == guildId);
xps.Delete(x => x.UserId == userId && x.GuildId == guildId);
}
public static void ResetGuildXp(this DbSet<UserXpStats> xps, ulong guildId) public static void ResetGuildXp(this DbSet<UserXpStats> xps, ulong guildId)
{ => xps.Delete(x => x.GuildId == guildId);
xps.Delete(x => x.GuildId == guildId);
}
} }

View File

@@ -65,24 +65,20 @@ public static class WaifuExtensions
} }
public static decimal GetTotalValue(this DbSet<WaifuInfo> waifus) public static decimal GetTotalValue(this DbSet<WaifuInfo> waifus)
{ => waifus
return waifus
.AsQueryable() .AsQueryable()
.Where(x => x.ClaimerId != null) .Where(x => x.ClaimerId != null)
.Sum(x => x.Price); .Sum(x => x.Price);
}
public static ulong GetWaifuUserId(this DbSet<WaifuInfo> waifus, ulong ownerId, string name) public static ulong GetWaifuUserId(this DbSet<WaifuInfo> waifus, ulong ownerId, string name)
{ => waifus
return waifus
.AsQueryable() .AsQueryable()
.AsNoTracking() .AsNoTracking()
.Where(x => x.Claimer.UserId == ownerId .Where(x => x.Claimer.UserId == ownerId
&& x.Waifu.Username + "#" + x.Waifu.Discriminator == name) && x.Waifu.Username + "#" + x.Waifu.Discriminator == name)
.Select(x => x.Waifu.UserId) .Select(x => x.Waifu.UserId)
.FirstOrDefault(); .FirstOrDefault();
}
public static WaifuInfoStats GetWaifuInfo(this NadekoContext ctx, ulong userId) public static WaifuInfoStats GetWaifuInfo(this NadekoContext ctx, ulong userId)
{ {
ctx.Database.ExecuteSqlInterpolated($@" ctx.Database.ExecuteSqlInterpolated($@"

View File

@@ -33,8 +33,7 @@ public static class WarningExtensions
} }
public static async Task ForgiveAll(this DbSet<Warning> warnings, ulong guildId, ulong userId, string mod) public static async Task ForgiveAll(this DbSet<Warning> warnings, ulong guildId, ulong userId, string mod)
{ => await warnings.AsQueryable().Where(x => x.GuildId == guildId && x.UserId == userId)
await warnings.AsQueryable().Where(x => x.GuildId == guildId && x.UserId == userId)
.ForEachAsync(x => .ForEachAsync(x =>
{ {
if (x.Forgiven != true) if (x.Forgiven != true)
@@ -43,10 +42,7 @@ public static class WarningExtensions
x.ForgivenBy = mod; x.ForgivenBy = mod;
} }
}); });
}
public static Warning[] GetForGuild(this DbSet<Warning> warnings, ulong id) public static Warning[] GetForGuild(this DbSet<Warning> warnings, ulong id)
{ => warnings.AsQueryable().Where(x => x.GuildId == id).ToArray();
return warnings.AsQueryable().Where(x => x.GuildId == id).ToArray();
}
} }

View File

@@ -57,9 +57,7 @@ public class AntiSpamIgnore : DbEntity
public override int GetHashCode() => ChannelId.GetHashCode(); public override int GetHashCode() => ChannelId.GetHashCode();
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is AntiSpamIgnore inst
return obj is AntiSpamIgnore inst
? inst.ChannelId == ChannelId ? inst.ChannelId == ChannelId
: false; : false;
}
} }

View File

@@ -23,9 +23,7 @@ public class ClubInfo : DbEntity
public string Description { get; set; } public string Description { get; set; }
public override string ToString() public override string ToString()
{ => Name + "#" + Discrim;
return Name + "#" + Discrim;
}
} }
public class ClubApplicants public class ClubApplicants

View File

@@ -17,7 +17,7 @@ public class CustomReaction : DbEntity
? Array.Empty<string>() ? Array.Empty<string>()
: Reactions.Split("@@@"); : Reactions.Split("@@@");
public bool IsGlobal() => GuildId is null || GuildId == 0; public bool IsGlobal() => GuildId is null or 0;
} }
public class ReactionResponse : DbEntity public class ReactionResponse : DbEntity

View File

@@ -6,13 +6,9 @@ public class DelMsgOnCmdChannel : DbEntity
public bool State { get; set; } public bool State { get; set; }
public override int GetHashCode() public override int GetHashCode()
{ => ChannelId.GetHashCode();
return ChannelId.GetHashCode();
}
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is DelMsgOnCmdChannel x
return obj is DelMsgOnCmdChannel x && x.ChannelId == ChannelId;
&& x.ChannelId == ChannelId;
}
} }

View File

@@ -20,16 +20,12 @@ public class DiscordUser : DbEntity
public long CurrencyAmount { get; set; } public long CurrencyAmount { get; set; }
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is DiscordUser du
return obj is DiscordUser du
? du.UserId == UserId ? du.UserId == UserId
: false; : false;
}
public override int GetHashCode() public override int GetHashCode()
{ => UserId.GetHashCode();
return UserId.GetHashCode();
}
public override string ToString() => public override string ToString() =>
Username + "#" + Discriminator; Username + "#" + Discriminator;

View File

@@ -9,14 +9,10 @@ public class FeedSub : DbEntity
public string Url { get; set; } public string Url { get; set; }
public override int GetHashCode() public override int GetHashCode()
{ => Url.GetHashCode(StringComparison.InvariantCulture) ^ GuildConfigId.GetHashCode();
return Url.GetHashCode(StringComparison.InvariantCulture) ^ GuildConfigId.GetHashCode();
}
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is FeedSub s
return obj is FeedSub s && s.Url.ToLower() == Url.ToLower()
&& s.Url.ToLower() == Url.ToLower() && s.GuildConfigId == GuildConfigId;
&& s.GuildConfigId == GuildConfigId;
}
} }

View File

@@ -20,16 +20,12 @@ public class FollowedStream : DbEntity
} }
protected bool Equals(FollowedStream other) protected bool Equals(FollowedStream other)
{ => ChannelId == other.ChannelId
return ChannelId == other.ChannelId && Username.Trim().ToUpperInvariant() == other.Username.Trim().ToUpperInvariant()
&& Username.Trim().ToUpperInvariant() == other.Username.Trim().ToUpperInvariant() && Type == other.Type;
&& Type == other.Type;
}
public override int GetHashCode() public override int GetHashCode()
{ => HashCode.Combine(ChannelId, Username, (int) Type);
return HashCode.Combine(ChannelId, Username, (int) Type);
}
public override bool Equals(object obj) public override bool Equals(object obj)
=> obj is FollowedStream fs && Equals(fs); => obj is FollowedStream fs && Equals(fs);

View File

@@ -6,11 +6,9 @@ public class GCChannelId : DbEntity
public ulong ChannelId { get; set; } public ulong ChannelId { get; set; }
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is GCChannelId gc
return obj is GCChannelId gc
? gc.ChannelId == ChannelId ? gc.ChannelId == ChannelId
: false; : false;
}
public override int GetHashCode() => public override int GetHashCode() =>
this.ChannelId.GetHashCode(); this.ChannelId.GetHashCode();

View File

@@ -5,14 +5,10 @@ public class MutedUserId : DbEntity
public ulong UserId { get; set; } public ulong UserId { get; set; }
public override int GetHashCode() public override int GetHashCode()
{ => UserId.GetHashCode();
return UserId.GetHashCode();
}
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is MutedUserId mui
return obj is MutedUserId mui
? mui.UserId == UserId ? mui.UserId == UserId
: false; : false;
}
} }

View File

@@ -6,14 +6,10 @@ public class PollVote : DbEntity
public int VoteIndex { get; set; } public int VoteIndex { get; set; }
public override int GetHashCode() public override int GetHashCode()
{ => UserId.GetHashCode();
return UserId.GetHashCode();
}
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is PollVote p
return obj is PollVote p
? p.UserId == UserId ? p.UserId == UserId
: false; : false;
}
} }

View File

@@ -17,7 +17,5 @@ public class SlowmodeIgnoredRole : DbEntity
// override object.GetHashCode // override object.GetHashCode
public override int GetHashCode() public override int GetHashCode()
{ => RoleId.GetHashCode();
return RoleId.GetHashCode();
}
} }

View File

@@ -17,7 +17,5 @@ public class SlowmodeIgnoredUser : DbEntity
// override object.GetHashCode // override object.GetHashCode
public override int GetHashCode() public override int GetHashCode()
{ => UserId.GetHashCode();
return UserId.GetHashCode();
}
} }

View File

@@ -51,9 +51,7 @@ public class StreamRoleBlacklistedUser : DbEntity
} }
public override int GetHashCode() public override int GetHashCode()
{ => UserId.GetHashCode();
return UserId.GetHashCode();
}
} }
public class StreamRoleWhitelistedUser : DbEntity public class StreamRoleWhitelistedUser : DbEntity
@@ -62,14 +60,10 @@ public class StreamRoleWhitelistedUser : DbEntity
public string Username { get; set; } public string Username { get; set; }
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is StreamRoleWhitelistedUser x
return obj is StreamRoleWhitelistedUser x
? x.UserId == UserId ? x.UserId == UserId
: false; : false;
}
public override int GetHashCode() public override int GetHashCode()
{ => UserId.GetHashCode();
return UserId.GetHashCode();
}
} }

View File

@@ -9,9 +9,7 @@ public class UnbanTimer : DbEntity
UserId.GetHashCode(); UserId.GetHashCode();
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is UnbanTimer ut
return obj is UnbanTimer ut
? ut.UserId == UserId ? ut.UserId == UserId
: false; : false;
}
} }

View File

@@ -9,9 +9,7 @@ public class UnmuteTimer : DbEntity
UserId.GetHashCode(); UserId.GetHashCode();
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is UnmuteTimer ut
return obj is UnmuteTimer ut
? ut.UserId == UserId ? ut.UserId == UserId
: false; : false;
}
} }

View File

@@ -10,9 +10,7 @@ public class UnroleTimer : DbEntity
UserId.GetHashCode() ^ RoleId.GetHashCode(); UserId.GetHashCode() ^ RoleId.GetHashCode();
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is UnroleTimer ut
return obj is UnroleTimer ut
? ut.UserId == UserId && ut.RoleId == RoleId ? ut.UserId == UserId && ut.RoleId == RoleId
: false; : false;
}
} }

View File

@@ -27,14 +27,10 @@ public class XpRoleReward : DbEntity
public bool Remove { get; set; } public bool Remove { get; set; }
public override int GetHashCode() public override int GetHashCode()
{ => Level.GetHashCode() ^ XpSettingsId.GetHashCode();
return Level.GetHashCode() ^ XpSettingsId.GetHashCode();
}
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is XpRoleReward xrr && xrr.Level == Level && xrr.XpSettingsId == XpSettingsId;
return obj is XpRoleReward xrr && xrr.Level == Level && xrr.XpSettingsId == XpSettingsId;
}
} }
public class XpCurrencyReward : DbEntity public class XpCurrencyReward : DbEntity
@@ -46,14 +42,10 @@ public class XpCurrencyReward : DbEntity
public int Amount { get; set; } public int Amount { get; set; }
public override int GetHashCode() public override int GetHashCode()
{ => Level.GetHashCode() ^ XpSettingsId.GetHashCode();
return Level.GetHashCode() ^ XpSettingsId.GetHashCode();
}
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is XpCurrencyReward xrr && xrr.Level == Level && xrr.XpSettingsId == XpSettingsId;
return obj is XpCurrencyReward xrr && xrr.Level == Level && xrr.XpSettingsId == XpSettingsId;
}
} }
public class ExcludedItem : DbEntity public class ExcludedItem : DbEntity
@@ -62,12 +54,8 @@ public class ExcludedItem : DbEntity
public ExcludedItemType ItemType { get; set; } public ExcludedItemType ItemType { get; set; }
public override int GetHashCode() public override int GetHashCode()
{ => ItemId.GetHashCode() ^ ItemType.GetHashCode();
return ItemId.GetHashCode() ^ ItemType.GetHashCode();
}
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is ExcludedItem ei && ei.ItemId == ItemId && ei.ItemType == ItemType;
return obj is ExcludedItem ei && ei.ItemId == ItemId && ei.ItemType == ItemType;
}
} }

View File

@@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore.Design;
using NadekoBot.Services.Database.Models; using NadekoBot.Services.Database.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NadekoBot.Db.Models; using NadekoBot.Db.Models;
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace NadekoBot.Services.Database; namespace NadekoBot.Services.Database;
@@ -68,9 +69,7 @@ public class NadekoContext : DbContext
private static readonly ILoggerFactory _debugLoggerFactory = private static readonly ILoggerFactory _debugLoggerFactory =
LoggerFactory.Create(x => x.AddConsole()); LoggerFactory.Create(x => x.AddConsole());
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ => optionsBuilder.UseLoggerFactory(_debugLoggerFactory);
optionsBuilder.UseLoggerFactory(_debugLoggerFactory);
}
#endif #endif
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)

View File

@@ -8,10 +8,8 @@ public partial class Administration : NadekoModule<AdministrationService>
private readonly ImageOnlyChannelService _imageOnly; private readonly ImageOnlyChannelService _imageOnly;
public Administration(ImageOnlyChannelService imageOnly) public Administration(ImageOnlyChannelService imageOnly)
{ => _imageOnly = imageOnly;
_imageOnly = imageOnly;
}
public enum List public enum List
{ {
List = 0, List = 0,
@@ -292,9 +290,7 @@ public partial class Administration : NadekoModule<AdministrationService>
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task Delete(ITextChannel channel, ulong messageId, StoopidTime time = null) public async Task Delete(ITextChannel channel, ulong messageId, StoopidTime time = null)
{ => await InternalMessageAction(channel, messageId, time, msg => msg.DeleteAsync());
await InternalMessageAction(channel, messageId, time, msg => msg.DeleteAsync());
}
private async Task InternalMessageAction(ITextChannel channel, ulong messageId, StoopidTime time, private async Task InternalMessageAction(ITextChannel channel, ulong messageId, StoopidTime time,
Func<IMessage, Task> func) Func<IMessage, Task> func)

View File

@@ -61,7 +61,7 @@ public partial class Administration
await ReplyConfirmLocalizedAsync(strs.aar_roles( await ReplyConfirmLocalizedAsync(strs.aar_roles(
'\n' + existing.Select(x => Format.Bold(x.ToString())) '\n' + existing.Select(x => Format.Bold(x.ToString()))
.JoinWith(",\n"))); .Join(",\n")));
} }
} }
} }

View File

@@ -1,5 +1,4 @@
using NadekoBot.Common.Collections; using NadekoBot.Services.Database.Models;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Administration.Common; namespace NadekoBot.Modules.Administration.Common;
@@ -35,10 +34,8 @@ public class AntiAltStats
public int Counter => _counter; public int Counter => _counter;
public AntiAltStats(AntiAltSetting setting) public AntiAltStats(AntiAltSetting setting)
{ => _setting = setting;
_setting = setting;
}
public void Increment() => Interlocked.Increment(ref _counter); public void Increment() => Interlocked.Increment(ref _counter);
} }

View File

@@ -42,11 +42,9 @@ public partial class Administration
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
[Priority(0)] [Priority(0)]
public async Task LanguageSet() public async Task LanguageSet()
{ => await ReplyConfirmLocalizedAsync(strs.lang_set_show(
await ReplyConfirmLocalizedAsync(strs.lang_set_show(
Format.Bold(_cultureInfo.ToString()), Format.Bold(_cultureInfo.ToString()),
Format.Bold(_cultureInfo.NativeName))); Format.Bold(_cultureInfo.NativeName)));
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
@@ -113,12 +111,10 @@ public partial class Administration
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
public async Task LanguagesList() public async Task LanguagesList()
{ => await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
.WithTitle(GetText(strs.lang_list)) .WithTitle(GetText(strs.lang_list))
.WithDescription(string.Join("\n", .WithDescription(string.Join("\n",
supportedLocales.Select(x => $"{Format.Code(x.Key),-10} => {x.Value}")))).ConfigureAwait(false); supportedLocales.Select(x => $"{Format.Code(x.Key),-10} => {x.Value}")))).ConfigureAwait(false);
}
} }
} }
/* list of language codes for reference. /* list of language codes for reference.

View File

@@ -8,9 +8,7 @@ public partial class Administration
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[Priority(1)] [Priority(1)]
public async Task PrefixCommand() public async Task PrefixCommand()
{ => await ReplyConfirmLocalizedAsync(strs.prefix_current(Format.Code(CmdHandler.GetPrefix(ctx.Guild)))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.prefix_current(Format.Code(CmdHandler.GetPrefix(ctx.Guild)))).ConfigureAwait(false);
}
public enum Set public enum Set
{ {

View File

@@ -94,13 +94,13 @@ public partial class Administration
return; return;
} }
if (userThreshold < 2 || userThreshold > 30) if (userThreshold is < 2 or > 30)
{ {
await ReplyErrorLocalizedAsync(strs.raid_cnt(2, 30)); await ReplyErrorLocalizedAsync(strs.raid_cnt(2, 30));
return; return;
} }
if (seconds < 2 || seconds > 300) if (seconds is < 2 or > 300)
{ {
await ReplyErrorLocalizedAsync(strs.raid_time(2, 300)); await ReplyErrorLocalizedAsync(strs.raid_time(2, 300));
return; return;
@@ -115,7 +115,7 @@ public partial class Administration
} }
var time = (int?) punishTime?.Time.TotalMinutes ?? 0; var time = (int?) punishTime?.Time.TotalMinutes ?? 0;
if (time < 0 || time > 60 * 24) if (time is < 0 or > 60 * 24)
return; return;
var stats = await _service.StartAntiRaidAsync(ctx.Guild.Id, userThreshold, seconds, var stats = await _service.StartAntiRaidAsync(ctx.Guild.Id, userThreshold, seconds,
@@ -175,7 +175,7 @@ public partial class Administration
public async Task InternalAntiSpam(int messageCount, PunishmentAction action, public async Task InternalAntiSpam(int messageCount, PunishmentAction action,
StoopidTime timeData = null, IRole role = null) StoopidTime timeData = null, IRole role = null)
{ {
if (messageCount < 2 || messageCount > 10) if (messageCount is < 2 or > 10)
return; return;
if (timeData is not null) if (timeData is not null)
@@ -187,7 +187,7 @@ public partial class Administration
} }
var time = (int?) timeData?.Time.TotalMinutes ?? 0; var time = (int?) timeData?.Time.TotalMinutes ?? 0;
if (time < 0 || time > 60 * 24) if (time is < 0 or > 60 * 24)
return; return;
var stats = await _service.StartAntiSpamAsync(ctx.Guild.Id, messageCount, action, time, role?.Id).ConfigureAwait(false); var stats = await _service.StartAntiSpamAsync(ctx.Guild.Id, messageCount, action, time, role?.Id).ConfigureAwait(false);

View File

@@ -17,7 +17,7 @@ public partial class Administration
{ {
var user = await ctx.Guild.GetCurrentUserAsync().ConfigureAwait(false); var user = await ctx.Guild.GetCurrentUserAsync().ConfigureAwait(false);
if (parameter == "-s" || parameter == "--safe") if (parameter is "-s" or "--safe")
await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id && !x.IsPinned).ConfigureAwait(false); await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id && !x.IsPinned).ConfigureAwait(false);
else else
await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id).ConfigureAwait(false); await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id).ConfigureAwait(false);
@@ -37,7 +37,7 @@ public partial class Administration
if (count > 1000) if (count > 1000)
count = 1000; count = 1000;
if (parameter == "-s" || parameter == "--safe") if (parameter is "-s" or "--safe")
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => !x.IsPinned).ConfigureAwait(false); await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => !x.IsPinned).ConfigureAwait(false);
else else
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => true).ConfigureAwait(false); await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => true).ConfigureAwait(false);
@@ -69,7 +69,7 @@ public partial class Administration
if (count > 1000) if (count > 1000)
count = 1000; count = 1000;
if (parameter == "-s" || parameter == "--safe") if (parameter is "-s" or "--safe")
await _service.PruneWhere((ITextChannel)ctx.Channel, count, m => m.Author.Id == userId && DateTime.UtcNow - m.CreatedAt < twoWeeks && !m.IsPinned).ConfigureAwait(false); await _service.PruneWhere((ITextChannel)ctx.Channel, count, m => m.Author.Id == userId && DateTime.UtcNow - m.CreatedAt < twoWeeks && !m.IsPinned).ConfigureAwait(false);
else else
await _service.PruneWhere((ITextChannel)ctx.Channel, count, m => m.Author.Id == userId && DateTime.UtcNow - m.CreatedAt < twoWeeks).ConfigureAwait(false); await _service.PruneWhere((ITextChannel)ctx.Channel, count, m => m.Author.Id == userId && DateTime.UtcNow - m.CreatedAt < twoWeeks).ConfigureAwait(false);

View File

@@ -13,9 +13,7 @@ public partial class Administration
public enum Exclude { Excl } public enum Exclude { Excl }
public RoleCommands(IServiceProvider services) public RoleCommands(IServiceProvider services)
{ => _services = services;
_services = services;
}
public async Task InternalReactionRoles(bool exclusive, ulong? messageId, params string[] input) public async Task InternalReactionRoles(bool exclusive, ulong? messageId, params string[] input)
{ {
@@ -326,9 +324,7 @@ public partial class Administration
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
[Priority(1)] [Priority(1)]
public async Task RoleColor([Leftover] IRole role) public async Task RoleColor([Leftover] IRole role)
{ => await SendConfirmAsync("Role Color", role.Color.RawValue.ToString("x6")).ConfigureAwait(false);
await SendConfirmAsync("Role Color", role.Color.RawValue.ToString("x6")).ConfigureAwait(false);
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]

View File

@@ -145,9 +145,7 @@ public partial class Administration
} }
private string GetIntervalText(int interval) private string GetIntervalText(int interval)
{ => $"[{GetText(strs.interval)}]: {interval}";
return $"[{GetText(strs.interval)}]: {interval}";
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[OwnerOnly] [OwnerOnly]
@@ -298,9 +296,7 @@ public partial class Administration
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[OwnerOnly] [OwnerOnly]
public Task Leave([Leftover] string guildStr) public Task Leave([Leftover] string guildStr)
{ => _service.LeaveGuild(guildStr);
return _service.LeaveGuild(guildStr);
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
@@ -450,7 +446,7 @@ public partial class Administration
if (ids[1].ToUpperInvariant().StartsWith("C:", StringComparison.InvariantCulture)) if (ids[1].ToUpperInvariant().StartsWith("C:", StringComparison.InvariantCulture))
{ {
var cid = ulong.Parse(ids[1].Substring(2)); var cid = ulong.Parse(ids[1][2..]);
var ch = server.TextChannels.FirstOrDefault(c => c.Id == cid); var ch = server.TextChannels.FirstOrDefault(c => c.Id == cid);
if (ch is null) if (ch is null)
return; return;
@@ -460,7 +456,7 @@ public partial class Administration
} }
else if (ids[1].ToUpperInvariant().StartsWith("U:", StringComparison.InvariantCulture)) else if (ids[1].ToUpperInvariant().StartsWith("U:", StringComparison.InvariantCulture))
{ {
var uid = ulong.Parse(ids[1].Substring(2)); var uid = ulong.Parse(ids[1][2..]);
var user = server.Users.FirstOrDefault(u => u.Id == uid); var user = server.Users.FirstOrDefault(u => u.Id == uid);
if (user is null) if (user is null)
return; return;

View File

@@ -23,7 +23,7 @@ public partial class Administration
[UserPerm(GuildPerm.ManageGuild)] [UserPerm(GuildPerm.ManageGuild)]
public async Task BoostDel(int timer = 30) public async Task BoostDel(int timer = 30)
{ {
if (timer < 0 || timer > 600) if (timer is < 0 or > 600)
return; return;
await _service.SetBoostDel(ctx.Guild.Id, timer); await _service.SetBoostDel(ctx.Guild.Id, timer);
@@ -66,7 +66,7 @@ public partial class Administration
[UserPerm(GuildPerm.ManageGuild)] [UserPerm(GuildPerm.ManageGuild)]
public async Task GreetDel(int timer = 30) public async Task GreetDel(int timer = 30)
{ {
if (timer < 0 || timer > 600) if (timer is < 0 or > 600)
return; return;
await _service.SetGreetDel(ctx.Guild.Id, timer).ConfigureAwait(false); await _service.SetGreetDel(ctx.Guild.Id, timer).ConfigureAwait(false);

View File

@@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models; using NadekoBot.Services.Database.Models;
using NadekoBot.Db; using NadekoBot.Db;

View File

@@ -155,7 +155,5 @@ public static class GuildConfigExtensions
} }
public static void SetAutoAssignableRoles(this GuildConfig gc, IEnumerable<ulong> roles) public static void SetAutoAssignableRoles(this GuildConfig gc, IEnumerable<ulong> roles)
{ => gc.AutoAssignRoleIds = roles.Join(',');
gc.AutoAssignRoleIds = roles.JoinWith(',');
}
} }

View File

@@ -33,9 +33,7 @@ DELETE FROM Clubs;";
private readonly DbService _db; private readonly DbService _db;
public DangerousCommandsService(DbService db) public DangerousCommandsService(DbService db)
{ => _db = db;
_db = db;
}
public async Task<int> ExecuteSql(string sql) public async Task<int> ExecuteSql(string sql)
{ {

View File

@@ -1,5 +1,4 @@
using NadekoBot.Common.Collections; using NadekoBot.Db;
using NadekoBot.Db;
namespace NadekoBot.Modules.Administration.Services; namespace NadekoBot.Modules.Administration.Services;

View File

@@ -2,7 +2,6 @@
using System.Threading.Channels; using System.Threading.Channels;
using LinqToDB; using LinqToDB;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using NadekoBot.Common.Collections;
using NadekoBot.Common.ModuleBehaviors; using NadekoBot.Common.ModuleBehaviors;
namespace NadekoBot.Modules.Administration.Services; namespace NadekoBot.Modules.Administration.Services;

View File

@@ -1,6 +1,5 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models; using NadekoBot.Services.Database.Models;
using NadekoBot.Db; using NadekoBot.Db;
using NadekoBot.Modules.Administration.Common; using NadekoBot.Modules.Administration.Common;
@@ -23,24 +22,16 @@ public sealed class DummyLogCommandService : ILogCommandService
} }
public Task LogServer(ulong guildId, ulong channelId, bool actionValue) public Task LogServer(ulong guildId, ulong channelId, bool actionValue)
{ => Task.CompletedTask;
return Task.CompletedTask;
}
public bool LogIgnore(ulong guildId, ulong itemId, IgnoredItemType itemType) public bool LogIgnore(ulong guildId, ulong itemId, IgnoredItemType itemType)
{ => false;
return false;
}
public LogSetting GetGuildLogSettings(ulong guildId) public LogSetting GetGuildLogSettings(ulong guildId)
{ => default;
return default;
}
public bool Log(ulong guildId, ulong? channelId, LogType type) public bool Log(ulong guildId, ulong? channelId, LogType type)
{ => false;
return false;
}
} }
public sealed class LogCommandService : ILogCommandService public sealed class LogCommandService : ILogCommandService
@@ -150,9 +141,7 @@ public sealed class LogCommandService : ILogCommandService
} }
public void AddDeleteIgnore(ulong messageId) public void AddDeleteIgnore(ulong messageId)
{ => _ignoreMessageIds.Add(messageId);
_ignoreMessageIds.Add(messageId);
}
public bool LogIgnore(ulong gid, ulong itemId, IgnoredItemType itemType) public bool LogIgnore(ulong gid, ulong itemId, IgnoredItemType itemType)
{ {
@@ -1172,7 +1161,7 @@ public sealed class LogCommandService : ILogCommandService
break; break;
} }
if (!id.HasValue || id == 0) if (id is null or 0)
{ {
UnsetLogSetting(guild.Id, logChannelType); UnsetLogSetting(guild.Id, logChannelType);
return null; return null;

View File

@@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models; using NadekoBot.Services.Database.Models;
using NadekoBot.Db; using NadekoBot.Db;

View File

@@ -317,7 +317,11 @@ public class ProtectionService : INService
{ {
if (_antiSpamGuilds.TryRemove(guildId, out var removed)) if (_antiSpamGuilds.TryRemove(guildId, out var removed))
{ {
removed.UserStats.ForEach(x => x.Value.Dispose()); foreach (var (_, val) in removed.UserStats)
{
val.Dispose();
}
using var uow = _db.GetDbContext(); using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting) var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting)
.ThenInclude(x => x.IgnoredChannels)); .ThenInclude(x => x.IgnoredChannels));

View File

@@ -1,22 +1,19 @@
using NadekoBot.Common.Collections; namespace NadekoBot.Modules.Administration.Services;
namespace NadekoBot.Modules.Administration.Services;
public class PruneService : INService public class PruneService : INService
{ {
//channelids where prunes are currently occuring //channelids where prunes are currently occuring
private readonly ConcurrentHashSet<ulong> _pruningGuilds = new(); private readonly ConcurrentHashSet<ulong> _pruningGuilds = new();
private readonly TimeSpan twoWeeks = TimeSpan.FromDays(14); private readonly TimeSpan _twoWeeks = TimeSpan.FromDays(14);
private readonly ILogCommandService _logService; private readonly ILogCommandService _logService;
public PruneService(ILogCommandService logService) public PruneService(ILogCommandService logService)
{ => this._logService = logService;
this._logService = logService;
}
public async Task PruneWhere(ITextChannel channel, int amount, Func<IMessage, bool> predicate) public async Task PruneWhere(ITextChannel channel, int amount, Func<IMessage, bool> predicate)
{ {
channel.ThrowIfNull(nameof(channel)); ArgumentNullException.ThrowIfNull(channel, nameof(channel));
if (amount <= 0) if (amount <= 0)
throw new ArgumentOutOfRangeException(nameof(amount)); throw new ArgumentOutOfRangeException(nameof(amount));
@@ -38,7 +35,7 @@ public class PruneService : INService
{ {
_logService.AddDeleteIgnore(x.Id); _logService.AddDeleteIgnore(x.Id);
if (DateTime.UtcNow - x.CreatedAt < twoWeeks) if (DateTime.UtcNow - x.CreatedAt < _twoWeeks)
bulkDeletable.Add(x); bulkDeletable.Add(x);
else else
singleDeletable.Add(x); singleDeletable.Add(x);

View File

@@ -135,9 +135,7 @@ public class RoleCommandsService : INService
} }
public bool Get(ulong id, out IndexedCollection<ReactionRoleMessage> rrs) public bool Get(ulong id, out IndexedCollection<ReactionRoleMessage> rrs)
{ => _models.TryGetValue(id, out rrs);
return _models.TryGetValue(id, out rrs);
}
public bool Add(ulong id, ReactionRoleMessage rrm) public bool Add(ulong id, ReactionRoleMessage rrm)
{ {

View File

@@ -27,9 +27,7 @@ public class SelfAssignedRolesService : INService
} }
public SelfAssignedRolesService(DbService db) public SelfAssignedRolesService(DbService db)
{ => _db = db;
_db = db;
}
public bool AddNew(ulong guildId, IRole role, int group) public bool AddNew(ulong guildId, IRole role, int group)
{ {

View File

@@ -123,12 +123,10 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
} }
private Timer TimerFromAutoCommand(AutoCommand x) private Timer TimerFromAutoCommand(AutoCommand x)
{ => new(async obj => await ExecuteCommand((AutoCommand) obj).ConfigureAwait(false),
return new(async obj => await ExecuteCommand((AutoCommand) obj).ConfigureAwait(false),
x, x,
x.Interval * 1000, x.Interval * 1000,
x.Interval * 1000); x.Interval * 1000);
}
private async Task ExecuteCommand(AutoCommand cmd) private async Task ExecuteCommand(AutoCommand cmd)
{ {
@@ -366,8 +364,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
} }
private void HandleStatusChanges() private void HandleStatusChanges()
{ => _pubSub.Sub(_activitySetKey, async data =>
_pubSub.Sub(_activitySetKey, async data =>
{ {
try try
{ {
@@ -378,7 +375,6 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
Log.Warning(ex, "Error setting activity"); Log.Warning(ex, "Error setting activity");
} }
}); });
}
public Task SetGameAsync(string game, ActivityType type) public Task SetGameAsync(string game, ActivityType type)
=> _pubSub.Pub(_activitySetKey, new() {Name = game, Link = null, Type = type}); => _pubSub.Pub(_activitySetKey, new() {Name = game, Link = null, Type = type});

View File

@@ -300,7 +300,7 @@ WHERE GuildId={guildId}
public bool WarnPunish(ulong guildId, int number, PunishmentAction punish, StoopidTime time, IRole role = null) public bool WarnPunish(ulong guildId, int number, PunishmentAction punish, StoopidTime time, IRole role = null)
{ {
// these 3 don't make sense with time // these 3 don't make sense with time
if ((punish == PunishmentAction.Softban || punish == PunishmentAction.Kick || punish == PunishmentAction.RemoveRoles) && time != null) if (punish is PunishmentAction.Softban or PunishmentAction.Kick or PunishmentAction.RemoveRoles && time != null)
return false; return false;
if (number <= 0 || (time != null && time.Time > TimeSpan.FromDays(49))) if (number <= 0 || (time != null && time.Time > TimeSpan.FromDays(49)))
return false; return false;
@@ -427,8 +427,7 @@ WHERE GuildId={guildId}
public SmartText GetBanUserDmEmbed(ICommandContext context, IGuildUser target, string defaultMessage, public SmartText GetBanUserDmEmbed(ICommandContext context, IGuildUser target, string defaultMessage,
string banReason, TimeSpan? duration) string banReason, TimeSpan? duration)
{ => GetBanUserDmEmbed(
return GetBanUserDmEmbed(
(DiscordSocketClient) context.Client, (DiscordSocketClient) context.Client,
(SocketGuild) context.Guild, (SocketGuild) context.Guild,
(IGuildUser) context.User, (IGuildUser) context.User,
@@ -436,7 +435,6 @@ WHERE GuildId={guildId}
defaultMessage, defaultMessage,
banReason, banReason,
duration); duration);
}
public SmartText GetBanUserDmEmbed(DiscordSocketClient client, SocketGuild guild, public SmartText GetBanUserDmEmbed(DiscordSocketClient client, SocketGuild guild,
IGuildUser moderator, IGuildUser target, string defaultMessage, string banReason, TimeSpan? duration) IGuildUser moderator, IGuildUser target, string defaultMessage, string banReason, TimeSpan? duration)

View File

@@ -13,7 +13,7 @@ public partial class Administration
{ {
page--; page--;
if (page < 0 || page > 20) if (page is < 0 or > 20)
return; return;
var timezones = TimeZoneInfo.GetSystemTimeZones() var timezones = TimeZoneInfo.GetSystemTimeZones()
@@ -56,9 +56,7 @@ public partial class Administration
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task Timezone() public async Task Timezone()
{ => await ReplyConfirmLocalizedAsync(strs.timezone_guild(_service.GetTimeZoneOrUtc(ctx.Guild.Id))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.timezone_guild(_service.GetTimeZoneOrUtc(ctx.Guild.Id))).ConfigureAwait(false);
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]

View File

@@ -144,7 +144,7 @@ public partial class Administration
[Priority(2)] [Priority(2)]
public async Task WarnExpire(int days, params string[] args) public async Task WarnExpire(int days, params string[] args)
{ {
if (days < 0 || days > 366) if (days is < 0 or > 366)
return; return;
var opts = OptionsParser.ParseFrom<WarnExpireOptions>(args); var opts = OptionsParser.ParseFrom<WarnExpireOptions>(args);

View File

@@ -95,7 +95,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
+ (string.IsNullOrWhiteSpace(cr.Reactions) + (string.IsNullOrWhiteSpace(cr.Reactions)
? string.Empty ? string.Empty
: " // " + string.Join(" ", cr.GetReactions()))) : " // " + string.Join(" ", cr.GetReactions())))
.JoinWith('\n'); .Join('\n');
return _eb.Create().WithOkColor() return _eb.Create().WithOkColor()
.WithTitle(GetText(strs.custom_reactions)) .WithTitle(GetText(strs.custom_reactions))

View File

@@ -33,8 +33,8 @@ public static class CustomReactionExtensions
var rep = new ReplacementBuilder() var rep = new ReplacementBuilder()
.WithDefault(ctx.Author, ctx.Channel, (ctx.Channel as ITextChannel)?.Guild as SocketGuild, client) .WithDefault(ctx.Author, ctx.Channel, (ctx.Channel as ITextChannel)?.Guild as SocketGuild, client)
.WithOverride("%target%", () => canMentionEveryone .WithOverride("%target%", () => canMentionEveryone
? ctx.Content.Substring(substringIndex).Trim() ? ctx.Content[substringIndex..].Trim()
: ctx.Content.Substring(substringIndex).Trim().SanitizeMentions(true)) : ctx.Content[substringIndex..].Trim().SanitizeMentions(true))
.Build(); .Build();
var text = SmartText.CreateFrom(cr.Response); var text = SmartText.CreateFrom(cr.Response);
@@ -69,11 +69,7 @@ public static class CustomReactionExtensions
private static bool isValidWordDivider(this in ReadOnlySpan<char> str, int index) private static bool isValidWordDivider(this in ReadOnlySpan<char> str, int index)
{ {
var ch = str[index]; var ch = str[index];
if (ch is >= 'a' and <= 'z') if (ch is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or >= '1' and <= '9')
return false;
if (ch is >= 'A' and <= 'Z')
return false;
if (ch is >= '1' and <= '9')
return false; return false;
return true; return true;

View File

@@ -713,7 +713,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
{ {
GuildId = guildId, GuildId = guildId,
Response = cr.Res, Response = cr.Res,
Reactions = cr.React?.JoinWith("@@@"), Reactions = cr.React?.Join("@@@"),
Trigger = trigger, Trigger = trigger,
AllowTarget = cr.At, AllowTarget = cr.At,
ContainsAnywhere = cr.Ca, ContainsAnywhere = cr.Ca,

View File

@@ -89,7 +89,7 @@ public partial class Gambling
dealerIcon = "🏁 "; dealerIcon = "🏁 ";
} }
var cStr = string.Concat(c.Select(x => x.Substring(0, x.Length - 1) + " ")); var cStr = string.Concat(c.Select(x => x[..^1] + " "));
cStr += "\n" + string.Concat(c.Select(x => x.Last() + " ")); cStr += "\n" + string.Concat(c.Select(x => x.Last() + " "));
var embed = _eb.Create() var embed = _eb.Create()
.WithOkColor() .WithOkColor()
@@ -104,7 +104,7 @@ public partial class Gambling
foreach (var p in bj.Players) foreach (var p in bj.Players)
{ {
c = p.Cards.Select(x => x.GetEmojiString()); c = p.Cards.Select(x => x.GetEmojiString());
cStr = "-\t" + string.Concat(c.Select(x => x.Substring(0, x.Length - 1) + " ")); cStr = "-\t" + string.Concat(c.Select(x => x[..^1] + " "));
cStr += "\n-\t" + string.Concat(c.Select(x => x.Last() + " ")); cStr += "\n-\t" + string.Concat(c.Select(x => x.Last() + " "));
var full = $"{p.DiscordUser.ToString().TrimTo(20)} | Bet: {p.Bet} | Value: {p.GetHandValue()}"; var full = $"{p.DiscordUser.ToString().TrimTo(20)} | Bet: {p.Bet} | Value: {p.GetHandValue()}";
if (bj.State == Blackjack.GameState.Ended) if (bj.State == Blackjack.GameState.Ended)

View File

@@ -18,14 +18,10 @@ public class AnimalRacingUser
} }
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is AnimalRacingUser x
return obj is AnimalRacingUser x
? x.UserId == this.UserId ? x.UserId == this.UserId
: false; : false;
}
public override int GetHashCode() public override int GetHashCode()
{ => this.UserId.GetHashCode();
return this.UserId.GetHashCode();
}
} }

View File

@@ -9,7 +9,7 @@ public class RaceOptions : INadekoCommandOptions
public void NormalizeOptions() public void NormalizeOptions()
{ {
if (this.StartTime < 10 || this.StartTime > 120) if (this.StartTime is < 10 or > 120)
this.StartTime = 20; this.StartTime = 20;
} }
} }

View File

@@ -203,7 +203,7 @@ public class Blackjack
{ {
foreach (var usr in Players) foreach (var usr in Players)
{ {
if (usr.State == User.UserState.Stand || usr.State == User.UserState.Blackjack) if (usr.State is User.UserState.Stand or User.UserState.Blackjack)
usr.State = User.UserState.Won; usr.State = User.UserState.Won;
else else
usr.State = User.UserState.Lost; usr.State = User.UserState.Lost;
@@ -226,7 +226,7 @@ public class Blackjack
foreach (var usr in Players) foreach (var usr in Players)
{ {
if (usr.State == User.UserState.Won || usr.State == User.UserState.Blackjack) if (usr.State is User.UserState.Won or User.UserState.Blackjack)
{ {
await _cs.AddAsync(usr.DiscordUser.Id, "BlackJack-win", usr.Bet * 2, gamble: true).ConfigureAwait(false); await _cs.AddAsync(usr.DiscordUser.Id, "BlackJack-win", usr.Bet * 2, gamble: true).ConfigureAwait(false);
} }

View File

@@ -20,9 +20,7 @@ public abstract class Player
} }
public int GetRawHandValue() public int GetRawHandValue()
{ => Cards.Sum(x => x.Number == 1 ? 11 : x.Number >= 10 ? 10 : x.Number);
return Cards.Sum(x => x.Number == 1 ? 11 : x.Number >= 10 ? 10 : x.Number);
}
} }
public class Dealer : Player public class Dealer : Player

View File

@@ -13,16 +13,12 @@ public class CurrencyRaffleGame
public long Amount { get; set; } public long Amount { get; set; }
public override int GetHashCode() public override int GetHashCode()
{ => DiscordUser.GetHashCode();
return DiscordUser.GetHashCode();
}
public override bool Equals(object obj) public override bool Equals(object obj)
{ => obj is User u
return obj is User u
? u.DiscordUser == DiscordUser ? u.DiscordUser == DiscordUser
: false; : false;
}
} }
private readonly HashSet<User> _users = new(); private readonly HashSet<User> _users = new();
@@ -30,9 +26,7 @@ public class CurrencyRaffleGame
public Type GameType { get; } public Type GameType { get; }
public CurrencyRaffleGame(Type type) public CurrencyRaffleGame(Type type)
{ => GameType = type;
GameType = type;
}
public bool AddUser(IUser usr, long amount) public bool AddUser(IUser usr, long amount)
{ {

View File

@@ -166,13 +166,11 @@ public class Deck
/// Creates a new instance of the BlackJackGame, this allows you to create multiple games running at one time. /// Creates a new instance of the BlackJackGame, this allows you to create multiple games running at one time.
/// </summary> /// </summary>
public Deck() public Deck()
{ => RefillPool();
RefillPool();
}
static Deck() static Deck()
{ => InitHandValues();
InitHandValues();
}
/// <summary> /// <summary>
/// Restart the game of blackjack. It will only refill the pool for now. Probably wont be used, unless you want to have only 1 bjg running at one time, /// Restart the game of blackjack. It will only refill the pool for now. Probably wont be used, unless you want to have only 1 bjg running at one time,
/// then you will restart the same game every time. /// then you will restart the same game every time.

View File

@@ -1,5 +1,4 @@
using NadekoBot.Common.Collections; using NadekoBot.Services.Database.Models;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Gambling.Common.Events; namespace NadekoBot.Modules.Gambling.Common.Events;
@@ -115,9 +114,7 @@ public class GameStatusEvent : ICurrencyEvent
} }
private IEmbedBuilder GetEmbed(long pot) private IEmbedBuilder GetEmbed(long pot)
{ => _embedFunc(CurrencyEvent.Type.GameStatus, _opts, pot);
return _embedFunc(CurrencyEvent.Type.GameStatus, _opts, pot);
}
private async Task OnMessageDeleted(Cacheable<IMessage, ulong> msg, Cacheable<IMessageChannel, ulong> cacheable) private async Task OnMessageDeleted(Cacheable<IMessage, ulong> msg, Cacheable<IMessageChannel, ulong> cacheable)
{ {

View File

@@ -1,5 +1,4 @@
using NadekoBot.Common.Collections; using NadekoBot.Services.Database.Models;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Gambling.Common.Events; namespace NadekoBot.Modules.Gambling.Common.Events;
@@ -118,9 +117,7 @@ public class ReactionEvent : ICurrencyEvent
} }
private IEmbedBuilder GetEmbed(long pot) private IEmbedBuilder GetEmbed(long pot)
{ => _embedFunc(CurrencyEvent.Type.Reaction, _opts, pot);
return _embedFunc(CurrencyEvent.Type.Reaction, _opts, pot);
}
private async Task OnMessageDeleted(Cacheable<IMessage, ulong> msg, Cacheable<IMessageChannel, ulong> cacheable) private async Task OnMessageDeleted(Cacheable<IMessage, ulong> msg, Cacheable<IMessageChannel, ulong> cacheable)
{ {

View File

@@ -105,14 +105,12 @@ Doesn't have to be ordered.")]
public BetRollPair[] Pairs { get; set; } = Array.Empty<BetRollPair>(); public BetRollPair[] Pairs { get; set; } = Array.Empty<BetRollPair>();
public BetRollConfig() public BetRollConfig()
{ => Pairs = new BetRollPair[]
Pairs = new BetRollPair[]
{ {
new() { WhenAbove = 99, MultiplyBy = 10 }, new() { WhenAbove = 99, MultiplyBy = 10 },
new() { WhenAbove = 90, MultiplyBy = 4 }, new() { WhenAbove = 90, MultiplyBy = 4 },
new() { WhenAbove = 66, MultiplyBy = 2 } new() { WhenAbove = 66, MultiplyBy = 2 }
}; };
}
} }
[Cloneable] [Cloneable]
@@ -163,8 +161,7 @@ public partial class WheelOfFortuneSettings
public decimal[] Multipliers { get; set; } public decimal[] Multipliers { get; set; }
public WheelOfFortuneSettings() public WheelOfFortuneSettings()
{ => Multipliers = new decimal[]
Multipliers = new decimal[]
{ {
1.7M, 1.7M,
1.5M, 1.5M,
@@ -175,7 +172,6 @@ public partial class WheelOfFortuneSettings
1.2M, 1.2M,
2.4M, 2.4M,
}; };
}
} }
[Cloneable] [Cloneable]
@@ -191,8 +187,7 @@ If negative is true, gift will instead reduce waifu value.")]
public List<WaifuItemModel> Items { get; set; } = new(); public List<WaifuItemModel> Items { get; set; } = new();
public WaifuConfig() public WaifuConfig()
{ => Items = new()
Items = new()
{ {
new("🥔", 5, "Potato"), new("🥔", 5, "Potato"),
new("🍪", 10, "Cookie"), new("🍪", 10, "Cookie"),
@@ -231,7 +226,6 @@ If negative is true, gift will instead reduce waifu value.")]
new("🚀", 30000, "Spaceship"), new("🚀", 30000, "Spaceship"),
new("🌕", 50000, "Moon") new("🌕", 50000, "Moon")
}; };
}
} }
[Cloneable] [Cloneable]

View File

@@ -10,9 +10,7 @@ public abstract class GamblingModule<TService> : NadekoModule<TService>
protected string CurrencyName => _config.Currency.Name; protected string CurrencyName => _config.Currency.Name;
protected GamblingModule(GamblingConfigService gambService) protected GamblingModule(GamblingConfigService gambService)
{ => _lazyConfig = new(() => gambService.Data);
_lazyConfig = new(() => gambService.Data);
}
private async Task<bool> InternalCheckBet(long amount) private async Task<bool> InternalCheckBet(long amount)
{ {

View File

@@ -151,14 +151,14 @@ public sealed class Connect4Game : IDisposable
try try
{ {
inputCol -= 1; inputCol -= 1;
if (CurrentPhase == Phase.Ended || CurrentPhase == Phase.Joining) if (CurrentPhase is Phase.Ended or Phase.Joining)
return false; return false;
if (!((_players[0].Value.UserId == userId && CurrentPhase == Phase.P1Move) if (!((_players[0].Value.UserId == userId && CurrentPhase == Phase.P1Move)
|| (_players[1].Value.UserId == userId && CurrentPhase == Phase.P2Move))) || (_players[1].Value.UserId == userId && CurrentPhase == Phase.P2Move)))
return false; return false;
if (inputCol < 0 || inputCol > NumberOfColumns) //invalid input if (inputCol is < 0 or > NumberOfColumns) //invalid input
return false; return false;
if (IsColumnFull(inputCol)) //can't play there event? if (IsColumnFull(inputCol)) //can't play there event?
@@ -259,9 +259,9 @@ public sealed class Connect4Game : IDisposable
var curCol = col - i; var curCol = col - i;
//check if current values are in range //check if current values are in range
if (curRow >= NumberOfRows || curRow < 0) if (curRow is >= NumberOfRows or < 0)
break; break;
if (curCol < 0 || curCol >= NumberOfColumns) if (curCol is < 0 or >= NumberOfColumns)
break; break;
var cur = _gameState[curRow + (curCol * NumberOfRows)]; var cur = _gameState[curRow + (curCol * NumberOfRows)];
@@ -286,9 +286,9 @@ public sealed class Connect4Game : IDisposable
var curCol = col + i; var curCol = col + i;
//check if current values are in range //check if current values are in range
if (curRow >= NumberOfRows || curRow < 0) if (curRow is >= NumberOfRows or < 0)
break; break;
if (curCol < 0 || curCol >= NumberOfColumns) if (curCol is < 0 or >= NumberOfColumns)
break; break;
var cur = _gameState[curRow + (curCol * NumberOfRows)]; var cur = _gameState[curRow + (curCol * NumberOfRows)];
@@ -328,9 +328,7 @@ public sealed class Connect4Game : IDisposable
} }
private void ResetTimer() private void ResetTimer()
{ => _playerTimeoutTimer.Change(TimeSpan.FromSeconds(_options.TurnTimer), TimeSpan.FromSeconds(_options.TurnTimer));
_playerTimeoutTimer.Change(TimeSpan.FromSeconds(_options.TurnTimer), TimeSpan.FromSeconds(_options.TurnTimer));
}
private void EndGame(Result result, ulong? winId) private void EndGame(Result result, ulong? winId)
{ {
@@ -378,7 +376,7 @@ public sealed class Connect4Game : IDisposable
{ {
public void NormalizeOptions() public void NormalizeOptions()
{ {
if (TurnTimer < 5 || TurnTimer > 60) if (TurnTimer is < 5 or > 60)
TurnTimer = 15; TurnTimer = 15;
if (Bet < 0) if (Bet < 0)

View File

@@ -86,8 +86,7 @@ public partial class Gambling
try { await arg.DeleteAsync().ConfigureAwait(false); } catch { } try { await arg.DeleteAsync().ConfigureAwait(false); } catch { }
else else
{ {
if (game.CurrentPhase == Connect4Game.Phase.Joining if (game.CurrentPhase is Connect4Game.Phase.Joining or Connect4Game.Phase.Ended)
|| game.CurrentPhase == Connect4Game.Phase.Ended)
{ {
return; return;
} }
@@ -145,7 +144,7 @@ public partial class Gambling
get => _repostCounter; get => _repostCounter;
set set
{ {
if (value < 0 || value > 7) if (value is < 0 or > 7)
_repostCounter = 0; _repostCounter = 0;
else _repostCounter = value; else _repostCounter = value;
} }
@@ -169,8 +168,7 @@ public partial class Gambling
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
if (game.CurrentPhase == Connect4Game.Phase.P1Move || if (game.CurrentPhase is Connect4Game.Phase.P1Move or Connect4Game.Phase.P2Move)
game.CurrentPhase == Connect4Game.Phase.P2Move)
sb.AppendLine(GetText(strs.connect4_player_to_move(Format.Bold(game.CurrentPlayer.Username)))); sb.AppendLine(GetText(strs.connect4_player_to_move(Format.Bold(game.CurrentPlayer.Username))));
for (var i = Connect4Game.NumberOfRows; i > 0; i--) for (var i = Connect4Game.NumberOfRows; i > 0; i--)

View File

@@ -32,8 +32,7 @@ public partial class Gambling
} }
private IEmbedBuilder GetEmbed(CurrencyEvent.Type type, EventOptions opts, long currentPot) private IEmbedBuilder GetEmbed(CurrencyEvent.Type type, EventOptions opts, long currentPot)
{ => type switch
return type switch
{ {
CurrencyEvent.Type.Reaction => _eb.Create() CurrencyEvent.Type.Reaction => _eb.Create()
.WithOkColor() .WithOkColor()
@@ -47,7 +46,6 @@ public partial class Gambling
.WithFooter(GetText(strs.event_duration_footer(opts.Hours))), .WithFooter(GetText(strs.event_duration_footer(opts.Hours))),
_ => throw new ArgumentOutOfRangeException(nameof(type)) _ => throw new ArgumentOutOfRangeException(nameof(type))
}; };
}
private string GetReactionDescription(long amount, long potSize) private string GetReactionDescription(long amount, long potSize)
{ {

View File

@@ -17,9 +17,7 @@ public partial class Gambling
private readonly IImageCache _images; private readonly IImageCache _images;
public DiceRollCommands(IDataCache data) public DiceRollCommands(IDataCache data)
{ => _images = data.LocalImages;
_images = data.LocalImages;
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
public async Task Roll() public async Task Roll()
@@ -42,35 +40,27 @@ public partial class Gambling
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[Priority(1)] [Priority(1)]
public async Task Roll(int num) public async Task Roll(int num)
{ => await InternalRoll(num, true).ConfigureAwait(false);
await InternalRoll(num, true).ConfigureAwait(false);
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[Priority(1)] [Priority(1)]
public async Task Rolluo(int num = 1) public async Task Rolluo(int num = 1)
{ => await InternalRoll(num, false).ConfigureAwait(false);
await InternalRoll(num, false).ConfigureAwait(false);
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[Priority(0)] [Priority(0)]
public async Task Roll(string arg) public async Task Roll(string arg)
{ => await InternallDndRoll(arg, true).ConfigureAwait(false);
await InternallDndRoll(arg, true).ConfigureAwait(false);
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[Priority(0)] [Priority(0)]
public async Task Rolluo(string arg) public async Task Rolluo(string arg)
{ => await InternallDndRoll(arg, false).ConfigureAwait(false);
await InternallDndRoll(arg, false).ConfigureAwait(false);
}
private async Task InternalRoll(int num, bool ordered) private async Task InternalRoll(int num, bool ordered)
{ {
if (num < 1 || num > 30) if (num is < 1 or > 30)
{ {
await ReplyErrorLocalizedAsync(strs.dice_invalid_number(1, 30)); await ReplyErrorLocalizedAsync(strs.dice_invalid_number(1, 30));
return; return;
@@ -201,7 +191,7 @@ public partial class Gambling
private Image<Rgba32> GetDice(int num) private Image<Rgba32> GetDice(int num)
{ {
if (num < 0 || num > 10) if (num is < 0 or > 10)
throw new ArgumentOutOfRangeException(nameof(num)); throw new ArgumentOutOfRangeException(nameof(num));
if (num == 10) if (num == 10)

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