dev: Using collection expressions, no functional change

This commit is contained in:
Kwoth
2024-05-13 14:54:24 +00:00
parent 52438f45e1
commit 9406a9cc34
38 changed files with 173 additions and 142 deletions

View File

@@ -319,13 +319,13 @@ public class GreetService : INService, IReadyExecutor
// if there are no embeds, add an embed with the footer
smartText = seta with
{
Embeds = new[]
{
Embeds =
[
new SmartEmbedArrayElementText()
{
Footer = CreateFooterSource(user)
}
}
]
};
}
else

View File

@@ -305,10 +305,7 @@ public sealed class ReactionRolesService : IReadyExecutor, INService, IReactionR
lock (_cacheLock)
{
_cache.AddOrUpdate(msg.Id,
_ => new()
{
obj
},
_ => [obj],
(_, list) =>
{
list.RemoveAll(x => x.Emote == emote);

View File

@@ -24,7 +24,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
private readonly GuildTimezoneService _tz;
private readonly IMemoryCache _memoryCache;
private readonly ConcurrentHashSet<ulong> _ignoreMessageIds = new();
private readonly ConcurrentHashSet<ulong> _ignoreMessageIds = [];
private readonly UserPunishService _punishService;
private readonly IMessageSenderService _sender;
@@ -115,10 +115,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
strs.user_status_change("👤" + Format.Bold(gu.Username),
Format.Bold(after.Status.ToString())));
PresenceUpdates.AddOrUpdate(logChannel,
new List<string>
{
str
},
[str],
(_, list) =>
{
list.Add(str);
@@ -130,10 +127,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
var str =
$"👾`{PrettyCurrentTime(gu.Guild)}`👤__**{gu.Username}**__ is now playing **{after.Activities.FirstOrDefault()?.Name ?? "-"}**.";
PresenceUpdates.AddOrUpdate(logChannel,
new List<string>
{
str
},
[str],
(_, list) =>
{
list.Add(str);
@@ -881,10 +875,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
if (!string.IsNullOrWhiteSpace(str))
{
PresenceUpdates.AddOrUpdate(logChannel,
new List<string>
{
str
},
[str],
(_, list) =>
{
list.Add(str);

View File

@@ -356,7 +356,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor
if (maybeGuildId is { } guildId)
{
newguildExpressions.AddOrUpdate(guildId,
new[] { expr },
[expr],
(_, old) =>
{
var newArray = old.ToArray();
@@ -389,7 +389,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor
expr.Trigger = expr.Trigger.Replace(MENTION_PH, _client.CurrentUser.Mention);
if (maybeGuildId is { } guildId)
newguildExpressions.AddOrUpdate(guildId, new[] { expr }, (_, old) => old.With(expr));
newguildExpressions.AddOrUpdate(guildId, [expr], (_, old) => old.With(expr));
else
return _pubSub.Pub(_gexprAddedKey, expr);

View File

@@ -12,9 +12,9 @@ public partial class Gambling
public partial class Connect4Commands : GamblingSubmodule<GamblingService>
{
private static readonly string[] _numbers =
{
[
":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:"
};
];
private int RepostCounter
{

View File

@@ -16,7 +16,7 @@ public partial class Gambling
private static readonly Regex _fudgeRegex = new(@"^(?<n1>\d+)d(?:F|f)$", RegexOptions.Compiled);
private static readonly char[] _fateRolls = { '-', ' ', '+' };
private static readonly char[] _fateRolls = ['-', ' ', '+'];
private readonly IImageCache _images;
public DiceRollCommands(IImageCache images)

View File

@@ -131,8 +131,8 @@ public partial class BetRollConfig
public BetRollPair[] Pairs { get; set; } = Array.Empty<BetRollPair>();
public BetRollConfig()
=> Pairs = new BetRollPair[]
{
=> Pairs =
[
new()
{
WhenAbove = 99,
@@ -148,7 +148,7 @@ public partial class BetRollConfig
WhenAbove = 66,
MultiplyBy = 2
}
};
];
}
[Cloneable]
@@ -207,7 +207,7 @@ public partial class LuckyLadderSettings
public decimal[] Multipliers { get; set; }
public LuckyLadderSettings()
=> Multipliers = new[] { 2.4M, 1.7M, 1.5M, 1.2M, 0.5M, 0.3M, 0.2M, 0.1M };
=> Multipliers = [2.4M, 1.7M, 1.5M, 1.2M, 0.5M, 0.3M, 0.2M, 0.1M];
}
[Cloneable]
@@ -228,11 +228,11 @@ public sealed partial class WaifuConfig
List of items available for gifting.
If negative is true, gift will instead reduce waifu value.
""")]
public List<WaifuItemModel> Items { get; set; } = new();
public List<WaifuItemModel> Items { get; set; } = [];
public WaifuConfig()
=> Items = new()
{
=> Items =
[
new("🥔", 5, "Potato"),
new("🍪", 10, "Cookie"),
new("🥖", 20, "Bread"),
@@ -269,7 +269,7 @@ public sealed partial class WaifuConfig
new("🚁", 20000, "Helicopter"),
new("🚀", 30000, "Spaceship"),
new("🌕", 50000, "Moon")
};
];
public class WaifuDecayConfig
{

View File

@@ -28,9 +28,9 @@ public static class WaifuExtensions
public static IEnumerable<WaifuLbResult> GetTop(this DbSet<WaifuInfo> waifus, int count, int skip = 0)
{
ArgumentOutOfRangeException.ThrowIfNegative(count);
if (count == 0)
return new List<WaifuLbResult>();
return [];
return waifus.Include(wi => wi.Waifu)
.Include(wi => wi.Affinity)

View File

@@ -42,7 +42,7 @@ public sealed class AcrophobiaGame : IDisposable
private readonly SemaphoreSlim _locker = new(1, 1);
private readonly NadekoRandom _rng;
private readonly HashSet<ulong> _usersWhoVoted = new();
private readonly HashSet<ulong> _usersWhoVoted = [];
public AcrophobiaGame(Options options)
{

View File

@@ -24,8 +24,8 @@ public sealed partial class GamesConfig : ICloneable<GamesConfig>
};
[Comment("List of responses for the .8ball command. A random one will be selected every time")]
public List<string> EightBallResponses { get; set; } = new()
{
public List<string> EightBallResponses { get; set; } =
[
"Most definitely yes.",
"For sure.",
"Totally!",
@@ -49,52 +49,59 @@ public sealed partial class GamesConfig : ICloneable<GamesConfig>
"Don't even think about it.",
"Definitely no.",
"NO - It may cause disease contraction!"
};
];
[Comment("List of animals which will be used for the animal race game (.race)")]
public List<RaceAnimal> RaceAnimals { get; set; } = new()
{
public List<RaceAnimal> RaceAnimals { get; set; } =
[
new()
{
Icon = "🐼",
Name = "Panda"
},
new()
{
Icon = "🐻",
Name = "Bear"
},
new()
{
Icon = "🐧",
Name = "Pengu"
},
new()
{
Icon = "🐨",
Name = "Koala"
},
new()
{
Icon = "🐬",
Name = "Dolphin"
},
new()
{
Icon = "🐞",
Name = "Ladybird"
},
new()
{
Icon = "🦀",
Name = "Crab"
},
new()
{
Icon = "🦄",
Name = "Unicorn"
}
};
];
[Comment(@"Which chatbot API should bot use.
'cleverbot' - bot will use Cleverbot API.

View File

@@ -33,8 +33,8 @@ public sealed class NunchiGame : IDisposable
private readonly SemaphoreSlim _locker = new(1, 1);
private HashSet<(ulong Id, string Name)> participants = new();
private readonly HashSet<(ulong Id, string Name)> _passed = new();
private HashSet<(ulong Id, string Name)> participants = [];
private readonly HashSet<(ulong Id, string Name)> _passed = [];
private Timer killTimer;
public NunchiGame(ulong creatorId, string creatorName)

View File

@@ -17,9 +17,9 @@ public class TicTacToe
private IGuildUser winner;
private readonly string[] _numbers =
{
[
":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:", ":nine:"
};
];
private IUserMessage previousMessage;
private Timer timeoutTimer;
@@ -42,7 +42,7 @@ public class TicTacToe
_options = options;
_sender = sender;
_users = new[] { firstUser, null };
_users = [firstUser, null];
_state = new int?[,] { { null, null, null }, { null, null, null }, { null, null, null } };
phase = Phase.Starting;

View File

@@ -9,13 +9,13 @@ public class TriviaQuestion
public const int MAX_STRING_LENGTH = 22;
//represents the min size to judge levDistance with
private static readonly HashSet<Tuple<int, int>> _strictness = new()
{
private static readonly HashSet<Tuple<int, int>> _strictness =
[
new(9, 0),
new(14, 1),
new(19, 2),
new(22, 3)
};
];
public string Category
=> _qModel.Category;

View File

@@ -249,13 +249,16 @@ public sealed partial class Help : NadekoModule<HelpService>
var succ = new HashSet<CommandInfo>();
if (opts.View != CommandsOptions.ViewType.All)
{
succ = new((await cmds.Select(async x =>
{
var pre = await x.CheckPreconditionsAsync(Context, _services);
return (Cmd: x, Succ: pre.IsSuccess);
})
.WhenAll()).Where(x => x.Succ)
.Select(x => x.Cmd));
succ =
[
..(await cmds.Select(async x =>
{
var pre = await x.CheckPreconditionsAsync(Context, _services);
return (Cmd: x, Succ: pre.IsSuccess);
})
.WhenAll()).Where(x => x.Succ)
.Select(x => x.Cmd)
];
if (opts.View == CommandsOptions.ViewType.Hide)
// if hidden is specified, completely remove these commands from the list

View File

@@ -6,17 +6,62 @@ public class MedusaeRepositoryService : IMedusaeRepositoryService, INService
{
// Simulate retrieving data from a database or API
await Task.Delay(100);
return new List<ModuleItem>
{
new ModuleItem { Name = "RSS Reader", Description = "Keep up to date with your favorite websites", Command = ".meinstall rss" },
new ModuleItem { Name = "Password Manager", Description = "Safely store and manage all your passwords", Command = ".meinstall passwordmanager" },
new ModuleItem { Name = "Browser Extension", Description = "Enhance your browsing experience with useful tools", Command = ".meinstall browserextension" },
new ModuleItem { Name = "Video Downloader", Description = "Download videos from popular websites", Command = ".meinstall videodownloader" },
new ModuleItem { Name = "Virtual Private Network", Description = "Securely browse the web and protect your privacy", Command = ".meinstall vpn" },
new ModuleItem { Name = "Ad Blocker", Description = "Block annoying ads and improve page load times", Command = ".meinstall adblocker" },
new ModuleItem { Name = "Cloud Storage", Description = "Store and share your files online", Command = ".meinstall cloudstorage" },
new ModuleItem { Name = "Social Media Manager", Description = "Manage all your social media accounts in one place", Command = ".meinstall socialmediamanager" },
new ModuleItem { Name = "Code Editor", Description = "Write and edit code online", Command = ".meinstall codeeditor" }
};
return
[
new()
{
Name = "RSS Reader",
Description = "Keep up to date with your favorite websites",
Command = ".meinstall rss"
},
new()
{
Name = "Password Manager",
Description = "Safely store and manage all your passwords",
Command = ".meinstall passwordmanager"
},
new()
{
Name = "Browser Extension",
Description = "Enhance your browsing experience with useful tools",
Command = ".meinstall browserextension"
},
new()
{
Name = "Video Downloader",
Description = "Download videos from popular websites",
Command = ".meinstall videodownloader"
},
new()
{
Name = "Virtual Private Network",
Description = "Securely browse the web and protect your privacy",
Command = ".meinstall vpn"
},
new()
{
Name = "Ad Blocker",
Description = "Block annoying ads and improve page load times",
Command = ".meinstall adblocker"
},
new()
{
Name = "Cloud Storage",
Description = "Store and share your files online",
Command = ".meinstall cloudstorage"
},
new()
{
Name = "Social Media Manager",
Description = "Manage all your social media accounts in one place",
Command = ".meinstall socialmediamanager"
},
new()
{
Name = "Code Editor",
Description = "Write and edit code online",
Command = ".meinstall codeeditor"
}
];
}
}

View File

@@ -28,11 +28,10 @@ public sealed class AyuVoiceStateService : INService
_dnetApiClient = prop.GetValue(_client, null);
_sendVoiceStateUpdateMethodInfo = _dnetApiClient.GetType()
.GetMethod("SendVoiceStateUpdateAsync",
new[]
{
typeof(ulong), typeof(ulong?), typeof(bool),
[
typeof(ulong), typeof(ulong?), typeof(bool),
typeof(bool), typeof(RequestOptions)
});
]);
_client.LeftGuild += ClientOnLeftGuild;
}
@@ -55,7 +54,7 @@ public sealed class AyuVoiceStateService : INService
bool isMuted = false)
// return _voiceStateUpdate(guildId, channelId, isDeafened, isMuted);
=> (Task)_sendVoiceStateUpdateMethodInfo.Invoke(_dnetApiClient,
new object[] { guildId, channelId, isMuted, isDeafened, null });
[guildId, channelId, isMuted, isDeafened, null]);
private Task SendLeaveVoiceChannelInternalAsync(ulong guildId)
=> InvokeSendVoiceStateUpdateAsync(guildId);

View File

@@ -11,9 +11,9 @@ public sealed partial class YtLoader : INService
private static readonly byte[] _ytResultJsonEnd = Encoding.UTF8.GetBytes(";<");
private static readonly string[] _durationFormats =
{
[
@"m\:ss", @"mm\:ss", @"h\:mm\:ss", @"hh\:mm\:ss", @"hhh\:mm\:ss"
};
];
private readonly IHttpClientFactory _httpFactory;

View File

@@ -7,9 +7,9 @@ namespace NadekoBot.Modules.Music;
public sealed class YtdlYoutubeResolver : IYoutubeResolver
{
private static readonly string[] _durationFormats =
{
[
"ss", "m\\:ss", "mm\\:ss", "h\\:mm\\:ss", "hh\\:mm\\:ss", "hhh\\:mm\\:ss"
};
];
private static readonly Regex _expiryRegex = new(@"(?:[\?\&]expire\=(?<timestamp>\d+))");

View File

@@ -162,7 +162,7 @@ public partial class Searches
.AddField(GetText(strs.episodes), animeData.TotalEpisodes.ToString(), true)
.AddField(GetText(strs.status), animeData.AiringStatus, true)
.AddField(GetText(strs.genres),
string.Join(",\n", animeData.Genres.Any() ? animeData.Genres : new[] { "none" }),
string.Join(",\n", animeData.Genres.Any() ? animeData.Genres : ["none"]),
true)
.WithFooter($"{GetText(strs.score)} {animeData.AverageScore} / 100");
await Response().Embed(embed).SendAsync();
@@ -194,7 +194,7 @@ public partial class Searches
.AddField(GetText(strs.chapters), mangaData.TotalChapters.ToString(), true)
.AddField(GetText(strs.status), mangaData.PublishingStatus, true)
.AddField(GetText(strs.genres),
string.Join(",\n", mangaData.Genres.Any() ? mangaData.Genres : new[] { "none" }),
string.Join(",\n", mangaData.Genres.Any() ? mangaData.Genres : ["none"]),
true)
.WithFooter($"{GetText(strs.score)} {mangaData.AverageScore} / 100");

View File

@@ -247,10 +247,7 @@ public class FeedsService : INService
foreach (var feed in gc.FeedSubs)
{
_subs.AddOrUpdate(feed.Url.ToLower(),
new List<FeedSub>
{
feed
},
[feed],
(_, old) =>
{
old.Add(feed);
@@ -275,7 +272,7 @@ public class FeedsService : INService
return false;
var toRemove = items[index];
_subs.AddOrUpdate(toRemove.Url.ToLower(),
new List<FeedSub>(),
[],
(_, old) =>
{
old.Remove(toRemove);

View File

@@ -23,8 +23,8 @@ public class SearchesService : INService
Birds
}
public List<WoWJoke> WowJokes { get; } = new();
public List<MagicItem> MagicItems { get; } = new();
public List<WoWJoke> WowJokes { get; } = [];
public List<MagicItem> MagicItems { get; } = [];
private readonly IHttpClientFactory _httpFactory;
private readonly IGoogleApiService _google;
private readonly IImageCache _imgs;
@@ -68,7 +68,7 @@ public class SearchesService : INService
_yomamaJokes = File.ReadAllLines("data/yomama.txt").Shuffle().ToList();
else
{
_yomamaJokes = new();
_yomamaJokes = [];
Log.Warning("data/yomama.txt is missing. .yomama command won't work");
}
}

View File

@@ -202,10 +202,7 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
_trackCounter[key].Add(info.GuildId);
else
{
_trackCounter[key] = new()
{
info.GuildId
};
_trackCounter[key] = [info.GuildId];
}
}
@@ -572,12 +569,12 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
{
if (map.TryGetValue(guildId, out var set))
return set;
return map[guildId] = new();
return map[guildId] = [];
}
_shardTrackedStreams[key] = new()
{
{ guildId, new() }
{ guildId, [] }
};
return _shardTrackedStreams[key][guildId];
}

View File

@@ -41,10 +41,7 @@ public class PicartoProvider : Provider
public override async Task<StreamData?> GetStreamDataAsync(string login)
{
var data = await GetStreamDataAsync(new List<string>
{
login
});
var data = await GetStreamDataAsync([login]);
return data.FirstOrDefault();
}
@@ -52,7 +49,7 @@ public class PicartoProvider : Provider
public override async Task<IReadOnlyCollection<StreamData>> GetStreamDataAsync(List<string> logins)
{
if (logins.Count == 0)
return new List<StreamData>();
return [];
using var http = _httpClientFactory.CreateClient();
var toReturn = new List<StreamData>();

View File

@@ -66,10 +66,7 @@ public sealed class TwitchHelixProvider : Provider
public override async Task<StreamData?> GetStreamDataAsync(string login)
{
var data = await GetStreamDataAsync(new List<string>
{
login
});
var data = await GetStreamDataAsync([login]);
return data.FirstOrDefault();
}
@@ -125,7 +122,7 @@ public sealed class TwitchHelixProvider : Provider
catch (Exception ex)
{
Log.Warning(ex, "Something went wrong retreiving {StreamPlatform} streams", Platform);
return new List<StreamData>();
return [];
}
}
@@ -163,7 +160,7 @@ public sealed class TwitchHelixProvider : Provider
catch (Exception ex)
{
Log.Warning(ex, "Something went wrong retreiving {StreamPlatform} streams", Platform);
return new List<StreamData>();
return [];
}
}

View File

@@ -58,13 +58,13 @@ public class ConverterService : INService, IReadyExecutor
var currencyRates = await GetCurrencyRates();
var baseType = new ConvertUnit
{
Triggers = new[] { currencyRates.Base },
Triggers = [currencyRates.Base],
Modifier = decimal.One,
UnitType = unitTypeString
};
var units = currencyRates.ConversionRates.Select(u => new ConvertUnit
{
Triggers = new[] { u.Key },
Triggers = [u.Key],
Modifier = u.Value,
UnitType = unitTypeString
})

View File

@@ -480,7 +480,7 @@ public partial class Utility : NadekoModule
try
{
if (tags.Length == 0)
tags = new[] { name };
tags = [name];
await ctx.Guild.CreateStickerAsync(
name,