- 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
end_of_line = crlf
@@ -109,3 +109,14 @@ resharper_unused_method_return_value_local_highlighting = suggestion
resharper_web_config_module_not_resolved_highlighting = warning
resharper_web_config_type_not_resolved_highlighting = warning
resharper_web_config_wrong_module_highlighting = warning
resharper_convert_to_using_declaration_highlighting = warning
# Expression-bodied members
csharp_style_expression_bodied_accessors = true:warning
csharp_style_expression_bodied_constructors = true:warning
csharp_style_expression_bodied_indexers = true:warning
csharp_style_expression_bodied_lambdas = true:warning
csharp_style_expression_bodied_local_functions = true:warning
csharp_style_expression_bodied_methods = true:warning
csharp_style_expression_bodied_operators = when_on_single_line:suggestion
csharp_style_expression_bodied_properties = true:warning

View File

@@ -1,5 +1,5 @@
# Remove the line below if you want to inherit .editorconfig settings from higher directories
root = true
# Remove the line below if you want to inherit .editorconfig settings from higher directories
# C# files
[*.cs]
@@ -20,7 +20,6 @@ insert_final_newline = false
# Organize usings
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = false
file_header_template = unset
# this. and Me. preferences
dotnet_style_qualification_for_event = false
@@ -51,8 +50,8 @@ dotnet_style_object_initializer = true
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_auto_properties = true:warning
dotnet_style_prefer_compound_assignment = true
dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
dotnet_style_prefer_conditional_expression_over_return = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = false:suggestion
dotnet_style_prefer_conditional_expression_over_return = false:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true
dotnet_style_prefer_inferred_tuple_names = true
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:error
@@ -65,13 +64,6 @@ dotnet_style_readonly_field = true:suggestion
# Parameter preferences
dotnet_code_quality_unused_parameters = all:warning
# Suppression preferences
dotnet_remove_unnecessary_suppression_exclusions = none
# New line preferences
dotnet_style_allow_multiple_blank_lines_experimental = false
dotnet_style_allow_statement_immediately_after_block_experimental = false
#### C# Coding Conventions ####
# var preferences
@@ -85,8 +77,8 @@ csharp_style_expression_bodied_constructors = when_on_single_line:suggestion
csharp_style_expression_bodied_indexers = true:suggestion
csharp_style_expression_bodied_lambdas = true:suggestion
csharp_style_expression_bodied_local_functions = true:suggestion
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
csharp_style_expression_bodied_operators = when_on_single_line:suggestion
csharp_style_expression_bodied_methods = when_on_single_line:warning
csharp_style_expression_bodied_operators = when_on_single_line:warning
csharp_style_expression_bodied_properties = true:suggestion
# Pattern matching preferences
@@ -236,6 +228,7 @@ dotnet_naming_rule.public_anything_should_be_pascal_case.style = pascal_case
# Symbol specifications
dotnet_naming_symbols.const_fields.required_modifiers = const
dotnet_naming_symbols.const_fields.applicable_kinds = field
dotnet_naming_symbols.class.applicable_kinds = class
dotnet_naming_symbols.class.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
@@ -316,13 +309,24 @@ dotnet_naming_style.camel_case.word_separator =
dotnet_naming_style.camel_case.capitalization = camel_case
# CA1822: Mark members as static
dotnet_diagnostic.CA1822.severity = suggestion
dotnet_diagnostic.ca1822.severity = suggestion
# IDE0004: Cast is redundant
dotnet_diagnostic.IDE0004.severity = error
dotnet_diagnostic.ide0004.severity = error
# IDE0058: Expression value is never used
dotnet_diagnostic.IDE0058.severity = none
dotnet_diagnostic.ide0058.severity = none
# IDE0011: Add braces to 'if'/'else' statement
dotnet_diagnostic.IDE0011.severity = none
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()
{
return Client.Guilds.Select(x => x.Id).ToList();
}
=> Client.Guilds.Select(x => x.Id).ToList();
private void AddServices()
{

View File

@@ -12,5 +12,6 @@ public class AsyncLazy<T> : Lazy<Task<T>>
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="")
: base(CommandNameLoadHelper.GetCommandNameFor(memberName))
{
this.MethodName = memberName.ToLowerInvariant();
}
=> this.MethodName = memberName.ToLowerInvariant();
public string MethodName { get; }
}

View File

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

View File

@@ -1,10 +1,9 @@
// License MIT
// Source: https://github.com/i3arnon/ConcurrentHashSet
using System.Collections;
using System.Diagnostics;
namespace NadekoBot.Common.Collections;
namespace System.Collections.Generic;
/// <summary>
/// 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 volatile Tables _tables;
private static int DefaultConcurrencyLevel => PlatformHelper.ProcessorCount;
private static int DefaultConcurrencyLevel
=> PlatformHelper.ProcessorCount;
/// <summary>
/// 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.
/// </summary>
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
/// 0.</exception>
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>
/// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference.</exception>
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.
/// </exception>
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 (comparer is null) throw new ArgumentNullException(nameof(comparer));
@@ -225,7 +237,10 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
/// </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference.</exception>
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>
/// <exception cref="T:System.OverflowException">The <see cref="ConcurrentHashSet{T}"/>
/// contains too many items.</exception>
public bool Add(T item) =>
AddInternal(item, _comparer.GetHashCode(item), true);
public bool Add(T item)
=> AddInternal(item, _comparer.GetHashCode(item), true);
/// <summary>
/// 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)
{
if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
if (hashcode == current.Hashcode &&
_comparer.Equals(current.Item, item))
{
return true;
}
current = current.Next;
}
@@ -330,7 +347,11 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
{
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])
{
@@ -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);
if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
if (hashcode == current.Hashcode &&
_comparer.Equals(current.Item, item))
{
if (previous is null)
{
@@ -360,6 +382,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
tables.CountPerLock[lockNo]--;
return true;
}
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
/// 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)
{
@@ -417,9 +443,11 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
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);
@@ -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)
{
@@ -450,7 +479,11 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
while (true)
{
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 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)
{
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;
}
previous = current;
}
@@ -525,7 +560,8 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
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;
lockNo = bucketNo % lockCount;
@@ -569,6 +605,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
{
_budget = int.MaxValue;
}
return;
}
@@ -624,7 +661,11 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
if (_growLockArray && tables.Locks.Length < MaxLockNumber)
{
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++)
{
newLocks[i] = new();
@@ -641,7 +682,11 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
while (current != null)
{
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]);
@@ -676,6 +721,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
if (this.TryRemove(elem))
removed++;
}
return removed;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -7,9 +7,7 @@ public sealed class GuildDateTimeTypeReader : NadekoTypeReader<GuildDateTime>
private readonly GuildTimezoneService _gts;
public GuildDateTimeTypeReader(GuildTimezoneService gts)
{
_gts = gts;
}
=> _gts = gts;
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input)
{

View File

@@ -5,9 +5,7 @@ public sealed class GuildTypeReader : NadekoTypeReader<IGuild>
private readonly DiscordSocketClient _client;
public GuildTypeReader(DiscordSocketClient client)
{
_client = client;
}
=> _client = client;
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 override Task<TypeReaderResult> ReadAsync(ICommandContext ctx, string input)
{
return Task.FromResult(TypeReaderResult.FromSuccess(SmartText.CreateFrom(input)));
}
=> Task.FromResult(TypeReaderResult.FromSuccess(SmartText.CreateFrom(input)));
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -6,9 +6,7 @@ namespace NadekoBot.Db;
public static class QuoteExtensions
{
public static IEnumerable<Quote> GetForGuild(this DbSet<Quote> quotes, ulong guildId)
{
return quotes.AsQueryable().Where(x => x.GuildId == guildId);
}
=> quotes.AsQueryable().Where(x => x.GuildId == guildId);
public static IEnumerable<Quote> GetGroup(this DbSet<Quote> quotes, ulong guildId, int page, OrderType order)
{
@@ -46,8 +44,5 @@ public static class QuoteExtensions
}
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)
{
return xps
=> xps
.AsQueryable()
.AsNoTracking()
.Where(x => x.GuildId == guildId)
@@ -35,29 +34,24 @@ public static class UserXpExtensions
.Skip(page * 9)
.Take(9)
.ToList();
}
public static List<UserXpStats> GetTopUserXps(this DbSet<UserXpStats> xps, ulong guildId, int count)
{
return xps
=> xps
.AsQueryable()
.AsNoTracking()
.Where(x => x.GuildId == guildId)
.OrderByDescending(x => x.Xp + x.AwardedXp)
.Take(count)
.ToList();
}
public static int GetUserGuildRanking(this DbSet<UserXpStats> xps, ulong userId, ulong guildId)
{
// @"SELECT COUNT(*) + 1
//FROM UserXpStats
//WHERE GuildId = @p1 AND ((Xp + AwardedXp) > (SELECT Xp + AwardedXp
// FROM UserXpStats
// WHERE UserId = @p2 AND GuildId = @p1
// LIMIT 1));";
return xps
=> xps
.AsQueryable()
.AsNoTracking()
.Where(x => x.GuildId == guildId && x.Xp + x.AwardedXp >
@@ -66,15 +60,10 @@ public static class UserXpExtensions
.Select(y => y.Xp + y.AwardedXp)
.FirstOrDefault())
.Count() + 1;
}
public static void ResetGuildUserXp(this DbSet<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)
{
xps.Delete(x => x.GuildId == guildId);
}
=> xps.Delete(x => x.GuildId == guildId);
}

View File

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

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)
{
await warnings.AsQueryable().Where(x => x.GuildId == guildId && x.UserId == userId)
=> await warnings.AsQueryable().Where(x => x.GuildId == guildId && x.UserId == userId)
.ForEachAsync(x =>
{
if (x.Forgiven != true)
@@ -43,10 +42,7 @@ public static class WarningExtensions
x.ForgivenBy = mod;
}
});
}
public static Warning[] GetForGuild(this DbSet<Warning> warnings, ulong id)
{
return warnings.AsQueryable().Where(x => x.GuildId == id).ToArray();
}
=> 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 bool Equals(object obj)
{
return obj is AntiSpamIgnore inst
=> obj is AntiSpamIgnore inst
? inst.ChannelId == ChannelId
: false;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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;
@@ -35,9 +34,7 @@ public class AntiAltStats
public int Counter => _counter;
public AntiAltStats(AntiAltSetting setting)
{
_setting = setting;
}
=> _setting = setting;
public void Increment() => Interlocked.Increment(ref _counter);

View File

@@ -42,11 +42,9 @@ public partial class Administration
[RequireContext(ContextType.Guild)]
[Priority(0)]
public async Task LanguageSet()
{
await ReplyConfirmLocalizedAsync(strs.lang_set_show(
=> await ReplyConfirmLocalizedAsync(strs.lang_set_show(
Format.Bold(_cultureInfo.ToString()),
Format.Bold(_cultureInfo.NativeName)));
}
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
@@ -113,14 +111,12 @@ public partial class Administration
[NadekoCommand, Aliases]
public async Task LanguagesList()
{
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
=> await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
.WithTitle(GetText(strs.lang_list))
.WithDescription(string.Join("\n",
supportedLocales.Select(x => $"{Format.Code(x.Key),-10} => {x.Value}")))).ConfigureAwait(false);
}
}
}
/* list of language codes for reference.
* taken from https://github.com/dotnet/coreclr/blob/ee5862c6a257e60e263537d975ab6c513179d47f/src/mscorlib/src/System/Globalization/CultureData.cs#L192
{ "029", "en-029" },

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -33,9 +33,7 @@ DELETE FROM Clubs;";
private readonly DbService _db;
public DangerousCommandsService(DbService db)
{
_db = db;
}
=> _db = db;
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;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -13,26 +13,20 @@ public class CurrencyRaffleGame
public long Amount { get; set; }
public override int GetHashCode()
{
return DiscordUser.GetHashCode();
}
=> DiscordUser.GetHashCode();
public override bool Equals(object obj)
{
return obj is User u
=> obj is User u
? u.DiscordUser == DiscordUser
: false;
}
}
private readonly HashSet<User> _users = new();
public IEnumerable<User> Users => _users;
public Type GameType { get; }
public CurrencyRaffleGame(Type type)
{
GameType = type;
}
=> GameType = type;
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.
/// </summary>
public Deck()
{
RefillPool();
}
=> RefillPool();
static Deck()
{
InitHandValues();
}
=> InitHandValues();
/// <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,
/// 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;
@@ -115,9 +114,7 @@ public class GameStatusEvent : ICurrencyEvent
}
private IEmbedBuilder GetEmbed(long pot)
{
return _embedFunc(CurrencyEvent.Type.GameStatus, _opts, pot);
}
=> _embedFunc(CurrencyEvent.Type.GameStatus, _opts, pot);
private async Task OnMessageDeleted(Cacheable<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;
@@ -118,9 +117,7 @@ public class ReactionEvent : ICurrencyEvent
}
private IEmbedBuilder GetEmbed(long pot)
{
return _embedFunc(CurrencyEvent.Type.Reaction, _opts, pot);
}
=> _embedFunc(CurrencyEvent.Type.Reaction, _opts, pot);
private async Task OnMessageDeleted(Cacheable<IMessage, ulong> msg, Cacheable<IMessageChannel, ulong> cacheable)
{

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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