vars and target-typed new

This commit is contained in:
Kwoth
2021-12-20 00:15:39 +01:00
parent ee33313519
commit cd379fd308
75 changed files with 198 additions and 198 deletions

View File

@@ -89,7 +89,7 @@ public class IndexedCollection<T> : IList<T> where T : class, IIndexed
{ {
if (removed = Source.Remove(item)) if (removed = Source.Remove(item))
{ {
for (int i = 0; i < Source.Count; i++) for (var i = 0; i < Source.Count; i++)
{ {
if (Source[i].Index != i) if (Source[i].Index != i)
Source[i].Index = i; Source[i].Index = i;
@@ -104,7 +104,7 @@ public class IndexedCollection<T> : IList<T> where T : class, IIndexed
lock (_locker) lock (_locker)
{ {
Source.Insert(index, item); Source.Insert(index, item);
for (int i = index; i < Source.Count; i++) for (var i = index; i < Source.Count; i++)
{ {
Source[i].Index = i; Source[i].Index = i;
} }
@@ -116,7 +116,7 @@ public class IndexedCollection<T> : IList<T> where T : class, IIndexed
lock (_locker) lock (_locker)
{ {
Source.RemoveAt(index); Source.RemoveAt(index);
for (int i = index; i < Source.Count; i++) for (var i = index; i < Source.Count; i++)
{ {
Source[i].Index = i; Source[i].Index = i;
} }

View File

@@ -69,7 +69,7 @@ public class ReplacementBuilder
_reps.TryAdd("%members%", () => g != null && g is SocketGuild sg ? sg.MemberCount.ToString() : "?"); _reps.TryAdd("%members%", () => g != null && g is SocketGuild sg ? sg.MemberCount.ToString() : "?");
_reps.TryAdd("%server_time%", () => _reps.TryAdd("%server_time%", () =>
{ {
TimeZoneInfo to = TimeZoneInfo.Local; var to = TimeZoneInfo.Local;
if (g != null) if (g != null)
{ {
if (GuildTimezoneService.AllServices.TryGetValue(client.CurrentUser.Id, out var tz)) if (GuildTimezoneService.AllServices.TryGetValue(client.CurrentUser.Id, out var tz))
@@ -88,7 +88,7 @@ public class ReplacementBuilder
_reps.TryAdd("%server.boost_level%", () => ((int)g.PremiumTier).ToString()); _reps.TryAdd("%server.boost_level%", () => ((int)g.PremiumTier).ToString());
_reps.TryAdd("%server.time%", () => _reps.TryAdd("%server.time%", () =>
{ {
TimeZoneInfo to = TimeZoneInfo.Local; var to = TimeZoneInfo.Local;
if (g != null) if (g != null)
{ {
if (GuildTimezoneService.AllServices.TryGetValue(client.CurrentUser.Id, out var tz)) if (GuildTimezoneService.AllServices.TryGetValue(client.CurrentUser.Id, out var tz))

View File

@@ -22,7 +22,7 @@ public class StoopidTime
throw new ArgumentException("Invalid string input format."); throw new ArgumentException("Invalid string input format.");
} }
string output = ""; var output = string.Empty;
var namesAndValues = new Dictionary<string, int>(); var namesAndValues = new Dictionary<string, int>();
foreach (var groupName in _regex.GetGroupNames()) foreach (var groupName in _regex.GetGroupNames())

View File

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

View File

@@ -9,7 +9,7 @@ public class ClubInfo : DbEntity
public string Name { get; set; } public string Name { get; set; }
public int Discrim { get; set; } public int Discrim { get; set; }
public string ImageUrl { get; set; } = ""; public string ImageUrl { get; set; } = string.Empty;
public int MinimumLevelReq { get; set; } = 5; public int MinimumLevelReq { get; set; } = 5;
public int Xp { get; set; } = 0; public int Xp { get; set; } = 0;

View File

@@ -20,7 +20,7 @@ public class WaifuInfo : DbEntity
public override string ToString() public override string ToString()
{ {
var claimer = "no one"; var claimer = "no one";
var status = ""; var status = string.Empty;
var waifuUsername = Waifu.Username.TrimTo(20); var waifuUsername = Waifu.Username.TrimTo(20);
var claimerUsername = Claimer?.Username.TrimTo(20); var claimerUsername = Claimer?.Username.TrimTo(20);
@@ -61,7 +61,7 @@ public class WaifuLbResult
public override string ToString() public override string ToString()
{ {
var claimer = "no one"; var claimer = "no one";
var status = ""; var status = string.Empty;
var waifuUsername = Username.TrimTo(20); var waifuUsername = Username.TrimTo(20);
var claimerUsername = Claimer?.TrimTo(20); var claimerUsername = Claimer?.TrimTo(20);

View File

@@ -14,7 +14,7 @@ public class NadekoContextFactory : IDesignTimeDbContextFactory<NadekoContext>
{ {
LogSetup.SetupLogger(-2); LogSetup.SetupLogger(-2);
var optionsBuilder = new DbContextOptionsBuilder<NadekoContext>(); var optionsBuilder = new DbContextOptionsBuilder<NadekoContext>();
IBotCredentials creds = new BotCredsProvider().GetCreds(); var creds = new BotCredsProvider().GetCreds();
var builder = new SqliteConnectionStringBuilder(creds.Db.ConnectionString); var builder = new SqliteConnectionStringBuilder(creds.Db.ConnectionString);
builder.DataSource = Path.Combine(AppContext.BaseDirectory, builder.DataSource); builder.DataSource = Path.Combine(AppContext.BaseDirectory, builder.DataSource);
optionsBuilder.UseSqlite(builder.ToString()); optionsBuilder.UseSqlite(builder.ToString());

View File

@@ -261,7 +261,7 @@ public partial class Administration
if (string.IsNullOrWhiteSpace(ignoredString)) if (string.IsNullOrWhiteSpace(ignoredString))
ignoredString = "none"; ignoredString = "none";
string add = ""; var add = string.Empty;
if (settings.MuteTime > 0) if (settings.MuteTime > 0)
{ {
add = $" ({TimeSpan.FromMinutes(settings.MuteTime):hh\\hmm\\m})"; add = $" ({TimeSpan.FromMinutes(settings.MuteTime):hh\\hmm\\m})";

View File

@@ -92,7 +92,7 @@ public partial class Administration
if (ctx.User.Id != guser.Guild.OwnerId && guser.GetRoles().Max(x => x.Position) <= role.Position) if (ctx.User.Id != guser.Guild.OwnerId && guser.GetRoles().Max(x => x.Position) <= role.Position)
return; return;
bool success = _service.RemoveSar(role.Guild.Id, role.Id); var success = _service.RemoveSar(role.Guild.Id, role.Id);
if (!success) if (!success)
{ {
await ReplyErrorLocalizedAsync(strs.self_assign_not).ConfigureAwait(false); await ReplyErrorLocalizedAsync(strs.self_assign_not).ConfigureAwait(false);
@@ -124,7 +124,7 @@ public partial class Administration
foreach (var kvp in roleGroups) foreach (var kvp in roleGroups)
{ {
var groupNameText = ""; var groupNameText = string.Empty;
if (!groups.TryGetValue(kvp.Key, out var name)) if (!groups.TryGetValue(kvp.Key, out var name))
{ {
groupNameText = Format.Bold(GetText(strs.self_assign_group(kvp.Key))); groupNameText = Format.Bold(GetText(strs.self_assign_group(kvp.Key)));
@@ -168,7 +168,7 @@ public partial class Administration
[BotPerm(GuildPerm.ManageRoles)] [BotPerm(GuildPerm.ManageRoles)]
public async Task Togglexclsar() public async Task Togglexclsar()
{ {
bool areExclusive = _service.ToggleEsar(ctx.Guild.Id); var areExclusive = _service.ToggleEsar(ctx.Guild.Id);
if (areExclusive) if (areExclusive)
await ReplyConfirmLocalizedAsync(strs.self_assign_excl).ConfigureAwait(false); await ReplyConfirmLocalizedAsync(strs.self_assign_excl).ConfigureAwait(false);
else else
@@ -184,7 +184,7 @@ public partial class Administration
if (level < 0) if (level < 0)
return; return;
bool succ = _service.SetLevelReq(ctx.Guild.Id, role, level); var succ = _service.SetLevelReq(ctx.Guild.Id, role, level);
if (!succ) if (!succ)
{ {

View File

@@ -332,7 +332,7 @@ public partial class Administration
[OwnerOnly] [OwnerOnly]
public async Task Restart() public async Task Restart()
{ {
bool success = _coord.RestartBot(); var success = _coord.RestartBot();
if (!success) if (!success)
{ {
await ReplyErrorLocalizedAsync(strs.restart_fail).ConfigureAwait(false); await ReplyErrorLocalizedAsync(strs.restart_fail).ConfigureAwait(false);

View File

@@ -73,7 +73,7 @@ DELETE FROM Clubs;";
{ {
if (reader.HasRows) if (reader.HasRows)
{ {
for (int i = 0; i < reader.FieldCount; i++) for (var i = 0; i < reader.FieldCount; i++)
{ {
result.ColumnNames.Add(reader.GetName(i)); result.ColumnNames.Add(reader.GetName(i));
} }

View File

@@ -153,7 +153,7 @@ public sealed class LogCommandService : ILogCommandService
public LogSetting GetGuildLogSettings(ulong guildId) public LogSetting GetGuildLogSettings(ulong guildId)
{ {
GuildLogSettings.TryGetValue(guildId, out LogSetting logSetting); GuildLogSettings.TryGetValue(guildId, out var logSetting);
return logSetting; return logSetting;
} }
@@ -164,7 +164,7 @@ public sealed class LogCommandService : ILogCommandService
public bool LogIgnore(ulong gid, ulong itemId, IgnoredItemType itemType) public bool LogIgnore(ulong gid, ulong itemId, IgnoredItemType itemType)
{ {
int removed = 0; var removed = 0;
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
var logSetting = uow.LogSettingsFor(gid); var logSetting = uow.LogSettingsFor(gid);
@@ -197,7 +197,7 @@ public sealed class LogCommandService : ILogCommandService
private string CurrentTime(IGuild g) private string CurrentTime(IGuild g)
{ {
DateTime time = DateTime.UtcNow; var time = DateTime.UtcNow;
if (g != null) if (g != null)
time = TimeZoneInfo.ConvertTime(time, _tz.GetTimeZoneOrUtc(g.Id)); time = TimeZoneInfo.ConvertTime(time, _tz.GetTimeZoneOrUtc(g.Id));
@@ -243,7 +243,7 @@ public sealed class LogCommandService : ILogCommandService
var g = after.Guild; var g = after.Guild;
if (!GuildLogSettings.TryGetValue(g.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(g.Id, out var logSetting)
|| (logSetting.UserUpdatedId is null)) || (logSetting.UserUpdatedId is null))
return; return;
@@ -375,7 +375,7 @@ public sealed class LogCommandService : ILogCommandService
if (beforeVch == afterVch) if (beforeVch == afterVch)
return; return;
if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out var logSetting)
|| (logSetting.LogVoicePresenceTTSId is null)) || (logSetting.LogVoicePresenceTTSId is null))
return; return;
@@ -384,7 +384,7 @@ public sealed class LogCommandService : ILogCommandService
.ConfigureAwait(false)) is null) .ConfigureAwait(false)) is null)
return; return;
var str = ""; var str = string.Empty;
if (beforeVch?.Guild == afterVch?.Guild) if (beforeVch?.Guild == afterVch?.Guild)
{ {
str = GetText(logChannel.Guild, strs.log_vc_moved(usr.Username, beforeVch?.Name, afterVch?.Name)); str = GetText(logChannel.Guild, strs.log_vc_moved(usr.Username, beforeVch?.Name, afterVch?.Name));
@@ -415,7 +415,7 @@ public sealed class LogCommandService : ILogCommandService
{ {
try try
{ {
if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out var logSetting)
|| (logSetting.UserMutedId is null)) || (logSetting.UserMutedId is null))
return; return;
@@ -423,7 +423,7 @@ public sealed class LogCommandService : ILogCommandService
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted) if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted)
.ConfigureAwait(false)) is null) .ConfigureAwait(false)) is null)
return; return;
var mutes = ""; var mutes = string.Empty;
var mutedLocalized = GetText(logChannel.Guild, strs.muted_sn); var mutedLocalized = GetText(logChannel.Guild, strs.muted_sn);
switch (muteType) switch (muteType)
{ {
@@ -459,7 +459,7 @@ public sealed class LogCommandService : ILogCommandService
{ {
try try
{ {
if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out var logSetting)
|| (logSetting.UserMutedId is null)) || (logSetting.UserMutedId is null))
return; return;
@@ -468,7 +468,7 @@ public sealed class LogCommandService : ILogCommandService
.ConfigureAwait(false)) is null) .ConfigureAwait(false)) is null)
return; return;
var mutes = ""; var mutes = string.Empty;
var unmutedLocalized = GetText(logChannel.Guild, strs.unmuted_sn); var unmutedLocalized = GetText(logChannel.Guild, strs.unmuted_sn);
switch (muteType) switch (muteType)
{ {
@@ -511,7 +511,7 @@ public sealed class LogCommandService : ILogCommandService
if (users.Length == 0) if (users.Length == 0)
return; return;
if (!GuildLogSettings.TryGetValue(users.First().Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(users.First().Guild.Id, out var logSetting)
|| (logSetting.LogOtherId is null)) || (logSetting.LogOtherId is null))
return; return;
ITextChannel logChannel; ITextChannel logChannel;
@@ -519,7 +519,7 @@ public sealed class LogCommandService : ILogCommandService
.ConfigureAwait(false)) is null) .ConfigureAwait(false)) is null)
return; return;
var punishment = ""; var punishment = string.Empty;
switch (action) switch (action)
{ {
case PunishmentAction.Mute: case PunishmentAction.Mute:
@@ -579,7 +579,7 @@ public sealed class LogCommandService : ILogCommandService
{ {
try try
{ {
if (!GuildLogSettings.TryGetValue(before.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(before.Guild.Id, out var logSetting)
|| logSetting.LogIgnores.Any(ilc => ilc.LogItemId == after.Id && ilc.ItemType == IgnoredItemType.User)) || logSetting.LogIgnores.Any(ilc => ilc.LogItemId == after.Id && ilc.ItemType == IgnoredItemType.User))
return; return;
@@ -680,7 +680,7 @@ public sealed class LogCommandService : ILogCommandService
var after = (IGuildChannel) cafter; var after = (IGuildChannel) cafter;
if (!GuildLogSettings.TryGetValue(before.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(before.Guild.Id, out var logSetting)
|| (logSetting.ChannelUpdatedId is null) || (logSetting.ChannelUpdatedId is null)
|| logSetting.LogIgnores.Any(ilc => ilc.LogItemId == after.Id && ilc.ItemType == IgnoredItemType.Channel)) || logSetting.LogIgnores.Any(ilc => ilc.LogItemId == after.Id && ilc.ItemType == IgnoredItemType.Channel))
return; return;
@@ -731,7 +731,7 @@ public sealed class LogCommandService : ILogCommandService
if (!(ich is IGuildChannel ch)) if (!(ich is IGuildChannel ch))
return; return;
if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out var logSetting)
|| (logSetting.ChannelDestroyedId is null) || (logSetting.ChannelDestroyedId is null)
|| logSetting.LogIgnores.Any(ilc => ilc.LogItemId == ch.Id && ilc.ItemType == IgnoredItemType.Channel)) || logSetting.LogIgnores.Any(ilc => ilc.LogItemId == ch.Id && ilc.ItemType == IgnoredItemType.Channel))
return; return;
@@ -771,7 +771,7 @@ public sealed class LogCommandService : ILogCommandService
if (!(ich is IGuildChannel ch)) if (!(ich is IGuildChannel ch))
return; return;
if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out var logSetting)
|| logSetting.ChannelCreatedId is null) || logSetting.ChannelCreatedId is null)
return; return;
@@ -816,7 +816,7 @@ public sealed class LogCommandService : ILogCommandService
if (beforeVch == afterVch) if (beforeVch == afterVch)
return; return;
if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out var logSetting)
|| (logSetting.LogVoicePresenceId is null) || (logSetting.LogVoicePresenceId is null)
|| logSetting.LogIgnores.Any(ilc => ilc.LogItemId == iusr.Id && ilc.ItemType == IgnoredItemType.User)) || logSetting.LogIgnores.Any(ilc => ilc.LogItemId == iusr.Id && ilc.ItemType == IgnoredItemType.User))
return; return;
@@ -869,7 +869,7 @@ public sealed class LogCommandService : ILogCommandService
{ {
try try
{ {
if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out var logSetting)
|| (logSetting.UserLeftId is null) || (logSetting.UserLeftId is null)
|| logSetting.LogIgnores.Any(ilc => ilc.LogItemId == usr.Id && ilc.ItemType == IgnoredItemType.User)) || logSetting.LogIgnores.Any(ilc => ilc.LogItemId == usr.Id && ilc.ItemType == IgnoredItemType.User))
return; return;
@@ -904,7 +904,7 @@ public sealed class LogCommandService : ILogCommandService
{ {
try try
{ {
if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out var logSetting)
|| (logSetting.UserJoinedId is null)) || (logSetting.UserJoinedId is null))
return; return;
@@ -945,7 +945,7 @@ public sealed class LogCommandService : ILogCommandService
{ {
try try
{ {
if (!GuildLogSettings.TryGetValue(guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(guild.Id, out var logSetting)
|| (logSetting.UserUnbannedId is null) || (logSetting.UserUnbannedId is null)
|| logSetting.LogIgnores.Any(ilc => ilc.LogItemId == usr.Id && ilc.ItemType == IgnoredItemType.User)) || logSetting.LogIgnores.Any(ilc => ilc.LogItemId == usr.Id && ilc.ItemType == IgnoredItemType.User))
return; return;
@@ -980,7 +980,7 @@ public sealed class LogCommandService : ILogCommandService
{ {
try try
{ {
if (!GuildLogSettings.TryGetValue(guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(guild.Id, out var logSetting)
|| (logSetting.UserBannedId is null) || (logSetting.UserBannedId is null)
|| logSetting.LogIgnores.Any(ilc => ilc.LogItemId == usr.Id && ilc.ItemType == IgnoredItemType.User)) || logSetting.LogIgnores.Any(ilc => ilc.LogItemId == usr.Id && ilc.ItemType == IgnoredItemType.User))
return; return;
@@ -1028,7 +1028,7 @@ public sealed class LogCommandService : ILogCommandService
if (!(ch is ITextChannel channel)) if (!(ch is ITextChannel channel))
return; return;
if (!GuildLogSettings.TryGetValue(channel.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(channel.Guild.Id, out var logSetting)
|| (logSetting.MessageDeletedId is null) || (logSetting.MessageDeletedId is null)
|| logSetting.LogIgnores.Any(ilc => ilc.LogItemId == channel.Id && ilc.ItemType == IgnoredItemType.Channel)) || logSetting.LogIgnores.Any(ilc => ilc.LogItemId == channel.Id && ilc.ItemType == IgnoredItemType.Channel))
return; return;
@@ -1086,7 +1086,7 @@ public sealed class LogCommandService : ILogCommandService
if (before.Author.IsBot) if (before.Author.IsBot)
return; return;
if (!GuildLogSettings.TryGetValue(channel.Guild.Id, out LogSetting logSetting) if (!GuildLogSettings.TryGetValue(channel.Guild.Id, out var logSetting)
|| (logSetting.MessageUpdatedId is null) || (logSetting.MessageUpdatedId is null)
|| logSetting.LogIgnores.Any(ilc => ilc.LogItemId == channel.Id && ilc.ItemType == IgnoredItemType.Channel)) || logSetting.LogIgnores.Any(ilc => ilc.LogItemId == channel.Id && ilc.ItemType == IgnoredItemType.Channel))
return; return;

View File

@@ -156,7 +156,7 @@ public class MuteService : INService
{ {
try try
{ {
MutedUsers.TryGetValue(usr.Guild.Id, out ConcurrentHashSet<ulong> muted); MutedUsers.TryGetValue(usr.Guild.Id, out var muted);
if (muted is null || !muted.Contains(usr.Id)) if (muted is null || !muted.Contains(usr.Id))
return Task.CompletedTask; return Task.CompletedTask;
@@ -198,7 +198,7 @@ public class MuteService : INService
{ {
UserId = usr.Id UserId = usr.Id
}); });
if (MutedUsers.TryGetValue(usr.Guild.Id, out ConcurrentHashSet<ulong> muted)) if (MutedUsers.TryGetValue(usr.Guild.Id, out var muted))
muted.Add(usr.Id); muted.Add(usr.Id);
config.UnmuteTimers.RemoveWhere(x => x.UserId == usr.Id); config.UnmuteTimers.RemoveWhere(x => x.UserId == usr.Id);
@@ -242,7 +242,7 @@ public class MuteService : INService
{ {
uow.Remove(toRemove); uow.Remove(toRemove);
} }
if (MutedUsers.TryGetValue(guildId, out ConcurrentHashSet<ulong> muted)) if (MutedUsers.TryGetValue(guildId, out var muted))
muted.TryRemove(usrId); muted.TryRemove(usrId);
config.UnmuteTimers.RemoveWhere(x => x.UserId == usrId); config.UnmuteTimers.RemoveWhere(x => x.UserId == usrId);
@@ -442,10 +442,10 @@ public class MuteService : INService
public void StopTimer(ulong guildId, ulong userId, TimerType type) public void StopTimer(ulong guildId, ulong userId, TimerType type)
{ {
if (!Un_Timers.TryGetValue(guildId, out ConcurrentDictionary<(ulong, TimerType), Timer> userTimer)) if (!Un_Timers.TryGetValue(guildId, out var userTimer))
return; return;
if (userTimer.TryRemove((userId, type), out Timer removed)) if (userTimer.TryRemove((userId, type), out var removed))
{ {
removed.Change(Timeout.Infinite, Timeout.Infinite); removed.Change(Timeout.Infinite, Timeout.Infinite);
} }

View File

@@ -131,7 +131,7 @@ public class SelfAssignedRolesService : INService
public async Task<bool> SetNameAsync(ulong guildId, int group, string name) public async Task<bool> SetNameAsync(ulong guildId, int group, string name)
{ {
bool set = false; var set = false;
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
var gc = uow.GuildConfigsForId(guildId, y => y.Include(x => x.SelfAssignableRoleGroupNames)); var gc = uow.GuildConfigsForId(guildId, y => y.Include(x => x.SelfAssignableRoleGroupNames));

View File

@@ -58,7 +58,7 @@ public class UserPunishService : INService
Weight = weight, Weight = weight,
}; };
int warnings = 1; var warnings = 1;
List<WarningPunishment> ps; List<WarningPunishment> ps;
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
@@ -299,7 +299,7 @@ WHERE GuildId={guildId}
public async Task<bool> WarnClearAsync(ulong guildId, ulong userId, int index, string moderator) public async Task<bool> WarnClearAsync(ulong guildId, ulong userId, int index, string moderator)
{ {
bool toReturn = true; var toReturn = true;
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
if (index == 0) if (index == 0)

View File

@@ -194,10 +194,10 @@ public class VcRoleService : INService
ulong guildId; ulong guildId;
guildId = newVc?.Guild.Id ?? oldVc.Guild.Id; guildId = newVc?.Guild.Id ?? oldVc.Guild.Id;
if (VcRoles.TryGetValue(guildId, out ConcurrentDictionary<ulong, IRole> guildVcRoles)) if (VcRoles.TryGetValue(guildId, out var guildVcRoles))
{ {
//remove old //remove old
if (oldVc != null && guildVcRoles.TryGetValue(oldVc.Id, out IRole role)) if (oldVc != null && guildVcRoles.TryGetValue(oldVc.Id, out var role))
{ {
Assign(false, gusr, role); Assign(false, gusr, role);
} }

View File

@@ -66,7 +66,7 @@ public partial class Administration
{ {
var guild = (SocketGuild)ctx.Guild; var guild = (SocketGuild)ctx.Guild;
string text; string text;
if (_service.VcRoles.TryGetValue(ctx.Guild.Id, out ConcurrentDictionary<ulong, IRole> roles)) if (_service.VcRoles.TryGetValue(ctx.Guild.Id, out var roles))
{ {
if (!roles.Any()) if (!roles.Any())
{ {

View File

@@ -199,7 +199,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
return; return;
} }
List<string> succ = new List<string>(); var succ = new List<string>();
foreach (var emojiStr in emojiStrs) foreach (var emojiStr in emojiStrs)
{ {

View File

@@ -403,7 +403,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
{ {
var pc = _perms.GetCacheFor(guild.Id); var pc = _perms.GetCacheFor(guild.Id);
if (!pc.Permissions.CheckPermissions(msg, cr.Trigger, "ActualCustomReactions", if (!pc.Permissions.CheckPermissions(msg, cr.Trigger, "ActualCustomReactions",
out int index)) out var index))
{ {
if (pc.Verbose) if (pc.Verbose)
{ {

View File

@@ -58,7 +58,7 @@ public class Deck
{ {
get get
{ {
var str = ""; var str = string.Empty;
if (Number <= 10 && Number > 1) if (Number <= 10 && Number > 1)
{ {
@@ -106,7 +106,7 @@ public class Deck
public string GetEmojiString() public string GetEmojiString()
{ {
var str = ""; var str = string.Empty;
str += _regIndicators[this.Number - 1]; str += _regIndicators[this.Number - 1];
str += _suitToSuitChar[this.Suit]; str += _suitToSuitChar[this.Suit];

View File

@@ -71,7 +71,7 @@ public class GameStatusEvent : ICurrencyEvent
private async void OnTimerTick(object state) private async void OnTimerTick(object state)
{ {
var potEmpty = PotEmptied; var potEmpty = PotEmptied;
List<ulong> toAward = new List<ulong>(); var toAward = new List<ulong>();
while (_toAward.TryDequeue(out var x)) while (_toAward.TryDequeue(out var x))
{ {
toAward.Add(x); toAward.Add(x);

View File

@@ -67,7 +67,7 @@ public class ReactionEvent : ICurrencyEvent
private async void OnTimerTick(object state) private async void OnTimerTick(object state)
{ {
var potEmpty = PotEmptied; var potEmpty = PotEmptied;
List<ulong> toAward = new List<ulong>(); var toAward = new List<ulong>();
while (_toAward.TryDequeue(out var x)) while (_toAward.TryDequeue(out var x))
{ {
toAward.Add(x); toAward.Add(x);

View File

@@ -79,7 +79,7 @@ public sealed class Connect4Game : IDisposable
_cs = cs; _cs = cs;
_rng = new NadekoRandom(); _rng = new NadekoRandom();
for (int i = 0; i < NumberOfColumns * NumberOfRows; i++) for (var i = 0; i < NumberOfColumns * NumberOfRows; i++)
{ {
_gameState[i] = Field.Empty; _gameState[i] = Field.Empty;
} }
@@ -169,7 +169,7 @@ public sealed class Connect4Game : IDisposable
return false; return false;
var start = NumberOfRows * inputCol; var start = NumberOfRows * inputCol;
for (int i = start; i < start + NumberOfRows; i++) for (var i = start; i < start + NumberOfRows; i++)
{ {
if (_gameState[i] == Field.Empty) if (_gameState[i] == Field.Empty)
{ {
@@ -181,12 +181,12 @@ public sealed class Connect4Game : IDisposable
//check winnning condition //check winnning condition
// ok, i'll go from [0-2] in rows (and through all columns) and check upward if 4 are connected // ok, i'll go from [0-2] in rows (and through all columns) and check upward if 4 are connected
for (int i = 0; i < NumberOfRows - 3; i++) for (var i = 0; i < NumberOfRows - 3; i++)
{ {
if (CurrentPhase == Phase.Ended) if (CurrentPhase == Phase.Ended)
break; break;
for (int j = 0; j < NumberOfColumns; j++) for (var j = 0; j < NumberOfColumns; j++)
{ {
if (CurrentPhase == Phase.Ended) if (CurrentPhase == Phase.Ended)
break; break;
@@ -194,7 +194,7 @@ public sealed class Connect4Game : IDisposable
var first = _gameState[i + j * NumberOfRows]; var first = _gameState[i + j * NumberOfRows];
if (first != Field.Empty) if (first != Field.Empty)
{ {
for (int k = 1; k < 4; k++) for (var k = 1; k < 4; k++)
{ {
var next = _gameState[i + k + j * NumberOfRows]; var next = _gameState[i + k + j * NumberOfRows];
if (next == first) if (next == first)
@@ -211,12 +211,12 @@ public sealed class Connect4Game : IDisposable
} }
// i'll go [0-1] in columns (and through all rows) and check to the right if 4 are connected // i'll go [0-1] in columns (and through all rows) and check to the right if 4 are connected
for (int i = 0; i < NumberOfColumns - 3; i++) for (var i = 0; i < NumberOfColumns - 3; i++)
{ {
if (CurrentPhase == Phase.Ended) if (CurrentPhase == Phase.Ended)
break; break;
for (int j = 0; j < NumberOfRows; j++) for (var j = 0; j < NumberOfRows; j++)
{ {
if (CurrentPhase == Phase.Ended) if (CurrentPhase == Phase.Ended)
break; break;
@@ -224,7 +224,7 @@ public sealed class Connect4Game : IDisposable
var first = _gameState[j + i * NumberOfRows]; var first = _gameState[j + i * NumberOfRows];
if (first != Field.Empty) if (first != Field.Empty)
{ {
for (int k = 1; k < 4; k++) for (var k = 1; k < 4; k++)
{ {
var next = _gameState[j + (i + k) * NumberOfRows]; var next = _gameState[j + (i + k) * NumberOfRows];
if (next == first) if (next == first)
@@ -239,12 +239,12 @@ public sealed class Connect4Game : IDisposable
} }
//need to check diagonal now //need to check diagonal now
for (int col = 0; col < NumberOfColumns; col++) for (var col = 0; col < NumberOfColumns; col++)
{ {
if (CurrentPhase == Phase.Ended) if (CurrentPhase == Phase.Ended)
break; break;
for (int row = 0; row < NumberOfRows; row++) for (var row = 0; row < NumberOfRows; row++)
{ {
if (CurrentPhase == Phase.Ended) if (CurrentPhase == Phase.Ended)
break; break;
@@ -256,7 +256,7 @@ public sealed class Connect4Game : IDisposable
var same = 1; var same = 1;
//top left //top left
for (int i = 1; i < 4; i++) for (var i = 1; i < 4; i++)
{ {
//while going top left, rows are increasing, columns are decreasing //while going top left, rows are increasing, columns are decreasing
var curRow = row + i; var curRow = row + i;
@@ -283,7 +283,7 @@ public sealed class Connect4Game : IDisposable
same = 1; same = 1;
//top right //top right
for (int i = 1; i < 4; i++) for (var i = 1; i < 4; i++)
{ {
//while going top right, rows are increasing, columns are increasing //while going top right, rows are increasing, columns are increasing
var curRow = row + i; var curRow = row + i;
@@ -361,7 +361,7 @@ public sealed class Connect4Game : IDisposable
private bool IsColumnFull(int column) private bool IsColumnFull(int column)
{ {
var start = NumberOfRows * column; var start = NumberOfRows * column;
for (int i = start; i < start + NumberOfRows; i++) for (var i = start; i < start + NumberOfRows; i++)
{ {
if (_gameState[i] == Field.Empty) if (_gameState[i] == Field.Empty)
return false; return false;

View File

@@ -84,7 +84,7 @@ public partial class Gambling
var _ = Task.Run(async () => var _ = Task.Run(async () =>
{ {
bool success = false; var success = false;
if (int.TryParse(arg.Content, out var col)) if (int.TryParse(arg.Content, out var col))
{ {
success = await game.Input(arg.Author.Id, col).ConfigureAwait(false); success = await game.Input(arg.Author.Id, col).ConfigureAwait(false);
@@ -181,9 +181,9 @@ public partial class Gambling
game.CurrentPhase == Connect4Game.Phase.P2Move) game.CurrentPhase == Connect4Game.Phase.P2Move)
sb.AppendLine(GetText(strs.connect4_player_to_move(Format.Bold(game.CurrentPlayer.Username)))); sb.AppendLine(GetText(strs.connect4_player_to_move(Format.Bold(game.CurrentPlayer.Username))));
for (int i = Connect4Game.NumberOfRows; i > 0; i--) for (var i = Connect4Game.NumberOfRows; i > 0; i--)
{ {
for (int j = 0; j < Connect4Game.NumberOfColumns; j++) for (var j = 0; j < Connect4Game.NumberOfColumns; j++)
{ {
var cur = game.GameState[i + (j * Connect4Game.NumberOfRows) - 1]; var cur = game.GameState[i + (j * Connect4Game.NumberOfRows) - 1];
@@ -197,7 +197,7 @@ public partial class Gambling
sb.AppendLine(); sb.AppendLine();
} }
for (int i = 0; i < Connect4Game.NumberOfColumns; i++) for (var i = 0; i < Connect4Game.NumberOfColumns; i++)
{ {
sb.Append(numbers[i]); sb.Append(numbers[i]);
} }

View File

@@ -136,14 +136,14 @@ public partial class Gambling
{ {
Match match; Match match;
if ((match = fudgeRegex.Match(arg)).Length != 0 && if ((match = fudgeRegex.Match(arg)).Length != 0 &&
int.TryParse(match.Groups["n1"].ToString(), out int n1) && int.TryParse(match.Groups["n1"].ToString(), out var n1) &&
n1 > 0 && n1 < 500) n1 > 0 && n1 < 500)
{ {
var rng = new NadekoRandom(); var rng = new NadekoRandom();
var rolls = new List<char>(); var rolls = new List<char>();
for (int i = 0; i < n1; i++) for (var i = 0; i < n1; i++)
{ {
rolls.Add(_fateRolls[rng.Next(0, _fateRolls.Length)]); rolls.Add(_fateRolls[rng.Next(0, _fateRolls.Length)]);
} }
@@ -158,16 +158,16 @@ public partial class Gambling
{ {
var rng = new NadekoRandom(); var rng = new NadekoRandom();
if (int.TryParse(match.Groups["n1"].ToString(), out n1) && if (int.TryParse(match.Groups["n1"].ToString(), out n1) &&
int.TryParse(match.Groups["n2"].ToString(), out int n2) && int.TryParse(match.Groups["n2"].ToString(), out var n2) &&
n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0) n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0)
{ {
if (!int.TryParse(match.Groups["add"].Value, out int add)) if (!int.TryParse(match.Groups["add"].Value, out var add))
add = 0; add = 0;
if (!int.TryParse(match.Groups["sub"].Value, out int sub)) if (!int.TryParse(match.Groups["sub"].Value, out var sub))
sub = 0; sub = 0;
var arr = new int[n1]; var arr = new int[n1];
for (int i = 0; i < n1; i++) for (var i = 0; i < n1; i++)
{ {
arr[i] = rng.Next(1, n2 + 1); arr[i] = rng.Next(1, n2 + 1);
} }

View File

@@ -31,7 +31,7 @@ public partial class Gambling
if (num < 1 || num > 10) if (num < 1 || num > 10)
throw new ArgumentOutOfRangeException(nameof(num)); throw new ArgumentOutOfRangeException(nameof(num));
Deck cards = guildId is null ? new Deck() : _allDecks.GetOrAdd(ctx.Guild, (s) => new Deck()); var cards = guildId is null ? new Deck() : _allDecks.GetOrAdd(ctx.Guild, (s) => new Deck());
var images = new List<Image<Rgba32>>(); var images = new List<Image<Rgba32>>();
var cardObjects = new List<Deck.Card>(); var cardObjects = new List<Deck.Card>();
for (var i = 0; i < num; i++) for (var i = 0; i < num; i++)

View File

@@ -197,7 +197,7 @@ public partial class Gambling : GamblingModule<GamblingService>
((SocketGuild)ctx.Guild)?.GetUser(userId)?.ToString() ?? $"{userId}"))) ((SocketGuild)ctx.Guild)?.GetUser(userId)?.ToString() ?? $"{userId}")))
.WithOkColor(); .WithOkColor();
var desc = ""; var desc = string.Empty;
foreach (var tr in trs) foreach (var tr in trs)
{ {
var type = tr.Amount > 0 ? "🔵" : "🔴"; var type = tr.Amount > 0 ? "🔵" : "🔴";
@@ -517,7 +517,7 @@ public partial class Gambling : GamblingModule<GamblingService>
var (opts, _) = OptionsParser.ParseFrom(new LbOpts(), args); var (opts, _) = OptionsParser.ParseFrom(new LbOpts(), args);
List<DiscordUser> cleanRichest = new List<DiscordUser>(); var cleanRichest = new List<DiscordUser>();
// it's pointless to have clean on dm context // it's pointless to have clean on dm context
if (ctx.Guild is null) if (ctx.Guild is null)
{ {

View File

@@ -84,7 +84,7 @@ public partial class Gambling
#endif #endif
public async Task GenCurrency() public async Task GenCurrency()
{ {
bool enabled = _service.ToggleCurrencyGeneration(ctx.Guild.Id, ctx.Channel.Id); var enabled = _service.ToggleCurrencyGeneration(ctx.Guild.Id, ctx.Channel.Id);
if (enabled) if (enabled)
{ {
await ReplyConfirmLocalizedAsync(strs.curgen_enabled).ConfigureAwait(false); await ReplyConfirmLocalizedAsync(strs.curgen_enabled).ConfigureAwait(false);

View File

@@ -31,8 +31,8 @@ public class CurrencyEventsService : INService
public async Task<bool> TryCreateEventAsync(ulong guildId, ulong channelId, CurrencyEvent.Type type, public async Task<bool> TryCreateEventAsync(ulong guildId, ulong channelId, CurrencyEvent.Type type,
EventOptions opts, Func<CurrencyEvent.Type, EventOptions, long, IEmbedBuilder> embed) EventOptions opts, Func<CurrencyEvent.Type, EventOptions, long, IEmbedBuilder> embed)
{ {
SocketGuild g = _client.GetGuild(guildId); var g = _client.GetGuild(guildId);
SocketTextChannel ch = g?.GetChannel(channelId) as SocketTextChannel; var ch = g?.GetChannel(channelId) as SocketTextChannel;
if (ch is null) if (ch is null)
return false; return false;

View File

@@ -59,7 +59,7 @@ public partial class Gambling
var embed = _eb.Create().WithOkColor() var embed = _eb.Create().WithOkColor()
.WithTitle(GetText(strs.shop)); .WithTitle(GetText(strs.shop));
for (int i = 0; i < theseEntries.Length; i++) for (var i = 0; i < theseEntries.Length; i++)
{ {
var entry = theseEntries[i]; var entry = theseEntries[i];
embed.AddField( embed.AddField(
@@ -292,8 +292,8 @@ public partial class Gambling
Text = itemText Text = itemText
}; };
ShopEntry entry; ShopEntry entry;
bool rightType = false; var rightType = false;
bool added = false; var added = false;
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
var entries = new IndexedCollection<ShopEntry>(uow.GuildConfigsForId(ctx.Guild.Id, var entries = new IndexedCollection<ShopEntry>(uow.GuildConfigsForId(ctx.Guild.Id,

View File

@@ -122,7 +122,7 @@ public partial class Gambling
return; return;
//multi vs how many times it occured //multi vs how many times it occured
var dict = new Dictionary<int, int>(); var dict = new Dictionary<int, int>();
for (int i = 0; i < tests; i++) for (var i = 0; i < tests; i++)
{ {
var res = SlotMachine.Pull(); var res = SlotMachine.Pull();
if (dict.ContainsKey(res.Multiplier)) if (dict.ContainsKey(res.Multiplier))
@@ -133,7 +133,7 @@ public partial class Gambling
var sb = new StringBuilder(); var sb = new StringBuilder();
const int bet = 1; const int bet = 1;
int payout = 0; var payout = 0;
foreach (var key in dict.Keys.OrderByDescending(x => x)) foreach (var key in dict.Keys.OrderByDescending(x => x))
{ {
sb.AppendLine($"x{key} occured {dict[key]} times. {dict[key] * 1.0f / tests * 100}%"); sb.AppendLine($"x{key} occured {dict[key]} times. {dict[key] * 1.0f / tests * 100}%");

View File

@@ -106,7 +106,7 @@ public sealed class AcrophobiaGame : IDisposable
var lettersArr = new char[wordCount]; var lettersArr = new char[wordCount];
for (int i = 0; i < wordCount; i++) for (var i = 0; i < wordCount; i++)
{ {
var randChar = (char)_rng.Next(65, 91); var randChar = (char)_rng.Next(65, 91);
lettersArr[i] = randChar == 'X' ? (char)_rng.Next(65, 88) : randChar; lettersArr[i] = randChar == 'X' ? (char)_rng.Next(65, 88) : randChar;
@@ -160,7 +160,7 @@ public sealed class AcrophobiaGame : IDisposable
if (inputWords.Length != StartingLetters.Length) // number of words must be the same as the number of the starting letters if (inputWords.Length != StartingLetters.Length) // number of words must be the same as the number of the starting letters
return false; return false;
for (int i = 0; i < StartingLetters.Length; i++) for (var i = 0; i < StartingLetters.Length; i++)
{ {
var letter = StartingLetters[i]; var letter = StartingLetters[i];

View File

@@ -33,7 +33,7 @@ public class PollRunner
return false; return false;
// has to be an integer // has to be an integer
if (!int.TryParse(msg.Content, out int vote)) if (!int.TryParse(msg.Content, out var vote))
return false; return false;
--vote; --vote;
if (vote < 0 || vote >= Poll.Answers.Count) if (vote < 0 || vote >= Poll.Answers.Count)

View File

@@ -250,7 +250,7 @@ public class TicTacToe
_phase = Phase.Ended; _phase = Phase.Ended;
} }
var reason = ""; var reason = string.Empty;
if (_phase == Phase.Ended) // if user won, stop receiving moves if (_phase == Phase.Ended) // if user won, stop receiving moves
{ {

View File

@@ -46,15 +46,15 @@ public class TriviaQuestion
return true; return true;
} }
int levDistanceClean = CleanAnswer.LevenshteinDistance(cleanGuess); var levDistanceClean = CleanAnswer.LevenshteinDistance(cleanGuess);
int levDistanceNormal = Answer.LevenshteinDistance(guess); var levDistanceNormal = Answer.LevenshteinDistance(guess);
return JudgeGuess(CleanAnswer.Length, cleanGuess.Length, levDistanceClean) return JudgeGuess(CleanAnswer.Length, cleanGuess.Length, levDistanceClean)
|| JudgeGuess(Answer.Length, guess.Length, levDistanceNormal); || JudgeGuess(Answer.Length, guess.Length, levDistanceNormal);
} }
private static bool JudgeGuess(int guessLength, int answerLength, int levDistance) private static bool JudgeGuess(int guessLength, int answerLength, int levDistance)
{ {
foreach (Tuple<int, int> level in strictness) foreach (var level in strictness)
{ {
if (guessLength <= level.Item1 || answerLength <= level.Item1) if (guessLength <= level.Item1 || answerLength <= level.Item1)
{ {

View File

@@ -105,7 +105,7 @@ public partial class Games
.OrderByDescending(x => x.votes) .OrderByDescending(x => x.votes)
.ToArray(); .ToArray();
for (int i = 0; i < stats.Length; i++) for (var i = 0; i < stats.Length; i++)
{ {
var (Index, votes, Text) = stats[i]; var (Index, votes, Text) = stats[i];
sb.AppendLine(GetText(strs.poll_result( sb.AppendLine(GetText(strs.poll_result(

View File

@@ -60,7 +60,7 @@ public class ChatterBotService : IEarlyBehavior
if (channel is null) if (channel is null)
return null; return null;
if (!ChatterBotGuilds.TryGetValue(channel.Guild.Id, out Lazy<IChatterBotSession> lazyCleverbot)) if (!ChatterBotGuilds.TryGetValue(channel.Guild.Id, out var lazyCleverbot))
return null; return null;
cleverbot = lazyCleverbot.Value; cleverbot = lazyCleverbot.Value;
@@ -107,7 +107,7 @@ public class ChatterBotService : IEarlyBehavior
return false; return false;
try try
{ {
var message = PrepareMessage(usrMsg, out IChatterBotSession cbs); var message = PrepareMessage(usrMsg, out var cbs);
if (message is null || cbs is null) if (message is null || cbs is null)
return false; return false;
@@ -115,7 +115,7 @@ public class ChatterBotService : IEarlyBehavior
if (!pc.Permissions.CheckPermissions(usrMsg, if (!pc.Permissions.CheckPermissions(usrMsg,
"cleverbot", "cleverbot",
"Games".ToLowerInvariant(), "Games".ToLowerInvariant(),
out int index)) out var index))
{ {
if (pc.Verbose) if (pc.Verbose)
{ {

View File

@@ -48,7 +48,7 @@ public partial class Games
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task TypeStop() public async Task TypeStop()
{ {
if (_service.RunningContests.TryRemove(ctx.Guild.Id, out TypingGame game)) if (_service.RunningContests.TryRemove(ctx.Guild.Id, out var game))
{ {
await game.Stop().ConfigureAwait(false); await game.Stop().ConfigureAwait(false);
return; return;

View File

@@ -34,7 +34,7 @@ public partial class Games
await _sem.WaitAsync(1000).ConfigureAwait(false); await _sem.WaitAsync(1000).ConfigureAwait(false);
try try
{ {
if (_service.TicTacToeGames.TryGetValue(channel.Id, out TicTacToe game)) if (_service.TicTacToeGames.TryGetValue(channel.Id, out var game))
{ {
var _ = Task.Run(async () => var _ = Task.Run(async () =>
{ {

View File

@@ -72,7 +72,7 @@ public partial class Games
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task Tl() public async Task Tl()
{ {
if (_service.RunningTrivias.TryGetValue(ctx.Guild.Id, out TriviaGame trivia)) if (_service.RunningTrivias.TryGetValue(ctx.Guild.Id, out var trivia))
{ {
await SendConfirmAsync(GetText(strs.leaderboard), trivia.GetLeaderboard()).ConfigureAwait(false); await SendConfirmAsync(GetText(strs.leaderboard), trivia.GetLeaderboard()).ConfigureAwait(false);
return; return;
@@ -87,7 +87,7 @@ public partial class Games
{ {
var channel = (ITextChannel)ctx.Channel; var channel = (ITextChannel)ctx.Channel;
if (_service.RunningTrivias.TryGetValue(channel.Guild.Id, out TriviaGame trivia)) if (_service.RunningTrivias.TryGetValue(channel.Guild.Id, out var trivia))
{ {
await trivia.StopGame().ConfigureAwait(false); await trivia.StopGame().ConfigureAwait(false);
return; return;

View File

@@ -283,7 +283,7 @@ public class Help : NadekoModule<HelpService>
if (com is null) if (com is null)
{ {
IMessageChannel ch = channel is ITextChannel var ch = channel is ITextChannel
? await ((IGuildUser)ctx.User).GetOrCreateDMChannelAsync().ConfigureAwait(false) ? await ((IGuildUser)ctx.User).GetOrCreateDMChannelAsync().ConfigureAwait(false)
: channel; : channel;
try try

View File

@@ -135,7 +135,7 @@ public class HelpService : ILateExecutor, INService
var userPerm = (UserPermAttribute)cmd.Preconditions var userPerm = (UserPermAttribute)cmd.Preconditions
.FirstOrDefault(ca => ca is UserPermAttribute); .FirstOrDefault(ca => ca is UserPermAttribute);
string userPermString = string.Empty; var userPermString = string.Empty;
if (userPerm is not null) if (userPerm is not null)
{ {
if (userPerm.UserPermissionAttribute.ChannelPermission is ChannelPermission cPerm) if (userPerm.UserPermissionAttribute.ChannelPermission is ChannelPermission cPerm)

View File

@@ -106,7 +106,7 @@ public sealed class MusicPlayer : IMusicPlayer
{ {
// wait until a song is available in the queue // wait until a song is available in the queue
// or until the queue is resumed // or until the queue is resumed
var track = _queue.GetCurrent(out int index); var track = _queue.GetCurrent(out var index);
if (track is null || IsStopped) if (track is null || IsStopped)
{ {

View File

@@ -85,7 +85,7 @@ public sealed partial class MusicQueue : IMusicQueue
return Enqueue(trackInfo, queuer, out index); return Enqueue(trackInfo, queuer, out index);
} }
LinkedListNode<QueuedTrackInfo> currentNode = _tracks.First!; var currentNode = _tracks.First!;
int i; int i;
for (i = 1; i <= _index; i++) for (i = 1; i <= _index; i++)
{ {

View File

@@ -280,7 +280,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
IEmbedBuilder printAction(int curPage) IEmbedBuilder printAction(int curPage)
{ {
string desc = string.Empty; var desc = string.Empty;
var current = mp.GetCurrentTrack(out var currentIndex); var current = mp.GetCurrentTrack(out var currentIndex);
if (current is not null) if (current is not null)
{ {
@@ -288,7 +288,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
} }
var repeatType = mp.Repeat; var repeatType = mp.Repeat;
var add = ""; var add = string.Empty;
if (mp.IsStopped) if (mp.IsStopped)
add += Format.Bold(GetText(strs.queue_stopped(Format.Code(Prefix + "play")))) + "\n"; add += Format.Bold(GetText(strs.queue_stopped(Format.Code(Prefix + "play")))) + "\n";
// var mps = mp.MaxPlaytimeSeconds; // var mps = mp.MaxPlaytimeSeconds;

View File

@@ -11,7 +11,7 @@ public static class PermissionExtensions
{ {
var perms = permsEnumerable as List<Permissionv2> ?? permsEnumerable.ToList(); var perms = permsEnumerable as List<Permissionv2> ?? permsEnumerable.ToList();
for (int i = perms.Count - 1; i >= 0; i--) for (var i = perms.Count - 1; i >= 0; i--)
{ {
var perm = perms[i]; var perm = perms[i];
@@ -68,7 +68,7 @@ public static class PermissionExtensions
public static string GetCommand(this Permissionv2 perm, string prefix, SocketGuild guild = null) public static string GetCommand(this Permissionv2 perm, string prefix, SocketGuild guild = null)
{ {
var com = ""; var com = string.Empty;
switch (perm.PrimaryTarget) switch (perm.PrimaryTarget)
{ {
case PrimaryPermissionType.User: case PrimaryPermissionType.User:

View File

@@ -33,7 +33,7 @@ public sealed class FilterService : IEarlyBehavior
public ConcurrentHashSet<string> FilteredWordsForChannel(ulong channelId, ulong guildId) public ConcurrentHashSet<string> FilteredWordsForChannel(ulong channelId, ulong guildId)
{ {
ConcurrentHashSet<string> words = new ConcurrentHashSet<string>(); var words = new ConcurrentHashSet<string>();
if (WordFilteringChannels.Contains(channelId)) if (WordFilteringChannels.Contains(channelId))
ServerFilteredWords.TryGetValue(guildId, out words); ServerFilteredWords.TryGetValue(guildId, out words);
return words; return words;

View File

@@ -119,8 +119,8 @@ public class PermissionService : ILateBlocker, INService
{ {
var resetCommand = commandName == "resetperms"; var resetCommand = commandName == "resetperms";
PermissionCache pc = GetCacheFor(guild.Id); var pc = GetCacheFor(guild.Id);
if (!resetCommand && !pc.Permissions.CheckPermissions(msg, commandName, moduleName, out int index)) if (!resetCommand && !pc.Permissions.CheckPermissions(msg, commandName, moduleName, out var index))
{ {
if (pc.Verbose) if (pc.Verbose)
{ {

View File

@@ -35,8 +35,8 @@
// if (_token != default && (DateTime.UtcNow - _token.Expiry) > TimeSpan.FromHours(1)) // if (_token != default && (DateTime.UtcNow - _token.Expiry) > TimeSpan.FromHours(1))
// return; // return;
// //
// const string clientId = ""; // const string clientId = string.Empty;
// const string clientSecret = ""; // const string clientSecret = string.Empty;
// //
// var client = _httpClientFactory.CreateClient(); // var client = _httpClientFactory.CreateClient();
// var res = await client.PostAsync("https://id.twitch.tv/oauth2/token" + // var res = await client.PostAsync("https://id.twitch.tv/oauth2/token" +

View File

@@ -55,7 +55,7 @@ public partial class Searches
await ctx.SendPaginatedConfirmAsync(page, curPage => await ctx.SendPaginatedConfirmAsync(page, curPage =>
{ {
var templates = ""; var templates = string.Empty;
foreach (var template in data.Skip(curPage * 15).Take(15)) foreach (var template in data.Skip(curPage * 15).Take(15))
{ {
templates += $"**{template.Name}:**\n key: `{template.Id}`\n"; templates += $"**{template.Name}:**\n key: `{template.Id}`\n";

View File

@@ -85,7 +85,7 @@ public partial class Searches
{ {
var sb = new System.Text.StringBuilder(); var sb = new System.Text.StringBuilder();
sb.AppendLine($"```{"#",-5}{"Character Name",-23}{"League",-10}{"Class",-13}{"Level",-3}"); sb.AppendLine($"```{"#",-5}{"Character Name",-23}{"League",-10}{"Class",-13}{"Level",-3}");
for (int i = 0; i < tempList.Count; i++) for (var i = 0; i < tempList.Count; i++)
{ {
var character = tempList[i]; var character = tempList[i];
@@ -131,7 +131,7 @@ public partial class Searches
var sb = new System.Text.StringBuilder(); var sb = new System.Text.StringBuilder();
sb.AppendLine($"```{"#",-5}{"League Name",-23}"); sb.AppendLine($"```{"#",-5}{"League Name",-23}");
for (int i = 0; i < leagues.Count; i++) for (var i = 0; i < leagues.Count; i++)
{ {
var league = leagues[i]; var league = leagues[i];
@@ -168,8 +168,8 @@ public partial class Searches
{ {
var obj = JObject.Parse(await http.GetStringAsync(res).ConfigureAwait(false)); var obj = JObject.Parse(await http.GetStringAsync(res).ConfigureAwait(false));
float chaosEquivalent = 0.0F; var chaosEquivalent = 0.0F;
float conversionEquivalent = 0.0F; var conversionEquivalent = 0.0F;
// poe.ninja API does not include a "chaosEquivalent" property for Chaos Orbs. // poe.ninja API does not include a "chaosEquivalent" property for Chaos Orbs.
if (cleanCurrency == "Chaos Orb") if (cleanCurrency == "Chaos Orb")

View File

@@ -36,7 +36,7 @@ public partial class Searches
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
public async Task Place(PlaceType placeType, uint width = 0, uint height = 0) public async Task Place(PlaceType placeType, uint width = 0, uint height = 0)
{ {
var url = ""; var url = string.Empty;
switch (placeType) switch (placeType)
{ {
case PlaceType.Cage: case PlaceType.Cage:

View File

@@ -75,7 +75,7 @@ public partial class Searches : NadekoModule<SearchesService>
} }
else else
{ {
Func<double, double> f = StandardConversions.CelsiusToFahrenheit; var f = StandardConversions.CelsiusToFahrenheit;
var tz = ctx.Guild is null var tz = ctx.Guild is null
? TimeZoneInfo.Utc ? TimeZoneInfo.Utc
@@ -616,7 +616,7 @@ public partial class Searches : NadekoModule<SearchesService>
using (var img = new Image<Rgba32>(colorObjects.Length * 50, 50)) using (var img = new Image<Rgba32>(colorObjects.Length * 50, 50))
{ {
for (int i = 0; i < colorObjects.Length; i++) for (var i = 0; i < colorObjects.Length; i++)
{ {
var x = i * 50; var x = i * 50;
img.Mutate(m => m.FillPolygon(colorObjects[i], new PointF[] { img.Mutate(m => m.FillPolygon(colorObjects[i], new PointF[] {

View File

@@ -72,7 +72,7 @@ public class FeedsService : INService
.Reverse() // start from the oldest .Reverse() // start from the oldest
.ToList(); .ToList();
if (!_lastPosts.TryGetValue(kvp.Key, out DateTime lastFeedUpdate)) if (!_lastPosts.TryGetValue(kvp.Key, out var lastFeedUpdate))
{ {
lastFeedUpdate = _lastPosts[kvp.Key] = lastFeedUpdate = _lastPosts[kvp.Key] =
items.Any() ? items[items.Count - 1].LastUpdate : DateTime.UtcNow; items.Any() ? items[items.Count - 1].LastUpdate : DateTime.UtcNow;

View File

@@ -77,7 +77,7 @@ public class SearchesService : INService
public async Task<Stream> GetRipPictureAsync(string text, Uri imgUrl) public async Task<Stream> GetRipPictureAsync(string text, Uri imgUrl)
{ {
byte[] data = await _cache.GetOrAddCachedDataAsync($"nadeko_rip_{text}_{imgUrl}", var data = await _cache.GetOrAddCachedDataAsync($"nadeko_rip_{text}_{imgUrl}",
GetRipPictureFactory, GetRipPictureFactory,
(text, imgUrl), (text, imgUrl),
TimeSpan.FromDays(1)).ConfigureAwait(false); TimeSpan.FromDays(1)).ConfigureAwait(false);
@@ -388,7 +388,7 @@ public class SearchesService : INService
return new MtgData[0]; return new MtgData[0];
var tasks = new List<Task<MtgData>>(cards.Length); var tasks = new List<Task<MtgData>>(cards.Length);
for (int i = 0; i < cards.Length; i++) for (var i = 0; i < cards.Length; i++)
{ {
var card = cards[i]; var card = cards[i];

View File

@@ -83,7 +83,7 @@ public partial class Searches
return; return;
} }
List<FollowedStream> streams = new List<FollowedStream>(); var streams = new List<FollowedStream>();
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
var all = uow var all = uow

View File

@@ -133,9 +133,9 @@ public partial class Utility
if (page < 0) if (page < 0)
return; return;
int startCount = page * activityPerPage; var startCount = page * activityPerPage;
StringBuilder str = new StringBuilder(); var str = new StringBuilder();
foreach (var kvp in CmdHandler.UserMessagesSent.OrderByDescending(kvp => kvp.Value).Skip(page * activityPerPage).Take(activityPerPage)) foreach (var kvp in CmdHandler.UserMessagesSent.OrderByDescending(kvp => kvp.Value).Skip(page * activityPerPage).Take(activityPerPage))
{ {
str.AppendLine(GetText(strs.activity_line( str.AppendLine(GetText(strs.activity_line(

View File

@@ -187,7 +187,7 @@ public partial class Utility
var executesInString = Format.Bold(executesIn.ToPrettyStringHM()); var executesInString = Format.Bold(executesIn.ToPrettyStringHM());
var message = Format.Sanitize(runner.Repeater.Message.TrimTo(50)); var message = Format.Sanitize(runner.Repeater.Message.TrimTo(50));
string description = ""; var description = string.Empty;
if (_service.IsNoRedundant(runner.Repeater.Id)) if (_service.IsNoRedundant(runner.Repeater.Id))
{ {
description = Format.Underline(Format.Bold(GetText(strs.no_redundant))) + "\n\n"; description = Format.Underline(Format.Bold(GetText(strs.no_redundant))) + "\n\n";

View File

@@ -67,7 +67,7 @@ public class CommandMapService : IInputTransformer, INService
if (guild != null) if (guild != null)
{ {
if (AliasMaps.TryGetValue(guild.Id, out ConcurrentDictionary<string, string> maps)) if (AliasMaps.TryGetValue(guild.Id, out var maps))
{ {
var keys = maps.Keys var keys = maps.Keys
.OrderByDescending(x => x.Length); .OrderByDescending(x => x.Length);

View File

@@ -69,7 +69,7 @@ public class StreamRoleService : INService
{ {
userName.ThrowIfNull(nameof(userName)); userName.ThrowIfNull(nameof(userName));
bool success = false; var success = false;
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
var streamRoleSettings = uow.GetStreamRoleSettings(guild.Id); var streamRoleSettings = uow.GetStreamRoleSettings(guild.Id);

View File

@@ -39,7 +39,7 @@ public partial class Utility
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task StreamRoleKeyword([Leftover]string keyword = null) public async Task StreamRoleKeyword([Leftover]string keyword = null)
{ {
string kw = await this._service.SetKeyword(ctx.Guild, keyword).ConfigureAwait(false); var kw = await this._service.SetKeyword(ctx.Guild, keyword).ConfigureAwait(false);
if(string.IsNullOrWhiteSpace(keyword)) if(string.IsNullOrWhiteSpace(keyword))
await ReplyConfirmLocalizedAsync(strs.stream_role_kw_reset).ConfigureAwait(false); await ReplyConfirmLocalizedAsync(strs.stream_role_kw_reset).ConfigureAwait(false);

View File

@@ -81,7 +81,7 @@ public partial class Utility : NadekoModule
.Take(60) .Take(60)
.ToArray()).ConfigureAwait(false); .ToArray()).ConfigureAwait(false);
int i = 0; var i = 0;
if (arr.Length == 0) if (arr.Length == 0)
await ReplyErrorLocalizedAsync(strs.nobody_playing_game).ConfigureAwait(false); await ReplyErrorLocalizedAsync(strs.nobody_playing_game).ConfigureAwait(false);
else else
@@ -140,7 +140,7 @@ public partial class Utility : NadekoModule
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task CheckPerms(MeOrBot who = MeOrBot.Me) public async Task CheckPerms(MeOrBot who = MeOrBot.Me)
{ {
StringBuilder builder = new StringBuilder(); var builder = new StringBuilder();
var user = who == MeOrBot.Me var user = who == MeOrBot.Me
? (IGuildUser)ctx.User ? (IGuildUser)ctx.User
: ((SocketGuild)ctx.Guild).CurrentUser; : ((SocketGuild)ctx.Guild).CurrentUser;

View File

@@ -62,7 +62,7 @@ public partial class Xp
return; return;
} }
if (!_service.CreateClub(ctx.User, clubName, out ClubInfo club)) if (!_service.CreateClub(ctx.User, clubName, out var club))
{ {
await ReplyErrorLocalizedAsync(strs.club_create_error).ConfigureAwait(false); await ReplyErrorLocalizedAsync(strs.club_create_error).ConfigureAwait(false);
return; return;
@@ -109,7 +109,7 @@ public partial class Xp
return; return;
} }
if (!_service.GetClubByName(clubName, out ClubInfo club)) if (!_service.GetClubByName(clubName, out var club))
{ {
await ReplyErrorLocalizedAsync(strs.club_not_exists).ConfigureAwait(false); await ReplyErrorLocalizedAsync(strs.club_not_exists).ConfigureAwait(false);
return; return;
@@ -226,7 +226,7 @@ public partial class Xp
if (string.IsNullOrWhiteSpace(clubName)) if (string.IsNullOrWhiteSpace(clubName))
return; return;
if (!_service.GetClubByName(clubName, out ClubInfo club)) if (!_service.GetClubByName(clubName, out var club))
{ {
await ReplyErrorLocalizedAsync(strs.club_not_exists).ConfigureAwait(false); await ReplyErrorLocalizedAsync(strs.club_not_exists).ConfigureAwait(false);
return; return;
@@ -345,7 +345,7 @@ public partial class Xp
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
public async Task ClubDisband() public async Task ClubDisband()
{ {
if (_service.Disband(ctx.User.Id, out ClubInfo club)) if (_service.Disband(ctx.User.Id, out var club))
{ {
await ReplyConfirmLocalizedAsync(strs.club_disbanded(Format.Bold(club.ToString()))); await ReplyConfirmLocalizedAsync(strs.club_disbanded(Format.Bold(club.ToString())));
} }

View File

@@ -339,7 +339,7 @@ public partial class Xp : NadekoModule<XpService>
await ctx.Channel.TriggerTypingAsync(); await ctx.Channel.TriggerTypingAsync();
var socketGuild = ((SocketGuild)ctx.Guild); var socketGuild = ((SocketGuild)ctx.Guild);
List<UserXpStats> allUsers = new List<UserXpStats>(); var allUsers = new List<UserXpStats>();
if (opts.Clean) if (opts.Clean)
{ {
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false); await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
@@ -370,14 +370,14 @@ public partial class Xp : NadekoModule<XpService>
return embed.WithDescription("-"); return embed.WithDescription("-");
else else
{ {
for (int i = 0; i < users.Count; i++) for (var i = 0; i < users.Count; i++)
{ {
var levelStats = new LevelStats(users[i].Xp + users[i].AwardedXp); var levelStats = new LevelStats(users[i].Xp + users[i].AwardedXp);
var user = ((SocketGuild)ctx.Guild).GetUser(users[i].UserId); var user = ((SocketGuild)ctx.Guild).GetUser(users[i].UserId);
var userXpData = users[i]; var userXpData = users[i];
var awardStr = ""; var awardStr = string.Empty;
if (userXpData.AwardedXp > 0) if (userXpData.AwardedXp > 0)
awardStr = $"(+{userXpData.AwardedXp})"; awardStr = $"(+{userXpData.AwardedXp})";
else if (userXpData.AwardedXp < 0) else if (userXpData.AwardedXp < 0)
@@ -408,7 +408,7 @@ public partial class Xp : NadekoModule<XpService>
embed.WithDescription("-"); embed.WithDescription("-");
else else
{ {
for (int i = 0; i < users.Length; i++) for (var i = 0; i < users.Length; i++)
{ {
var user = users[i]; var user = users[i];
embed.AddField( embed.AddField(

View File

@@ -94,9 +94,9 @@ public class CurrencyService : ICurrencyService, INService
public async Task AddBulkAsync(IEnumerable<ulong> userIds, IEnumerable<string> reasons, IEnumerable<long> amounts, bool gamble = false) public async Task AddBulkAsync(IEnumerable<ulong> userIds, IEnumerable<string> reasons, IEnumerable<long> amounts, bool gamble = false)
{ {
ulong[] idArray = userIds as ulong[] ?? userIds.ToArray(); var idArray = userIds as ulong[] ?? userIds.ToArray();
string[] reasonArray = reasons as string[] ?? reasons.ToArray(); var reasonArray = reasons as string[] ?? reasons.ToArray();
long[] amountArray = amounts as long[] ?? amounts.ToArray(); var amountArray = amounts as long[] ?? amounts.ToArray();
if (idArray.Length != reasonArray.Length || reasonArray.Length != amountArray.Length) if (idArray.Length != reasonArray.Length || reasonArray.Length != amountArray.Length)
throw new ArgumentException("Cannot perform bulk operation. Arrays are not of equal length."); throw new ArgumentException("Cannot perform bulk operation. Arrays are not of equal length.");
@@ -104,7 +104,7 @@ public class CurrencyService : ICurrencyService, INService
var userIdHashSet = new HashSet<ulong>(idArray.Length); var userIdHashSet = new HashSet<ulong>(idArray.Length);
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
for (int i = 0; i < idArray.Length; i++) for (var i = 0; i < idArray.Length; i++)
{ {
// i have to prevent same user changing more than once as it will cause db error // i have to prevent same user changing more than once as it will cause db error
if (userIdHashSet.Add(idArray[i])) if (userIdHashSet.Add(idArray[i]))
@@ -126,7 +126,7 @@ public class CurrencyService : ICurrencyService, INService
var userIdHashSet = new HashSet<ulong>(idArray.Length); var userIdHashSet = new HashSet<ulong>(idArray.Length);
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
for (int i = 0; i < idArray.Length; i++) for (var i = 0; i < idArray.Length; i++)
{ {
// i have to prevent same user changing more than once as it will cause db error // i have to prevent same user changing more than once as it will cause db error
if (userIdHashSet.Add(idArray[i])) if (userIdHashSet.Add(idArray[i]))

View File

@@ -23,7 +23,7 @@ public class FontProvider : INService
{ {
try try
{ {
string fontsfolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Fonts); var fontsfolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Fonts);
FallBackFonts.Add(_fonts.Install(Path.Combine(fontsfolder, "seguiemj.ttf"))); FallBackFonts.Add(_fonts.Install(Path.Combine(fontsfolder, "seguiemj.ttf")));
FallBackFonts.AddRange(_fonts.InstallCollection(Path.Combine(fontsfolder, "msgothic.ttc"))); FallBackFonts.AddRange(_fonts.InstallCollection(Path.Combine(fontsfolder, "msgothic.ttc")));
FallBackFonts.AddRange(_fonts.InstallCollection(Path.Combine(fontsfolder, "segoe.ttc"))); FallBackFonts.AddRange(_fonts.InstallCollection(Path.Combine(fontsfolder, "segoe.ttc")));

View File

@@ -151,7 +151,7 @@ public class GoogleApiService : IGoogleApiService, INService
string nextPageToken = null; string nextPageToken = null;
List<string> toReturn = new List<string>(count); var toReturn = new List<string>(count);
do do
{ {
@@ -178,7 +178,7 @@ public class GoogleApiService : IGoogleApiService, INService
await Task.Yield(); await Task.Yield();
var videoIdsList = videoIds as List<string> ?? videoIds.ToList(); var videoIdsList = videoIds as List<string> ?? videoIds.ToList();
Dictionary<string, TimeSpan> toReturn = new Dictionary<string, TimeSpan>(); var toReturn = new Dictionary<string, TimeSpan>();
if (!videoIdsList.Any()) if (!videoIdsList.Any())
return toReturn; return toReturn;

View File

@@ -174,7 +174,7 @@ public class RedisCache : IDataCache
{ {
var _db = Redis.GetDatabase(); var _db = Redis.GetDatabase();
RedisValue data = await _db.StringGetAsync(key).ConfigureAwait(false); var data = await _db.StringGetAsync(key).ConfigureAwait(false);
if (!data.HasValue) if (!data.HasValue)
{ {
var obj = await factory(param).ConfigureAwait(false); var obj = await factory(param).ConfigureAwait(false);

View File

@@ -21,7 +21,7 @@ public sealed class RedisImagesCache : IImageCache, IReadyExecutor
private IDatabase _db => _con.GetDatabase(); private IDatabase _db => _con.GetDatabase();
private const string _basePath = "data/"; private const string _basePath = "data/";
private const string _cardsPath = "data/images/cards"; private const string _cardsPath = $"{_basePath}images/cards";
public ImageUrls ImageUrls { get; private set; } public ImageUrls ImageUrls { get; private set; }

View File

@@ -18,7 +18,7 @@ public class SoundCloudApiService : INService
if (string.IsNullOrWhiteSpace(url)) if (string.IsNullOrWhiteSpace(url))
throw new ArgumentNullException(nameof(url)); throw new ArgumentNullException(nameof(url));
string response = ""; var response = string.Empty;
using (var http = _httpFactory.CreateClient()) using (var http = _httpFactory.CreateClient())
{ {
@@ -37,7 +37,7 @@ public class SoundCloudApiService : INService
if (string.IsNullOrWhiteSpace(query)) if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query)); throw new ArgumentNullException(nameof(query));
var response = ""; var response = string.Empty;
using (var http = _httpFactory.CreateClient()) using (var http = _httpFactory.CreateClient())
{ {
response = await http.GetStringAsync(new Uri($"https://scapi.nadeko.bot/tracks?q={Uri.EscapeDataString(query)}")).ConfigureAwait(false); response = await http.GetStringAsync(new Uri($"https://scapi.nadeko.bot/tracks?q={Uri.EscapeDataString(query)}")).ConfigureAwait(false);
@@ -55,17 +55,17 @@ public class SoundCloudApiService : INService
public class SoundCloudVideo public class SoundCloudVideo
{ {
public string Kind { get; set; } = ""; public string Kind { get; set; } = string.Empty;
public long Id { get; set; } = 0; public long Id { get; set; } = 0;
public SoundCloudUser User { get; set; } = new SoundCloudUser(); public SoundCloudUser User { get; set; } = new SoundCloudUser();
public string Title { get; set; } = ""; public string Title { get; set; } = string.Empty;
public string FullName => User.Name + " - " + Title; public string FullName => User.Name + " - " + Title;
public bool? Streamable { get; set; } = false; public bool? Streamable { get; set; } = false;
public int Duration { get; set; } public int Duration { get; set; }
[JsonProperty("permalink_url")] [JsonProperty("permalink_url")]
public string TrackLink { get; set; } = ""; public string TrackLink { get; set; } = string.Empty;
[JsonProperty("artwork_url")] [JsonProperty("artwork_url")]
public string ArtworkUrl { get; set; } = ""; public string ArtworkUrl { get; set; } = string.Empty;
} }
public class SoundCloudUser public class SoundCloudUser

View File

@@ -103,8 +103,8 @@ public static class Extensions
// https://github.com/SixLabors/Samples/blob/master/ImageSharp/AvatarWithRoundedCorner/Program.cs // https://github.com/SixLabors/Samples/blob/master/ImageSharp/AvatarWithRoundedCorner/Program.cs
public static IImageProcessingContext ApplyRoundedCorners(this IImageProcessingContext ctx, float cornerRadius) public static IImageProcessingContext ApplyRoundedCorners(this IImageProcessingContext ctx, float cornerRadius)
{ {
Size size = ctx.GetCurrentSize(); var size = ctx.GetCurrentSize();
IPathCollection corners = BuildCorners(size.Width, size.Height, cornerRadius); var corners = BuildCorners(size.Width, size.Height, cornerRadius);
ctx.SetGraphicsOptions(new GraphicsOptions() ctx.SetGraphicsOptions(new GraphicsOptions()
{ {
@@ -125,18 +125,18 @@ public static class Extensions
var rect = new RectangularPolygon(-0.5f, -0.5f, cornerRadius, cornerRadius); var rect = new RectangularPolygon(-0.5f, -0.5f, cornerRadius, cornerRadius);
// then cut out of the square a circle so we are left with a corner // then cut out of the square a circle so we are left with a corner
IPath cornerTopLeft = rect.Clip(new EllipsePolygon(cornerRadius - 0.5f, cornerRadius - 0.5f, cornerRadius)); var cornerTopLeft = rect.Clip(new EllipsePolygon(cornerRadius - 0.5f, cornerRadius - 0.5f, cornerRadius));
// corner is now a corner shape positions top left // corner is now a corner shape positions top left
//lets make 3 more positioned correctly, we can do that by translating the original around the center of the image //lets make 3 more positioned correctly, we can do that by translating the original around the center of the image
float rightPos = imageWidth - cornerTopLeft.Bounds.Width + 1; var rightPos = imageWidth - cornerTopLeft.Bounds.Width + 1;
float bottomPos = imageHeight - cornerTopLeft.Bounds.Height + 1; var bottomPos = imageHeight - cornerTopLeft.Bounds.Height + 1;
// move it across the width of the image - the width of the shape // move it across the width of the image - the width of the shape
IPath cornerTopRight = cornerTopLeft.RotateDegree(90).Translate(rightPos, 0); var cornerTopRight = cornerTopLeft.RotateDegree(90).Translate(rightPos, 0);
IPath cornerBottomLeft = cornerTopLeft.RotateDegree(-90).Translate(0, bottomPos); var cornerBottomLeft = cornerTopLeft.RotateDegree(-90).Translate(0, bottomPos);
IPath cornerBottomRight = cornerTopLeft.RotateDegree(180).Translate(rightPos, bottomPos); var cornerBottomRight = cornerTopLeft.RotateDegree(180).Translate(rightPos, bottomPos);
return new PathCollection(cornerTopLeft, cornerBottomLeft, cornerTopRight, cornerBottomRight); return new PathCollection(cornerTopLeft, cornerBottomLeft, cornerTopRight, cornerBottomRight);
} }

View File

@@ -11,8 +11,8 @@ public static class StringExtensions
{ {
public static string PadBoth(this string str, int length) public static string PadBoth(this string str, int length)
{ {
int spaces = length - str.Length; var spaces = length - str.Length;
int padLeft = spaces / 2 + str.Length; var padLeft = spaces / 2 + str.Length;
return str.PadLeft(padLeft).PadRight(length); return str.PadLeft(padLeft).PadRight(length);
} }

View File

@@ -22,7 +22,7 @@ namespace Ayu.Discord.Gateway
var bufferWriter = new ArrayBufferWriter<byte>(CHUNK_SIZE); var bufferWriter = new ArrayBufferWriter<byte>(CHUNK_SIZE);
try try
{ {
using (_ws = new ClientWebSocket()) using (_ws = new())
{ {
await _ws.ConnectAsync(url, cancel).ConfigureAwait(false); await _ws.ConnectAsync(url, cancel).ConfigureAwait(false);
// WebsocketConnected!.Invoke(this); // WebsocketConnected!.Invoke(this);
@@ -94,10 +94,10 @@ namespace Ayu.Discord.Gateway
var ws = _ws; var ws = _ws;
if (ws is null) if (ws is null)
throw new WebSocketException("Websocket is disconnected."); throw new WebSocketException("Websocket is disconnected.");
for (int i = 0; i < data.Length; i += 4096) for (var i = 0; i < data.Length; i += 4096)
{ {
var count = i + 4096 > data.Length ? data.Length - i : 4096; var count = i + 4096 > data.Length ? data.Length - i : 4096;
await ws.SendAsync(new ArraySegment<byte>(data, i, count), await ws.SendAsync(new(data, i, count),
WebSocketMessageType.Text, WebSocketMessageType.Text,
i + count >= data.Length, i + count >= data.Length,
CancellationToken.None).ConfigureAwait(false); CancellationToken.None).ConfigureAwait(false);
@@ -115,7 +115,7 @@ namespace Ayu.Discord.Gateway
if (ws is null) if (ws is null)
throw new WebSocketException("Websocket is disconnected."); throw new WebSocketException("Websocket is disconnected.");
await ws.SendAsync(new ArraySegment<byte>(data, 0, data.Length), await ws.SendAsync(new(data, 0, data.Length),
WebSocketMessageType.Binary, WebSocketMessageType.Binary,
true, true,
CancellationToken.None).ConfigureAwait(false); CancellationToken.None).ConfigureAwait(false);

View File

@@ -37,7 +37,7 @@ namespace Ayu.Discord.Voice
this.channels = (int) channels; this.channels = (int) channels;
this.bitDepth = (int) bitDepthEnum; this.bitDepth = (int) bitDepthEnum;
this.Encoder = new LibOpusEncoder(this.sampleRate, this.channels, this.bitRate, this.frameDelay); this.Encoder = new(this.sampleRate, this.channels, this.bitRate, this.frameDelay);
Encode = bitDepthEnum switch Encode = bitDepthEnum switch
{ {

View File

@@ -46,14 +46,14 @@ namespace Ayu.Discord.Voice
private IPEndPoint? _udpEp; private IPEndPoint? _udpEp;
public uint Ssrc { get; private set; } public uint Ssrc { get; private set; }
public string Ip { get; private set; } = ""; public string Ip { get; private set; } = string.Empty;
public int Port { get; private set; } = 0; public int Port { get; private set; } = 0;
public byte[] SecretKey { get; private set; } = Array.Empty<byte>(); public byte[] SecretKey { get; private set; } = Array.Empty<byte>();
public string Mode { get; private set; } = ""; public string Mode { get; private set; } = string.Empty;
public ushort Sequence { get; set; } public ushort Sequence { get; set; }
public uint NonceSequence { get; set; } public uint NonceSequence { get; set; }
public uint Timestamp { get; set; } public uint Timestamp { get; set; }
public string MyIp { get; private set; } = ""; public string MyIp { get; private set; } = string.Empty;
public ushort MyPort { get; private set; } public ushort MyPort { get; private set; }
private bool shouldResume = false; private bool shouldResume = false;
@@ -74,21 +74,21 @@ namespace Ayu.Discord.Voice
//Log.Information("g: {GuildId} u: {UserId} sess: {Session} tok: {Token} ep: {Endpoint}", //Log.Information("g: {GuildId} u: {UserId} sess: {Session} tok: {Token} ep: {Endpoint}",
// guildId, userId, session, token, endpoint); // guildId, userId, session, token, endpoint);
this._websocketUrl = new Uri($"wss://{_endpoint.Replace(":80", "")}?v=4"); this._websocketUrl = new($"wss://{_endpoint.Replace(":80", "")}?v=4");
this._channel = Channel.CreateUnbounded<QueueItem>(new UnboundedChannelOptions this._channel = Channel.CreateUnbounded<QueueItem>(new()
{ {
SingleReader = true, SingleReader = true,
SingleWriter = false, SingleWriter = false,
AllowSynchronousContinuations = false, AllowSynchronousContinuations = false,
}); });
ConnectingFinished = new TaskCompletionSource<bool>(); ConnectingFinished = new();
_rng = new Random(); _rng = new();
_ws = new SocketClient(); _ws = new();
_udpClient = new UdpClient(); _udpClient = new();
_stopCancellationSource = new CancellationTokenSource(); _stopCancellationSource = new();
_stopCancellationToken = _stopCancellationSource.Token; _stopCancellationToken = _stopCancellationSource.Token;
_ws.PayloadReceived += _ws_PayloadReceived; _ws.PayloadReceived += _ws_PayloadReceived;
@@ -216,7 +216,7 @@ namespace Ayu.Discord.Voice
private Task ResumeAsync() private Task ResumeAsync()
{ {
shouldResume = false; shouldResume = false;
return SendCommandPayloadAsync(new VoicePayload return SendCommandPayloadAsync(new()
{ {
OpCode = VoiceOpCode.Resume, OpCode = VoiceOpCode.Resume,
Data = JToken.FromObject(new VoiceResume Data = JToken.FromObject(new VoiceResume
@@ -234,7 +234,7 @@ namespace Ayu.Discord.Voice
//Log.Information("Received ready {GuildId}, {Session}, {Token}", guildId, session, token); //Log.Information("Received ready {GuildId}, {Session}, {Token}", guildId, session, token);
_udpEp = new IPEndPoint(IPAddress.Parse(ready.Ip), ready.Port); _udpEp = new(IPAddress.Parse(ready.Ip), ready.Port);
var ssrcBytes = BitConverter.GetBytes(Ssrc); var ssrcBytes = BitConverter.GetBytes(Ssrc);
var ipDiscoveryData = new byte[70]; var ipDiscoveryData = new byte[70];
@@ -265,7 +265,7 @@ namespace Ayu.Discord.Voice
private Task HandleHelloAsync(VoiceHello data) private Task HandleHelloAsync(VoiceHello data)
{ {
_receivedAck = true; _receivedAck = true;
_heartbeatTimer = new Timer(async _ => _heartbeatTimer = new(async _ =>
{ {
await SendHeartbeatAsync(); await SendHeartbeatAsync();
}, default, data.HeartbeatInterval, data.HeartbeatInterval); }, default, data.HeartbeatInterval, data.HeartbeatInterval);
@@ -279,7 +279,7 @@ namespace Ayu.Discord.Voice
} }
private Task IdentifyAsync() private Task IdentifyAsync()
=> SendCommandPayloadAsync(new VoicePayload => SendCommandPayloadAsync(new()
{ {
OpCode = VoiceOpCode.Identify, OpCode = VoiceOpCode.Identify,
Data = JToken.FromObject(new VoiceIdentify Data = JToken.FromObject(new VoiceIdentify
@@ -292,13 +292,13 @@ namespace Ayu.Discord.Voice
}); });
private Task SelectProtocol() private Task SelectProtocol()
=> SendCommandPayloadAsync(new VoicePayload => SendCommandPayloadAsync(new()
{ {
OpCode = VoiceOpCode.SelectProtocol, OpCode = VoiceOpCode.SelectProtocol,
Data = JToken.FromObject(new SelectProtocol Data = JToken.FromObject(new SelectProtocol
{ {
Protocol = "udp", Protocol = "udp",
Data = new SelectProtocol.ProtocolData() Data = new()
{ {
Address = MyIp, Address = MyIp,
Port = MyPort, Port = MyPort,
@@ -319,7 +319,7 @@ namespace Ayu.Discord.Voice
} }
_receivedAck = false; _receivedAck = false;
await SendCommandPayloadAsync(new VoicePayload await SendCommandPayloadAsync(new()
{ {
OpCode = VoiceOpCode.Heartbeat, OpCode = VoiceOpCode.Heartbeat,
Data = JToken.FromObject(_rng.Next()) Data = JToken.FromObject(_rng.Next())
@@ -327,7 +327,7 @@ namespace Ayu.Discord.Voice
} }
public Task SendSpeakingAsync(VoiceSpeaking.State speaking) public Task SendSpeakingAsync(VoiceSpeaking.State speaking)
=> SendCommandPayloadAsync(new VoicePayload => SendCommandPayloadAsync(new()
{ {
OpCode = VoiceOpCode.Speaking, OpCode = VoiceOpCode.Speaking,
Data = JToken.FromObject(new VoiceSpeaking Data = JToken.FromObject(new VoiceSpeaking