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

@@ -80,10 +80,10 @@ public sealed class Bot : IBot
// _interactionService = new(Client.Rest); // _interactionService = new(Client.Rest);
Client.Log += Client_Log; Client.Log += Client_Log;
_loadedAssemblies = new[] _loadedAssemblies =
{ [
typeof(Bot).Assembly, // bot typeof(Bot).Assembly // bot
}; ];
} }

View File

@@ -7,19 +7,20 @@ namespace NadekoBot.Db;
public static class GuildConfigExtensions public static class GuildConfigExtensions
{ {
private static List<WarningPunishment> DefaultWarnPunishments private static List<WarningPunishment> DefaultWarnPunishments
=> new() =>
{ [
new() new()
{ {
Count = 3, Count = 3,
Punishment = PunishmentAction.Kick Punishment = PunishmentAction.Kick
}, },
new() new()
{ {
Count = 5, Count = 5,
Punishment = PunishmentAction.Ban Punishment = PunishmentAction.Ban
} }
}; ];
/// <summary> /// <summary>
/// Gets full stream role settings for the guild with the specified id. /// Gets full stream role settings for the guild with the specified id.

View File

@@ -33,10 +33,7 @@ public class Permissionv2 : DbEntity, IIndexed
}; };
public static List<Permissionv2> GetDefaultPermlist public static List<Permissionv2> GetDefaultPermlist
=> new() => [AllowAllPerm];
{
AllowAllPerm
};
} }
public enum PrimaryPermissionType public enum PrimaryPermissionType

View File

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

View File

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

View File

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

View File

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

View File

@@ -12,9 +12,9 @@ public partial class Gambling
public partial class Connect4Commands : GamblingSubmodule<GamblingService> public partial class Connect4Commands : GamblingSubmodule<GamblingService>
{ {
private static readonly string[] _numbers = private static readonly string[] _numbers =
{ [
":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:" ":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:"
}; ];
private int RepostCounter 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 Regex _fudgeRegex = new(@"^(?<n1>\d+)d(?:F|f)$", RegexOptions.Compiled);
private static readonly char[] _fateRolls = { '-', ' ', '+' }; private static readonly char[] _fateRolls = ['-', ' ', '+'];
private readonly IImageCache _images; private readonly IImageCache _images;
public DiceRollCommands(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 BetRollPair[] Pairs { get; set; } = Array.Empty<BetRollPair>();
public BetRollConfig() public BetRollConfig()
=> Pairs = new BetRollPair[] => Pairs =
{ [
new() new()
{ {
WhenAbove = 99, WhenAbove = 99,
@@ -148,7 +148,7 @@ public partial class BetRollConfig
WhenAbove = 66, WhenAbove = 66,
MultiplyBy = 2 MultiplyBy = 2
} }
}; ];
} }
[Cloneable] [Cloneable]
@@ -207,7 +207,7 @@ public partial class LuckyLadderSettings
public decimal[] Multipliers { get; set; } public decimal[] Multipliers { get; set; }
public LuckyLadderSettings() 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] [Cloneable]
@@ -228,11 +228,11 @@ public sealed partial class WaifuConfig
List of items available for gifting. List of items available for gifting.
If negative is true, gift will instead reduce waifu value. 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() public WaifuConfig()
=> Items = new() => Items =
{ [
new("🥔", 5, "Potato"), new("🥔", 5, "Potato"),
new("🍪", 10, "Cookie"), new("🍪", 10, "Cookie"),
new("🥖", 20, "Bread"), new("🥖", 20, "Bread"),
@@ -269,7 +269,7 @@ public sealed partial class WaifuConfig
new("🚁", 20000, "Helicopter"), new("🚁", 20000, "Helicopter"),
new("🚀", 30000, "Spaceship"), new("🚀", 30000, "Spaceship"),
new("🌕", 50000, "Moon") new("🌕", 50000, "Moon")
}; ];
public class WaifuDecayConfig public class WaifuDecayConfig
{ {

View File

@@ -30,7 +30,7 @@ public static class WaifuExtensions
ArgumentOutOfRangeException.ThrowIfNegative(count); ArgumentOutOfRangeException.ThrowIfNegative(count);
if (count == 0) if (count == 0)
return new List<WaifuLbResult>(); return [];
return waifus.Include(wi => wi.Waifu) return waifus.Include(wi => wi.Waifu)
.Include(wi => wi.Affinity) .Include(wi => wi.Affinity)

View File

@@ -42,7 +42,7 @@ public sealed class AcrophobiaGame : IDisposable
private readonly SemaphoreSlim _locker = new(1, 1); private readonly SemaphoreSlim _locker = new(1, 1);
private readonly NadekoRandom _rng; private readonly NadekoRandom _rng;
private readonly HashSet<ulong> _usersWhoVoted = new(); private readonly HashSet<ulong> _usersWhoVoted = [];
public AcrophobiaGame(Options options) 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")] [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.", "Most definitely yes.",
"For sure.", "For sure.",
"Totally!", "Totally!",
@@ -49,52 +49,59 @@ public sealed partial class GamesConfig : ICloneable<GamesConfig>
"Don't even think about it.", "Don't even think about it.",
"Definitely no.", "Definitely no.",
"NO - It may cause disease contraction!" "NO - It may cause disease contraction!"
}; ];
[Comment("List of animals which will be used for the animal race game (.race)")] [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() new()
{ {
Icon = "🐼", Icon = "🐼",
Name = "Panda" Name = "Panda"
}, },
new() new()
{ {
Icon = "🐻", Icon = "🐻",
Name = "Bear" Name = "Bear"
}, },
new() new()
{ {
Icon = "🐧", Icon = "🐧",
Name = "Pengu" Name = "Pengu"
}, },
new() new()
{ {
Icon = "🐨", Icon = "🐨",
Name = "Koala" Name = "Koala"
}, },
new() new()
{ {
Icon = "🐬", Icon = "🐬",
Name = "Dolphin" Name = "Dolphin"
}, },
new() new()
{ {
Icon = "🐞", Icon = "🐞",
Name = "Ladybird" Name = "Ladybird"
}, },
new() new()
{ {
Icon = "🦀", Icon = "🦀",
Name = "Crab" Name = "Crab"
}, },
new() new()
{ {
Icon = "🦄", Icon = "🦄",
Name = "Unicorn" Name = "Unicorn"
} }
}; ];
[Comment(@"Which chatbot API should bot use. [Comment(@"Which chatbot API should bot use.
'cleverbot' - bot will use Cleverbot API. '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 readonly SemaphoreSlim _locker = new(1, 1);
private HashSet<(ulong Id, string Name)> participants = new(); private HashSet<(ulong Id, string Name)> participants = [];
private readonly HashSet<(ulong Id, string Name)> _passed = new(); private readonly HashSet<(ulong Id, string Name)> _passed = [];
private Timer killTimer; private Timer killTimer;
public NunchiGame(ulong creatorId, string creatorName) public NunchiGame(ulong creatorId, string creatorName)

View File

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

View File

@@ -9,13 +9,13 @@ public class TriviaQuestion
public const int MAX_STRING_LENGTH = 22; public const int MAX_STRING_LENGTH = 22;
//represents the min size to judge levDistance with //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(9, 0),
new(14, 1), new(14, 1),
new(19, 2), new(19, 2),
new(22, 3) new(22, 3)
}; ];
public string Category public string Category
=> _qModel.Category; => _qModel.Category;

View File

@@ -249,13 +249,16 @@ public sealed partial class Help : NadekoModule<HelpService>
var succ = new HashSet<CommandInfo>(); var succ = new HashSet<CommandInfo>();
if (opts.View != CommandsOptions.ViewType.All) if (opts.View != CommandsOptions.ViewType.All)
{ {
succ = new((await cmds.Select(async x => succ =
[
..(await cmds.Select(async x =>
{ {
var pre = await x.CheckPreconditionsAsync(Context, _services); var pre = await x.CheckPreconditionsAsync(Context, _services);
return (Cmd: x, Succ: pre.IsSuccess); return (Cmd: x, Succ: pre.IsSuccess);
}) })
.WhenAll()).Where(x => x.Succ) .WhenAll()).Where(x => x.Succ)
.Select(x => x.Cmd)); .Select(x => x.Cmd)
];
if (opts.View == CommandsOptions.ViewType.Hide) if (opts.View == CommandsOptions.ViewType.Hide)
// if hidden is specified, completely remove these commands from the list // 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 // Simulate retrieving data from a database or API
await Task.Delay(100); await Task.Delay(100);
return new List<ModuleItem> return
[
new()
{ {
new ModuleItem { Name = "RSS Reader", Description = "Keep up to date with your favorite websites", Command = ".meinstall rss" }, Name = "RSS Reader",
new ModuleItem { Name = "Password Manager", Description = "Safely store and manage all your passwords", Command = ".meinstall passwordmanager" }, Description = "Keep up to date with your favorite websites",
new ModuleItem { Name = "Browser Extension", Description = "Enhance your browsing experience with useful tools", Command = ".meinstall browserextension" }, Command = ".meinstall rss"
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()
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" }, Name = "Password Manager",
new ModuleItem { Name = "Social Media Manager", Description = "Manage all your social media accounts in one place", Command = ".meinstall socialmediamanager" }, Description = "Safely store and manage all your passwords",
new ModuleItem { Name = "Code Editor", Description = "Write and edit code online", Command = ".meinstall codeeditor" } 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); _dnetApiClient = prop.GetValue(_client, null);
_sendVoiceStateUpdateMethodInfo = _dnetApiClient.GetType() _sendVoiceStateUpdateMethodInfo = _dnetApiClient.GetType()
.GetMethod("SendVoiceStateUpdateAsync", .GetMethod("SendVoiceStateUpdateAsync",
new[] [
{
typeof(ulong), typeof(ulong?), typeof(bool), typeof(ulong), typeof(ulong?), typeof(bool),
typeof(bool), typeof(RequestOptions) typeof(bool), typeof(RequestOptions)
}); ]);
_client.LeftGuild += ClientOnLeftGuild; _client.LeftGuild += ClientOnLeftGuild;
} }
@@ -55,7 +54,7 @@ public sealed class AyuVoiceStateService : INService
bool isMuted = false) bool isMuted = false)
// return _voiceStateUpdate(guildId, channelId, isDeafened, isMuted); // return _voiceStateUpdate(guildId, channelId, isDeafened, isMuted);
=> (Task)_sendVoiceStateUpdateMethodInfo.Invoke(_dnetApiClient, => (Task)_sendVoiceStateUpdateMethodInfo.Invoke(_dnetApiClient,
new object[] { guildId, channelId, isMuted, isDeafened, null }); [guildId, channelId, isMuted, isDeafened, null]);
private Task SendLeaveVoiceChannelInternalAsync(ulong guildId) private Task SendLeaveVoiceChannelInternalAsync(ulong guildId)
=> InvokeSendVoiceStateUpdateAsync(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 byte[] _ytResultJsonEnd = Encoding.UTF8.GetBytes(";<");
private static readonly string[] _durationFormats = private static readonly string[] _durationFormats =
{ [
@"m\:ss", @"mm\:ss", @"h\:mm\:ss", @"hh\:mm\:ss", @"hhh\:mm\:ss" @"m\:ss", @"mm\:ss", @"h\:mm\:ss", @"hh\:mm\:ss", @"hhh\:mm\:ss"
}; ];
private readonly IHttpClientFactory _httpFactory; private readonly IHttpClientFactory _httpFactory;

View File

@@ -7,9 +7,9 @@ namespace NadekoBot.Modules.Music;
public sealed class YtdlYoutubeResolver : IYoutubeResolver public sealed class YtdlYoutubeResolver : IYoutubeResolver
{ {
private static readonly string[] _durationFormats = private static readonly string[] _durationFormats =
{ [
"ss", "m\\:ss", "mm\\:ss", "h\\:mm\\:ss", "hh\\:mm\\:ss", "hhh\\:mm\\:ss" "ss", "m\\:ss", "mm\\:ss", "h\\:mm\\:ss", "hh\\:mm\\:ss", "hhh\\:mm\\:ss"
}; ];
private static readonly Regex _expiryRegex = new(@"(?:[\?\&]expire\=(?<timestamp>\d+))"); 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.episodes), animeData.TotalEpisodes.ToString(), true)
.AddField(GetText(strs.status), animeData.AiringStatus, true) .AddField(GetText(strs.status), animeData.AiringStatus, true)
.AddField(GetText(strs.genres), .AddField(GetText(strs.genres),
string.Join(",\n", animeData.Genres.Any() ? animeData.Genres : new[] { "none" }), string.Join(",\n", animeData.Genres.Any() ? animeData.Genres : ["none"]),
true) true)
.WithFooter($"{GetText(strs.score)} {animeData.AverageScore} / 100"); .WithFooter($"{GetText(strs.score)} {animeData.AverageScore} / 100");
await Response().Embed(embed).SendAsync(); await Response().Embed(embed).SendAsync();
@@ -194,7 +194,7 @@ public partial class Searches
.AddField(GetText(strs.chapters), mangaData.TotalChapters.ToString(), true) .AddField(GetText(strs.chapters), mangaData.TotalChapters.ToString(), true)
.AddField(GetText(strs.status), mangaData.PublishingStatus, true) .AddField(GetText(strs.status), mangaData.PublishingStatus, true)
.AddField(GetText(strs.genres), .AddField(GetText(strs.genres),
string.Join(",\n", mangaData.Genres.Any() ? mangaData.Genres : new[] { "none" }), string.Join(",\n", mangaData.Genres.Any() ? mangaData.Genres : ["none"]),
true) true)
.WithFooter($"{GetText(strs.score)} {mangaData.AverageScore} / 100"); .WithFooter($"{GetText(strs.score)} {mangaData.AverageScore} / 100");

View File

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

View File

@@ -23,8 +23,8 @@ public class SearchesService : INService
Birds Birds
} }
public List<WoWJoke> WowJokes { get; } = new(); public List<WoWJoke> WowJokes { get; } = [];
public List<MagicItem> MagicItems { get; } = new(); public List<MagicItem> MagicItems { get; } = [];
private readonly IHttpClientFactory _httpFactory; private readonly IHttpClientFactory _httpFactory;
private readonly IGoogleApiService _google; private readonly IGoogleApiService _google;
private readonly IImageCache _imgs; private readonly IImageCache _imgs;
@@ -68,7 +68,7 @@ public class SearchesService : INService
_yomamaJokes = File.ReadAllLines("data/yomama.txt").Shuffle().ToList(); _yomamaJokes = File.ReadAllLines("data/yomama.txt").Shuffle().ToList();
else else
{ {
_yomamaJokes = new(); _yomamaJokes = [];
Log.Warning("data/yomama.txt is missing. .yomama command won't work"); 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); _trackCounter[key].Add(info.GuildId);
else else
{ {
_trackCounter[key] = new() _trackCounter[key] = [info.GuildId];
{
info.GuildId
};
} }
} }
@@ -572,12 +569,12 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
{ {
if (map.TryGetValue(guildId, out var set)) if (map.TryGetValue(guildId, out var set))
return set; return set;
return map[guildId] = new(); return map[guildId] = [];
} }
_shardTrackedStreams[key] = new() _shardTrackedStreams[key] = new()
{ {
{ guildId, new() } { guildId, [] }
}; };
return _shardTrackedStreams[key][guildId]; return _shardTrackedStreams[key][guildId];
} }

View File

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

View File

@@ -66,10 +66,7 @@ public sealed class TwitchHelixProvider : Provider
public override async Task<StreamData?> GetStreamDataAsync(string login) public override async Task<StreamData?> GetStreamDataAsync(string login)
{ {
var data = await GetStreamDataAsync(new List<string> var data = await GetStreamDataAsync([login]);
{
login
});
return data.FirstOrDefault(); return data.FirstOrDefault();
} }
@@ -125,7 +122,7 @@ public sealed class TwitchHelixProvider : Provider
catch (Exception ex) catch (Exception ex)
{ {
Log.Warning(ex, "Something went wrong retreiving {StreamPlatform} streams", Platform); 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) catch (Exception ex)
{ {
Log.Warning(ex, "Something went wrong retreiving {StreamPlatform} streams", Platform); 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 currencyRates = await GetCurrencyRates();
var baseType = new ConvertUnit var baseType = new ConvertUnit
{ {
Triggers = new[] { currencyRates.Base }, Triggers = [currencyRates.Base],
Modifier = decimal.One, Modifier = decimal.One,
UnitType = unitTypeString UnitType = unitTypeString
}; };
var units = currencyRates.ConversionRates.Select(u => new ConvertUnit var units = currencyRates.ConversionRates.Select(u => new ConvertUnit
{ {
Triggers = new[] { u.Key }, Triggers = [u.Key],
Modifier = u.Value, Modifier = u.Value,
UnitType = unitTypeString UnitType = unitTypeString
}) })

View File

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

View File

@@ -112,7 +112,7 @@ public class Localization : ILocalization
{ {
Cmd = key, Cmd = key,
Desc = key, Desc = key,
Usage = new[] { key } Usage = [key]
}; };
} }

View File

@@ -8,13 +8,13 @@ namespace NadekoBot.Common;
public sealed class RedisBotCache : IBotCache public sealed class RedisBotCache : IBotCache
{ {
private static readonly Type[] _supportedTypes = new [] private static readonly Type[] _supportedTypes =
{ [
typeof(bool), typeof(int), typeof(uint), typeof(long), typeof(bool), typeof(int), typeof(uint), typeof(long),
typeof(ulong), typeof(float), typeof(double), typeof(ulong), typeof(float), typeof(double),
typeof(string), typeof(byte[]), typeof(ReadOnlyMemory<byte>), typeof(Memory<byte>), typeof(string), typeof(byte[]), typeof(ReadOnlyMemory<byte>), typeof(Memory<byte>),
typeof(RedisValue), typeof(RedisValue)
}; ];
private static readonly JsonSerializerOptions _opts = new() private static readonly JsonSerializerOptions _opts = new()
{ {

View File

@@ -6,10 +6,13 @@ namespace NadekoBot.Extensions;
public static class StringExtensions public static class StringExtensions
{ {
private static readonly HashSet<char> _lettersAndDigits = new(Enumerable.Range(48, 10) private static readonly HashSet<char> _lettersAndDigits =
[
..Enumerable.Range(48, 10)
.Concat(Enumerable.Range(65, 26)) .Concat(Enumerable.Range(65, 26))
.Concat(Enumerable.Range(97, 26)) .Concat(Enumerable.Range(97, 26))
.Select(x => (char)x)); .Select(x => (char)x)
];
private static readonly Regex _filterRegex = new(@"discord(?:\.gg|\.io|\.me|\.li|(?:app)?\.com\/invite)\/(\w+)", private static readonly Regex _filterRegex = new(@"discord(?:\.gg|\.io|\.me|\.li|(?:app)?\.com\/invite)\/(\w+)",
RegexOptions.Compiled | RegexOptions.IgnoreCase); RegexOptions.Compiled | RegexOptions.IgnoreCase);
@@ -43,7 +46,7 @@ public static class StringExtensions
public static string ToTitleCase(this string str) public static string ToTitleCase(this string str)
{ {
var tokens = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); var tokens = str.Split([" "], StringSplitOptions.RemoveEmptyEntries);
for (var i = 0; i < tokens.Length; i++) for (var i = 0; i < tokens.Length; i++)
{ {
var token = tokens[i]; var token = tokens[i];

View File

@@ -146,14 +146,14 @@ public sealed partial class BotConfig : ICloneable<BotConfig>
Prefix = "."; Prefix = ".";
RotateStatuses = false; RotateStatuses = false;
GroupGreets = false; GroupGreets = false;
DmHelpTextKeywords = new() DmHelpTextKeywords =
{ [
"help", "help",
"commands", "commands",
"cmds", "cmds",
"module", "module",
"can you do" "can you do"
}; ];
} }
// [Comment(@"Whether the prefix will be a suffix, or prefix. // [Comment(@"Whether the prefix will be a suffix, or prefix.
@@ -178,8 +178,8 @@ public sealed partial class BlockedConfig
public BlockedConfig() public BlockedConfig()
{ {
Modules = new(); Modules = [];
Commands = new(); Commands = [];
} }
} }

View File

@@ -259,10 +259,10 @@ public class Deck
} }
private readonly string[] _regIndicators = private readonly string[] _regIndicators =
{ [
"🇦", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:", ":nine:", ":keycap_ten:", "🇦", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:", ":nine:", ":keycap_ten:",
"🇯", "🇶", "🇰" "🇯", "🇶", "🇰"
}; ];
public Card(CardSuit s, int cardNum) public Card(CardSuit s, int cardNum)
{ {

View File

@@ -64,7 +64,7 @@ public sealed class MedusaNinjectIocModule : IIocModule, IDisposable
var assembly = typeof(JsonSerializerOptions).Assembly; var assembly = typeof(JsonSerializerOptions).Assembly;
var updateHandlerType = assembly.GetType("System.Text.Json.JsonSerializerOptionsUpdateHandler"); var updateHandlerType = assembly.GetType("System.Text.Json.JsonSerializerOptionsUpdateHandler");
var clearCacheMethod = updateHandlerType?.GetMethod("ClearCache", BindingFlags.Static | BindingFlags.Public); var clearCacheMethod = updateHandlerType?.GetMethod("ClearCache", BindingFlags.Static | BindingFlags.Public);
clearCacheMethod?.Invoke(null, new object?[] { null }); clearCacheMethod?.Invoke(null, [null]);
isLoaded = false; isLoaded = false;
} }

View File

@@ -140,7 +140,7 @@ public sealed class MedusaLoaderService : IMedusaLoaderService, IReadyExecutor,
=> alias.Equals(commandName, StringComparison.InvariantCultureIgnoreCase))) => alias.Equals(commandName, StringComparison.InvariantCultureIgnoreCase)))
?.OptionalStrings ?.OptionalStrings
.Args .Args
?? new[] { string.Empty }; ?? [string.Empty];
} }
public Task ReloadStrings() public Task ReloadStrings()
@@ -375,7 +375,7 @@ public sealed class MedusaLoaderService : IMedusaLoaderService, IReadyExecutor,
var targetType = parserType.BaseType!.GetGenericArguments()[0]; var targetType = parserType.BaseType!.GetGenericArguments()[0];
var typeReaderInstance = (TypeReader)Activator.CreateInstance( var typeReaderInstance = (TypeReader)Activator.CreateInstance(
typeof(ParamParserAdapter<>).MakeGenericType(targetType), typeof(ParamParserAdapter<>).MakeGenericType(targetType),
args: new[] { parserObj, strings, _cont })!; args: [parserObj, strings, _cont])!;
typeReaders.Add(targetType, typeReaderInstance); typeReaders.Add(targetType, typeReaderInstance);
} }
@@ -888,7 +888,7 @@ public sealed class MedusaLoaderService : IMedusaLoaderService, IReadyExecutor,
var cmdAttribute = method.GetCustomAttribute<cmdAttribute>(true)!; var cmdAttribute = method.GetCustomAttribute<cmdAttribute>(true)!;
var aliases = cmdAttribute.Aliases; var aliases = cmdAttribute.Aliases;
if (aliases.Length == 0) if (aliases.Length == 0)
aliases = new[] { method.Name.ToLowerInvariant() }; aliases = [method.Name.ToLowerInvariant()];
cmds.Add(new( cmds.Add(new(
aliases, aliases,

View File

@@ -81,7 +81,7 @@ public class BotStrings : IBotStrings
return new CommandStrings() return new CommandStrings()
{ {
Examples = new[] { "" }, Examples = [""],
Desc = "?", Desc = "?",
Params = [] Params = []
}; };

View File

@@ -19,7 +19,7 @@ public class MultilineScalarFlowStyleEmitter : ChainedEventEmitter
var value = eventInfo.Source.Value as string; var value = eventInfo.Source.Value as string;
if (!string.IsNullOrEmpty(value)) if (!string.IsNullOrEmpty(value))
{ {
var isMultiLine = value.IndexOfAny(new[] { '\r', '\n', '\x85', '\x2028', '\x2029' }) >= 0; var isMultiLine = value.IndexOfAny(['\r', '\n', '\x85', '\x2028', '\x2029']) >= 0;
if (isMultiLine) if (isMultiLine)
{ {
eventInfo = new(eventInfo.Source) eventInfo = new(eventInfo.Source)