From 29c2bef51a1e09719ced0f391db64b7923165bb1 Mon Sep 17 00:00:00 2001 From: 13xforever Date: Sun, 9 Mar 2025 10:25:55 +0500 Subject: [PATCH] update namespaces and some enums --- CompatBot/Commands/BaseCommandModuleCustom.cs | 4 +-- CompatBot/Commands/ContentFilters.cs | 18 +++++----- CompatBot/Commands/EventsBaseCommand.cs | 10 +++--- CompatBot/Commands/Explain.cs | 4 +-- CompatBot/Commands/Misc.cs | 2 +- CompatBot/Commands/Psn.Check.cs | 6 ++-- CompatBot/Commands/Warnings.ListGroup.cs | 2 +- CompatBot/Database/Providers/ModProvider.cs | 2 +- .../EventHandlers/BotReactionsHandler.cs | 2 +- CompatBot/EventHandlers/BotStatusMonitor.cs | 4 +-- .../EventHandlers/DeletedMessagesMonitor.cs | 2 +- .../EventHandlers/DiscordInviteFilter.cs | 6 ++-- CompatBot/EventHandlers/GlobalMessageCache.cs | 25 +++++++------ CompatBot/EventHandlers/LogParsingHandler.cs | 2 +- CompatBot/EventHandlers/ProductCodeLookup.cs | 21 ++--------- CompatBot/EventHandlers/Starbucks.cs | 6 ++-- .../EventHandlers/UnknownCommandHandler.cs | 10 +++--- .../UsernameValidationMonitor.cs | 4 +-- CompatBot/Properties/GlobalSuppressions.cs | 6 ++-- CompatBot/Utils/DefaultHandlerFilter.cs | 8 ----- .../Extensions/CommandContextExtensions.cs | 36 +++++++++++++------ .../Extensions/DiscordClientExtensions.cs | 32 +++++++++++++---- .../Extensions/DiscordGuildExtensions.cs | 4 +-- .../Extensions/DiscordMessageExtensions.cs | 2 +- .../Utils/Extensions/EnumerableExtensions.cs | 9 ++++- .../Extensions/InteractivityExtensions.cs | 12 +++---- CompatBot/Watchdog.cs | 19 +++++++--- SourceGenerators/AttributeUsageAnalyzer.cs | 4 +-- 28 files changed, 146 insertions(+), 116 deletions(-) diff --git a/CompatBot/Commands/BaseCommandModuleCustom.cs b/CompatBot/Commands/BaseCommandModuleCustom.cs index e3904598..b52f6861 100644 --- a/CompatBot/Commands/BaseCommandModuleCustom.cs +++ b/CompatBot/Commands/BaseCommandModuleCustom.cs @@ -35,7 +35,7 @@ internal class BaseCommandModuleCustom : BaseCommandModule await dm.SendMessageAsync($"Only `{Config.CommandPrefix}warn` and `{Config.CommandPrefix}report` are allowed in {ctx.Channel.Mention}").ConfigureAwait(false); } Config.TelemetryClient?.TrackRequest(ctx.Command.QualifiedName, executionStart, DateTimeOffset.UtcNow - executionStart, HttpStatusCode.Forbidden.ToString(), true); - throw new DSharpPlus.CommandsNext.Exceptions.ChecksFailedException(ctx.Command, ctx, [new RequiresNotMedia() + throw new DSharpPlus.Commands.Exceptions.ChecksFailedException(ctx.Command, ctx, [new RequiresNotMedia() ]); } @@ -44,7 +44,7 @@ internal class BaseCommandModuleCustom : BaseCommandModule { await ctx.Channel.SendMessageAsync(embed: new DiscordEmbedBuilder {Color = Config.Colors.Maintenance, Description = "Command is currently disabled"}).ConfigureAwait(false); Config.TelemetryClient?.TrackRequest(ctx.Command.QualifiedName, executionStart, DateTimeOffset.UtcNow - executionStart, HttpStatusCode.Locked.ToString(), true); - throw new DSharpPlus.CommandsNext.Exceptions.ChecksFailedException(ctx.Command, ctx, [new RequiresDm()]); + throw new DSharpPlus.Commands.Exceptions.ChecksFailedException(ctx.Command, ctx, [new RequiresDm()]); } if (TriggersTyping(ctx)) diff --git a/CompatBot/Commands/ContentFilters.cs b/CompatBot/Commands/ContentFilters.cs index 29975e93..ab8402c1 100644 --- a/CompatBot/Commands/ContentFilters.cs +++ b/CompatBot/Commands/ContentFilters.cs @@ -263,7 +263,7 @@ internal sealed partial class ContentFilters: BaseCommandModuleCustom return; } - await ctx.Channel.SendMessageAsync(new DiscordMessageBuilder().WithEmbed(FormatFilter(filter))).ConfigureAwait(false); + await ctx.Channel.SendMessageAsync(new DiscordMessageBuilder().AddEmbed(FormatFilter(filter))).ConfigureAwait(false); } [Command("view")] @@ -278,7 +278,7 @@ internal sealed partial class ContentFilters: BaseCommandModuleCustom return; } - await ctx.Channel.SendMessageAsync(new DiscordMessageBuilder().WithEmbed(FormatFilter(filter))).ConfigureAwait(false); + await ctx.Channel.SendMessageAsync(new DiscordMessageBuilder().AddEmbed(FormatFilter(filter))).ConfigureAwait(false); } [Command("remove"), Aliases("delete", "del")] @@ -408,7 +408,7 @@ internal sealed partial class ContentFilters: BaseCommandModuleCustom saveEdit.SetEnabled(filter.IsComplete()); var messageBuilder = new DiscordMessageBuilder() .WithContent("Please specify a new **trigger**") - .WithEmbed(embed) + .AddEmbed(embed) .AddComponents(lastPage, nextPage, saveEdit, abort); errorMsg = null; msg = await msg.UpdateOrCreateMessageAsync(ctx.Channel, messageBuilder).ConfigureAwait(false); @@ -459,7 +459,7 @@ internal sealed partial class ContentFilters: BaseCommandModuleCustom contextLog.SetEmoji(filter.Context.HasFlag(FilterContext.Log) ? minus : plus); messageBuilder = new DiscordMessageBuilder() .WithContent("Please specify filter **context(s)**") - .WithEmbed(embed) + .AddEmbed(embed) .AddComponents(previousPage, nextPage, saveEdit, abort) .AddComponents(contextChat, contextLog); errorMsg = null; @@ -543,7 +543,7 @@ internal sealed partial class ContentFilters: BaseCommandModuleCustom saveEdit.SetEnabled(filter.IsComplete()); messageBuilder = new DiscordMessageBuilder() .WithContent("Please specify filter **action(s)**") - .WithEmbed(embed) + .AddEmbed(embed) .AddComponents(previousPage, nextPage, saveEdit, abort) .AddComponents(actionR, actionW, actionM, actionE, actionU) .AddComponents(actionK); @@ -671,7 +671,7 @@ internal sealed partial class ContentFilters: BaseCommandModuleCustom saveEdit.SetEnabled(filter.IsComplete()); messageBuilder = new DiscordMessageBuilder() .WithContent("Please specify filter **validation regex**") - .WithEmbed(embed) + .AddEmbed(embed) .AddComponents(previousPage, next, trash, saveEdit, abort); errorMsg = null; msg = await msg.UpdateOrCreateMessageAsync(ctx.Channel, messageBuilder).ConfigureAwait(false); @@ -738,7 +738,7 @@ internal sealed partial class ContentFilters: BaseCommandModuleCustom saveEdit.SetEnabled(filter.IsComplete()); messageBuilder = new DiscordMessageBuilder() .WithContent("Please specify filter **validation regex**") - .WithEmbed(embed) + .AddEmbed(embed) .AddComponents(previousPage, next, saveEdit, abort); errorMsg = null; msg = await msg.UpdateOrCreateMessageAsync(ctx.Channel, messageBuilder).ConfigureAwait(false); @@ -782,7 +782,7 @@ internal sealed partial class ContentFilters: BaseCommandModuleCustom saveEdit.SetEnabled(filter.IsComplete()); messageBuilder = new DiscordMessageBuilder() .WithContent("Please specify filter **explanation term**") - .WithEmbed(embed) + .AddEmbed(embed) .AddComponents(previousPage, firstPage, saveEdit, abort); errorMsg = null; msg = await msg.UpdateOrCreateMessageAsync(ctx.Channel, messageBuilder).ConfigureAwait(false); @@ -833,7 +833,7 @@ internal sealed partial class ContentFilters: BaseCommandModuleCustom saveEdit.SetEnabled(filter.IsComplete()); messageBuilder = new DiscordMessageBuilder() .WithContent("Does this look good? (y/n)") - .WithEmbed(FormatFilter(filter, errorMsg)) + .AddEmbed(FormatFilter(filter, errorMsg)) .AddComponents(previousPage, firstPage, saveEdit, abort); errorMsg = null; msg = await msg.UpdateOrCreateMessageAsync(ctx.Channel, messageBuilder).ConfigureAwait(false); diff --git a/CompatBot/Commands/EventsBaseCommand.cs b/CompatBot/Commands/EventsBaseCommand.cs index 500a178c..e8f48a8f 100644 --- a/CompatBot/Commands/EventsBaseCommand.cs +++ b/CompatBot/Commands/EventsBaseCommand.cs @@ -291,7 +291,7 @@ internal partial class EventsBaseCommand: BaseCommandModuleCustom saveEdit.SetEnabled(evt.IsComplete()); messageBuilder = new DiscordMessageBuilder() .WithContent("Please specify a new **start date and time**") - .WithEmbed(FormatEvent(evt, errorMsg, 1).WithDescription($""" + .AddEmbed(FormatEvent(evt, errorMsg, 1).WithDescription($""" Example: `{DateTime.UtcNow:yyyy-MM-dd HH:mm}` By default all times use UTC, only limited number of time zones supported """)) @@ -334,7 +334,7 @@ internal partial class EventsBaseCommand: BaseCommandModuleCustom saveEdit.SetEnabled(evt.IsComplete()); messageBuilder = new DiscordMessageBuilder() .WithContent("Please specify a new **event duration**") - .WithEmbed(FormatEvent(evt, errorMsg, 2).WithDescription("Example: `2d 1h 15m`, or `2.1:00`")) + .AddEmbed(FormatEvent(evt, errorMsg, 2).WithDescription("Example: `2d 1h 15m`, or `2.1:00`")) .AddComponents(previousPage, nextPage) .AddComponents(saveEdit, abort); errorMsg = null; @@ -374,7 +374,7 @@ internal partial class EventsBaseCommand: BaseCommandModuleCustom trash.SetDisabled(string.IsNullOrEmpty(evt.EventName)); messageBuilder = new DiscordMessageBuilder() .WithContent("Please specify a new **event name**") - .WithEmbed(FormatEvent(evt, errorMsg, 3)) + .AddEmbed(FormatEvent(evt, errorMsg, 3)) .AddComponents(previousPage, nextPage, trash) .AddComponents(saveEdit, abort); errorMsg = null; @@ -404,7 +404,7 @@ internal partial class EventsBaseCommand: BaseCommandModuleCustom saveEdit.SetEnabled(evt.IsComplete()); messageBuilder = new DiscordMessageBuilder() .WithContent("Please specify a new **schedule entry title**") - .WithEmbed(FormatEvent(evt, errorMsg, 4)) + .AddEmbed(FormatEvent(evt, errorMsg, 4)) .AddComponents(previousPage, firstPage) .AddComponents(saveEdit, abort); errorMsg = null; @@ -448,7 +448,7 @@ internal partial class EventsBaseCommand: BaseCommandModuleCustom saveEdit.SetEnabled(evt.IsComplete()); messageBuilder = new DiscordMessageBuilder() .WithContent("Does this look good? (y/n)") - .WithEmbed(FormatEvent(evt, errorMsg)) + .AddEmbed(FormatEvent(evt, errorMsg)) .AddComponents(previousPage, firstPage) .AddComponents(saveEdit, abort); errorMsg = null; diff --git a/CompatBot/Commands/Explain.cs b/CompatBot/Commands/Explain.cs index 1c87cee2..9f04fb3c 100644 --- a/CompatBot/Commands/Explain.cs +++ b/CompatBot/Commands/Explain.cs @@ -9,9 +9,9 @@ using CompatBot.Commands.Attributes; using CompatBot.Database; using CompatBot.Database.Providers; using CompatBot.EventHandlers; -using DSharpPlus.CommandsNext.Converters; +using DSharpPlus.Commands.Converters; using Microsoft.EntityFrameworkCore; -using Description = DSharpPlus.CommandsNext.Attributes.DescriptionAttribute; +using Description = DSharpPlus.Commands.Attributes.DescriptionAttribute; namespace CompatBot.Commands; diff --git a/CompatBot/Commands/Misc.cs b/CompatBot/Commands/Misc.cs index 77ecb5aa..91156955 100644 --- a/CompatBot/Commands/Misc.cs +++ b/CompatBot/Commands/Misc.cs @@ -200,7 +200,7 @@ internal sealed partial class Misc: BaseCommandModuleCustom if (string.IsNullOrEmpty(result) && embed == null) await message.ReactWithAsync(DiscordEmoji.FromUnicode("💩"), "Invalid dice description passed").ConfigureAwait(false); else if (embed != null) - await message.Channel.SendMessageAsync(new DiscordMessageBuilder().WithEmbed(embed).WithReply(message.Id)).ConfigureAwait(false); + await message.Channel.SendMessageAsync(new DiscordMessageBuilder().AddEmbed(embed).WithReply(message.Id)).ConfigureAwait(false); else await message.Channel.SendMessageAsync(new DiscordMessageBuilder().WithContent(result).WithReply(message.Id)).ConfigureAwait(false); } diff --git a/CompatBot/Commands/Psn.Check.cs b/CompatBot/Commands/Psn.Check.cs index e799c5bf..2e40e133 100644 --- a/CompatBot/Commands/Psn.Check.cs +++ b/CompatBot/Commands/Psn.Check.cs @@ -124,13 +124,13 @@ internal sealed partial class Psn await ctx.Message.ReactWithAsync(sqvat).ConfigureAwait(false); } var resultMsgBuilder = new DiscordMessageBuilder() - .WithEmbed(embeds[0]) + .AddEmbed(embeds[0]) .WithReply(ctx.Message.Id); await botMsg.UpdateOrCreateMessageAsync(ctx.Channel, resultMsgBuilder).ConfigureAwait(false); foreach (var embed in embeds.Skip(1)) { resultMsgBuilder = new DiscordMessageBuilder() - .WithEmbed(embed) + .AddEmbed(embed) .WithReply(ctx.Message.Id); await ctx.Channel.SendMessageAsync(resultMsgBuilder).ConfigureAwait(false); } @@ -208,7 +208,7 @@ internal sealed partial class Psn } } - internal static async Task OnCheckUpdatesButtonClick(DiscordClient client, ComponentInteractionCreateEventArgs e) + internal static async Task OnCheckUpdatesButtonClick(DiscordClient client, ComponentInteractionCreatedEventArgs e) { var btnId = e.Interaction.Data.CustomId; var parts = btnId.Split(':'); diff --git a/CompatBot/Commands/Warnings.ListGroup.cs b/CompatBot/Commands/Warnings.ListGroup.cs index a10c7fe3..e1541368 100644 --- a/CompatBot/Commands/Warnings.ListGroup.cs +++ b/CompatBot/Commands/Warnings.ListGroup.cs @@ -2,7 +2,7 @@ using CompatBot.Commands.Attributes; using CompatBot.Database; using CompatBot.Database.Providers; -using DSharpPlus.CommandsNext.Converters; +using DSharpPlus.Commands.Converters; namespace CompatBot.Commands; diff --git a/CompatBot/Database/Providers/ModProvider.cs b/CompatBot/Database/Providers/ModProvider.cs index e5305d5e..4b5e64e7 100644 --- a/CompatBot/Database/Providers/ModProvider.cs +++ b/CompatBot/Database/Providers/ModProvider.cs @@ -95,7 +95,7 @@ internal static class ModProvider return; var modRole = modRoleList.First().Value; - var members = await guild.GetAllMembersAsync().ConfigureAwait(false); + var members = await guild.GetAllMembersAsync().ToListAsync(); var guildMods = members.Where(m => m.Roles.Any(r => r.Id == modRole.Id) && !m.IsBot && !m.IsCurrent).ToList(); foreach (var mod in guildMods) { diff --git a/CompatBot/EventHandlers/BotReactionsHandler.cs b/CompatBot/EventHandlers/BotReactionsHandler.cs index 1997b6dc..534056cf 100644 --- a/CompatBot/EventHandlers/BotReactionsHandler.cs +++ b/CompatBot/EventHandlers/BotReactionsHandler.cs @@ -177,7 +177,7 @@ namespace CompatBot.EventHandlers if (await args.Author.IsSmartlistedAsync(c, args.Message.Channel.Guild).ConfigureAwait(false)) { var botMember = args.Guild?.CurrentMember ?? await c.GetMemberAsync(c.CurrentUser).ConfigureAwait(false); - if (args.Channel.PermissionsFor(botMember).HasPermission(Permissions.ReadMessageHistory)) + if (args.Channel.PermissionsFor(botMember).HasPermission(DiscordPermission.ReadMessageHistory)) { var lastBotMessages = await args.Channel.GetMessagesBeforeAsync(args.Message.Id, 20, DateTime.UtcNow.Add(-Config.ShutupTimeLimitInMin)).ConfigureAwait(false); if (lastBotMessages.OrderByDescending(m => m.CreationTimestamp).FirstOrDefault(m => m.Author.IsCurrent) is DiscordMessage msg) diff --git a/CompatBot/EventHandlers/BotStatusMonitor.cs b/CompatBot/EventHandlers/BotStatusMonitor.cs index dd89403a..525c9cb3 100644 --- a/CompatBot/EventHandlers/BotStatusMonitor.cs +++ b/CompatBot/EventHandlers/BotStatusMonitor.cs @@ -13,9 +13,9 @@ internal static class BotStatusMonitor var status = await db.BotState.FirstOrDefaultAsync(s => s.Key == "bot-status-activity").ConfigureAwait(false); var txt = await db.BotState.FirstOrDefaultAsync(s => s.Key == "bot-status-text").ConfigureAwait(false); var msg = txt?.Value; - if (Enum.TryParse(status?.Value ?? "Watching", true, out ActivityType activity) + if (Enum.TryParse(status?.Value ?? "Watching", true, out DiscordActivityType activity) && !string.IsNullOrEmpty(msg)) - await client.UpdateStatusAsync(new DiscordActivity(msg, activity), UserStatus.Online).ConfigureAwait(false); + await client.UpdateStatusAsync(new DiscordActivity(msg, activity), DiscordUserStatus.Online).ConfigureAwait(false); } catch (Exception e) { diff --git a/CompatBot/EventHandlers/DeletedMessagesMonitor.cs b/CompatBot/EventHandlers/DeletedMessagesMonitor.cs index 54d72ebb..10ae8b76 100644 --- a/CompatBot/EventHandlers/DeletedMessagesMonitor.cs +++ b/CompatBot/EventHandlers/DeletedMessagesMonitor.cs @@ -51,7 +51,7 @@ internal static class DeletedMessagesMonitor await PostLock.WaitAsync().ConfigureAwait(false); try { - await logChannel.SendMessageAsync(new DiscordMessageBuilder().WithEmbed(embed.Build()).WithAllowedMentions(Config.AllowedMentions.Nothing)).ConfigureAwait(false); + await logChannel.SendMessageAsync(new DiscordMessageBuilder().AddEmbed(embed.Build()).WithAllowedMentions(Config.AllowedMentions.Nothing)).ConfigureAwait(false); if (attachmentContent?.Count > 0) await logChannel.SendMessageAsync(new DiscordMessageBuilder().AddFiles(attachmentContent).WithContent(msg.Content).WithAllowedMentions(Config.AllowedMentions.Nothing)).ConfigureAwait(false); else if (!string.IsNullOrEmpty(msg.Content)) diff --git a/CompatBot/EventHandlers/DiscordInviteFilter.cs b/CompatBot/EventHandlers/DiscordInviteFilter.cs index 81d0041a..a4cdf962 100644 --- a/CompatBot/EventHandlers/DiscordInviteFilter.cs +++ b/CompatBot/EventHandlers/DiscordInviteFilter.cs @@ -144,16 +144,16 @@ internal static partial class DiscordInviteFilter } var after = DateTime.UtcNow - Config.ModerationBacklogThresholdInHours; - foreach (var channel in guild.Channels.Values.Where(ch => !ch.IsCategory && ch.Type != ChannelType.Voice)) + foreach (var channel in guild.Channels.Values.Where(ch => !ch.IsCategory && ch.Type != DiscordChannelType.Voice)) { var permissions = channel.PermissionsFor(botMember); - if (!permissions.HasPermission(Permissions.ReadMessageHistory)) + if (!permissions.HasPermission(DiscordPermission.ReadMessageHistory)) { Config.Log.Warn($"No permissions to read message history in #{channel.Name}"); continue; } - if (!permissions.HasPermission(Permissions.AccessChannels)) + if (!permissions.HasPermission(DiscordPermission.ViewChannel)) { Config.Log.Warn($"No permissions to access #{channel.Name}"); continue; diff --git a/CompatBot/EventHandlers/GlobalMessageCache.cs b/CompatBot/EventHandlers/GlobalMessageCache.cs index 237c181c..88047bc1 100644 --- a/CompatBot/EventHandlers/GlobalMessageCache.cs +++ b/CompatBot/EventHandlers/GlobalMessageCache.cs @@ -1,4 +1,6 @@ -using System.Collections.Concurrent; +using System.Linq; +using System.Linq.Expressions; +using System.Collections.Concurrent; using Microsoft.VisualStudio.Services.Common; namespace CompatBot.EventHandlers; @@ -70,7 +72,7 @@ internal static class GlobalMessageCache return Task.CompletedTask; } - internal static Task> GetMessagesCachedAsync(this DiscordChannel ch, int count = 100) + internal static async Task> GetMessagesCachedAsync(this DiscordChannel ch, int count = 100) { if (!MessageQueue.TryGetValue(ch.Id, out var queue)) lock (MessageQueue) @@ -83,11 +85,12 @@ internal static class GlobalMessageCache var fetchCount = Math.Max(count - cacheCount, 0); if (fetchCount > 0) { - IReadOnlyList fetchedList; - if (result.Any()) - fetchedList = ch.GetMessagesBeforeAsync(result[0].Id, fetchCount).ConfigureAwait(false).GetAwaiter().GetResult(); + IAsyncEnumerable fetchStream; + if (result.Count > 0) + fetchStream = ch.GetMessagesBeforeAsync(result[0].Id, fetchCount); else - fetchedList = ch.GetMessagesAsync(fetchCount).ConfigureAwait(false).GetAwaiter().GetResult(); + fetchStream = ch.GetMessagesAsync(fetchCount); + var fetchedList = await fetchStream.ToListAsync(); result.AddRange(fetchedList); if (queue.Count < Config.ChannelMessageHistorySize) lock (queue.SyncObj) @@ -98,10 +101,10 @@ internal static class GlobalMessageCache queue.AddRange(freshCopy.Concat(fetchedList).Distinct().Reverse()); } } - return Task.FromResult(result); + return result; } - internal static Task> GetMessagesBeforeCachedAsync(this DiscordChannel ch, ulong msgId, int count = 100) + internal static async Task> GetMessagesBeforeCachedAsync(this DiscordChannel ch, ulong msgId, int count = 100) { if (!MessageQueue.TryGetValue(ch.Id, out var queue)) lock (MessageQueue) @@ -117,7 +120,7 @@ internal static class GlobalMessageCache IReadOnlyList fetchedList; if (result.Any()) { - fetchedList = ch.GetMessagesBeforeAsync(result[0].Id, fetchCount).ConfigureAwait(false).GetAwaiter().GetResult(); + fetchedList = await ch.GetMessagesBeforeAsync(result[0].Id, fetchCount).ToListAsync(); if (queue.Count < Config.ChannelMessageHistorySize) lock (queue.SyncObj) { @@ -128,10 +131,10 @@ internal static class GlobalMessageCache } } else - fetchedList = ch.GetMessagesBeforeAsync(msgId, fetchCount).ConfigureAwait(false).GetAwaiter().GetResult(); + fetchedList = await ch.GetMessagesBeforeAsync(msgId, fetchCount).ToListAsync(); result.AddRange(fetchedList); } - return Task.FromResult(result); + return result; } } \ No newline at end of file diff --git a/CompatBot/EventHandlers/LogParsingHandler.cs b/CompatBot/EventHandlers/LogParsingHandler.cs index e7297300..5c80c717 100644 --- a/CompatBot/EventHandlers/LogParsingHandler.cs +++ b/CompatBot/EventHandlers/LogParsingHandler.cs @@ -103,7 +103,7 @@ public static class LogParsingHandler Config.Log.Debug($">>>>>>> {message.Id % 100} Parsing log '{source.FileName}' from {message.Author.Username}#{message.Author.Discriminator} ({message.Author.Id}) using {source.GetType().Name} ({source.SourceFileSize} bytes)…"); var analyzingProgressEmbed = GetAnalyzingMsgEmbed(client); var msgBuilder = new DiscordMessageBuilder() - .WithEmbed(await analyzingProgressEmbed.AddAuthorAsync(client, message, source).ConfigureAwait(false)) + .AddEmbed(await analyzingProgressEmbed.AddAuthorAsync(client, message, source).ConfigureAwait(false)) .WithReply(message.Id); botMsg = await channel.SendMessageAsync(msgBuilder).ConfigureAwait(false); parsedLog = true; diff --git a/CompatBot/EventHandlers/ProductCodeLookup.cs b/CompatBot/EventHandlers/ProductCodeLookup.cs index 4501164f..46200641 100644 --- a/CompatBot/EventHandlers/ProductCodeLookup.cs +++ b/CompatBot/EventHandlers/ProductCodeLookup.cs @@ -71,10 +71,9 @@ internal static partial class ProductCodeLookup foreach (var result in formattedResults) try { - await FixAfrikaAsync(client, message, result.builder).ConfigureAwait(false); - var messageBuilder = new DiscordMessageBuilder().WithEmbed(result.builder); + var messageBuilder = new DiscordMessageBuilder().AddEmbed(result.builder); if (LimitedToSpamChannel.IsSpamChannel(channel)) - messageBuilder.AddComponents(new DiscordButtonComponent(ButtonStyle.Secondary, $"replace with game updates:{message.Author.Id}:{message.Id}:{result.code}", "Check for updates", emoji: lookupEmoji)); + messageBuilder.AddComponents(new DiscordButtonComponent(DiscordButtonStyle.Secondary, $"replace with game updates:{message.Author.Id}:{message.Id}:{result.code}", "Check for updates", emoji: lookupEmoji)); await DiscordMessageExtensions.UpdateOrCreateMessageAsync(null, channel, messageBuilder).ConfigureAwait(false); } catch (Exception e) @@ -151,20 +150,4 @@ internal static partial class ProductCodeLookup return (TitleInfo.CommunicationError.AsEmbed(code, gameTitle, forLog, thumbnailUrl), result); } } - - public static async Task FixAfrikaAsync(DiscordClient client, DiscordMessage message, DiscordEmbedBuilder titleInfoEmbed) - { - if (message.IsOnionLike() - && ( - titleInfoEmbed.Title.Contains("africa", StringComparison.InvariantCultureIgnoreCase) - || titleInfoEmbed.Title.Contains("afrika", StringComparison.InvariantCultureIgnoreCase) - )) - { - var sqvat = client.GetEmoji(":sqvat:", Config.Reactions.No)!; - titleInfoEmbed.Title = "How about no (๑•ิཬ•ั๑)"; - if (!string.IsNullOrEmpty(titleInfoEmbed.Thumbnail?.Url)) - titleInfoEmbed.WithThumbnail(Config.ImgSrcNoCompatAbuse); - await message.ReactWithAsync(sqvat).ConfigureAwait(false); - } - } } diff --git a/CompatBot/EventHandlers/Starbucks.cs b/CompatBot/EventHandlers/Starbucks.cs index 0bcbeba2..f3b263ae 100644 --- a/CompatBot/EventHandlers/Starbucks.cs +++ b/CompatBot/EventHandlers/Starbucks.cs @@ -92,7 +92,7 @@ internal static class Starbucks select msg; foreach (var message in messagesToCheck) { - var reactionUsers = await message.GetReactionsAsync(Config.Reactions.Starbucks).ConfigureAwait(false); + var reactionUsers = await message.GetReactionsAsync(Config.Reactions.Starbucks).ToListAsync(); if (reactionUsers.Count > 0) checkTasks.Add(CheckMessageAsync(client, channel, reactionUsers[0], message, Config.Reactions.Starbucks, true)); } @@ -144,7 +144,7 @@ internal static class Starbucks if (await message.Author.IsWhitelistedAsync(client, channel.Guild).ConfigureAwait(false)) return; - var users = await message.GetReactionsAsync(emoji).ConfigureAwait(false); + var users = await message.GetReactionsAsync(emoji).ToListAsync(); if (users.Any(u => u.IsCurrent)) return; @@ -201,7 +201,7 @@ internal static class Starbucks { var bot = await client.GetMemberAsync(channel.Guild, client.CurrentUser).ConfigureAwait(false); var ch = channel.IsPrivate ? channel.Users.FirstOrDefault(u => u.Id != client.CurrentUser.Id)?.Username + "'s DM" : "#" + channel.Name; - if (!channel.PermissionsFor(bot).HasPermission(Permissions.AddReactions)) + if (!channel.PermissionsFor(bot).HasPermission(DiscordPermission.AddReactions)) { Config.Log.Debug($"No permissions to react in {ch}"); return; diff --git a/CompatBot/EventHandlers/UnknownCommandHandler.cs b/CompatBot/EventHandlers/UnknownCommandHandler.cs index 8de0f370..b6bb6879 100644 --- a/CompatBot/EventHandlers/UnknownCommandHandler.cs +++ b/CompatBot/EventHandlers/UnknownCommandHandler.cs @@ -79,17 +79,17 @@ internal static partial class UnknownCommandHandler .DistinctBy(i => i.fqn) .Take(4) .ToList(); - var btnExplain = new DiscordButtonComponent(cmdMatches.Count == 0 ? ButtonStyle.Primary : ButtonStyle.Secondary, "unk:cmd:explain", "Explain this", emoji: new(DiscordEmoji.FromUnicode("🔍"))); - var btnCompat = new DiscordButtonComponent(ButtonStyle.Secondary, "unk:cmd:compat", "Is this game playable?", emoji: new(DiscordEmoji.FromUnicode("🔍"))); - var btnHelp = new DiscordButtonComponent(ButtonStyle.Secondary, "unk:cmd:help", "Show bot commands", emoji: new(DiscordEmoji.FromUnicode("❔"))); - var btnCancel = new DiscordButtonComponent(ButtonStyle.Danger, "unk:cmd:cancel", "Ignore", emoji: new(DiscordEmoji.FromUnicode("✖"))); + var btnExplain = new DiscordButtonComponent(cmdMatches.Count == 0 ? DiscordButtonStyle.Primary : DiscordButtonStyle.Secondary, "unk:cmd:explain", "Explain this", emoji: new(DiscordEmoji.FromUnicode("🔍"))); + var btnCompat = new DiscordButtonComponent(DiscordButtonStyle.Secondary, "unk:cmd:compat", "Is this game playable?", emoji: new(DiscordEmoji.FromUnicode("🔍"))); + var btnHelp = new DiscordButtonComponent(DiscordButtonStyle.Secondary, "unk:cmd:help", "Show bot commands", emoji: new(DiscordEmoji.FromUnicode("❔"))); + var btnCancel = new DiscordButtonComponent(DiscordButtonStyle.Danger, "unk:cmd:cancel", "Ignore", emoji: new(DiscordEmoji.FromUnicode("✖"))); var cmdEmoji = new DiscordComponentEmoji(DiscordEmoji.FromUnicode("🤖")); var msgBuilder = new DiscordMessageBuilder() .WithContent("I'm afraid the intended command didn't spell out quite right") .AddComponents(btnExplain, btnCompat, btnHelp, btnCancel); if (cmdMatches.Count > 0) { - var btnSuggest = cmdMatches.Select((m, i) => new DiscordButtonComponent(i == 0 ? ButtonStyle.Primary : ButtonStyle.Secondary, "unk:cmd:s:" + m.cmd, Config.CommandPrefix + m.fqn + m.arg, emoji: cmdEmoji)); + var btnSuggest = cmdMatches.Select((m, i) => new DiscordButtonComponent(i == 0 ? DiscordButtonStyle.Primary : DiscordButtonStyle.Secondary, "unk:cmd:s:" + m.cmd, Config.CommandPrefix + m.fqn + m.arg, emoji: cmdEmoji)); foreach (var btn in btnSuggest) msgBuilder.AddComponents(btn); } diff --git a/CompatBot/EventHandlers/UsernameValidationMonitor.cs b/CompatBot/EventHandlers/UsernameValidationMonitor.cs index 18c0556e..fa7b9310 100644 --- a/CompatBot/EventHandlers/UsernameValidationMonitor.cs +++ b/CompatBot/EventHandlers/UsernameValidationMonitor.cs @@ -16,7 +16,7 @@ public static class UsernameValidationMonitor if (guildMember.IsWhitelisted()) return; - if (guild.Permissions?.HasFlag(Permissions.ChangeNickname) is false) + if (guild.Permissions?.HasFlag(DiscordPermission.ChangeNickname) is false) return; await using var db = new BotDb(); @@ -51,7 +51,7 @@ public static class UsernameValidationMonitor foreach (var guild in client.Guilds.Values) try { - if (guild.Permissions?.HasFlag(Permissions.ChangeNickname) is false) + if (guild.Permissions?.HasFlag(DiscordPermission.ChangeNickname) is false) continue; await using var db = new BotDb(); diff --git a/CompatBot/Properties/GlobalSuppressions.cs b/CompatBot/Properties/GlobalSuppressions.cs index 6b8d9ac3..bcd0f0e3 100644 --- a/CompatBot/Properties/GlobalSuppressions.cs +++ b/CompatBot/Properties/GlobalSuppressions.cs @@ -6,8 +6,8 @@ using System.Runtime.CompilerServices; // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. -[assembly: SuppressMessage("Usage", "VSTHRD100:Avoid async void methods", Justification = "async background check by design", Scope = "member", Target = "~M:CompatBot.Commands.Moderation.Audit.SpoofingCheck(DSharpPlus.CommandsNext.CommandContext)")] -[assembly: SuppressMessage("Usage", "VSTHRD100:Avoid async void methods", Justification = "async background check by design", Scope = "member", Target = "~M:CompatBot.ThumbScrapper.PsnScraper.CheckContentIdAsync(DSharpPlus.CommandsNext.CommandContext,System.String,System.Threading.CancellationToken)")] +[assembly: SuppressMessage("Usage", "VSTHRD100:Avoid async void methods", Justification = "async background check by design", Scope = "member", Target = "~M:CompatBot.Commands.Moderation.Audit.SpoofingCheck(DSharpPlus.Commands.CommandContext)")] +[assembly: SuppressMessage("Usage", "VSTHRD100:Avoid async void methods", Justification = "async background check by design", Scope = "member", Target = "~M:CompatBot.ThumbScrapper.PsnScraper.CheckContentIdAsync(DSharpPlus.Commands.CommandContext,System.String,System.Threading.CancellationToken)")] [assembly: SuppressMessage("Usage", "VSTHRD100:Avoid async void methods", Justification = "async background check by design", Scope = "member", Target = "~M:CompatBot.EventHandlers.LogParsingHandler.EnqueueLogProcessing(DSharpPlus.DiscordClient,DSharpPlus.Entities.DiscordChannel,DSharpPlus.Entities.DiscordMessage,DSharpPlus.Entities.DiscordMember,System.Boolean,System.Boolean)")] -[assembly: SuppressMessage("Usage", "VSTHRD100:Avoid async void methods", Justification = "async background check by design", Scope = "member", Target = "~M:CompatBot.EventHandlers.UnknownCommandHandler.OnErrorInternal(DSharpPlus.CommandsNext.CommandsNextExtension,DSharpPlus.CommandsNext.CommandErrorEventArgs)")] +[assembly: SuppressMessage("Usage", "VSTHRD100:Avoid async void methods", Justification = "async background check by design", Scope = "member", Target = "~M:CompatBot.EventHandlers.UnknownCommandHandler.OnErrorInternal(DSharpPlus.Commands.CommandsNextExtension,DSharpPlus.Commands.CommandErrorEventArgs)")] [assembly: InternalsVisibleTo("Tests")] \ No newline at end of file diff --git a/CompatBot/Utils/DefaultHandlerFilter.cs b/CompatBot/Utils/DefaultHandlerFilter.cs index 0cd448eb..1f3ae34a 100644 --- a/CompatBot/Utils/DefaultHandlerFilter.cs +++ b/CompatBot/Utils/DefaultHandlerFilter.cs @@ -19,12 +19,4 @@ internal static class DefaultHandlerFilter return false; } - - internal static bool IsOnionLike(this CommandContext ctx) - => IsOnionLike(ctx.Message); - - internal static bool IsOnionLike(this DiscordMessage message) - => !message.Channel.IsPrivate - && (message.Author.Id == 197163728867688448ul - || message.Author.Id == 272022580112654336ul && new Random().NextDouble() < 0.1 * Config.FunMultiplier); } \ No newline at end of file diff --git a/CompatBot/Utils/Extensions/CommandContextExtensions.cs b/CompatBot/Utils/Extensions/CommandContextExtensions.cs index 30e80624..3f686672 100644 --- a/CompatBot/Utils/Extensions/CommandContextExtensions.cs +++ b/CompatBot/Utils/Extensions/CommandContextExtensions.cs @@ -1,6 +1,9 @@ using System.Text.RegularExpressions; using CompatBot.Commands.Attributes; -using DSharpPlus.CommandsNext.Converters; +using DSharpPlus.Commands.Converters; +using DSharpPlus.Commands.Processors.TextCommands; +using DSharpPlus.Commands.Processors.TextCommands.Parsing; +using Microsoft.Extensions.DependencyInjection; namespace CompatBot.Utils; @@ -16,7 +19,23 @@ public static partial class CommandContextExtensions { try { - var result = await ((IArgumentConverter)new DiscordMemberConverter()).ConvertAsync(word, ctx).ConfigureAwait(false); + if (ctx is not TextCommandContext tctx) + return null; + + await using var scope = tctx.Extension.ServiceProvider.CreateAsyncScope(); + var cctx = new TextConverterContext + { + User = ctx.User, + Channel = ctx.Channel, + Message = tctx.Message, + Command = tctx.Command, + RawArguments = word, + + Splicer = DefaultTextArgumentSplicer.Splice, + Extension = tctx.Extension, + ServiceScope = scope, + }; + var result = await new DiscordMemberConverter().ConvertAsync(cctx).ConfigureAwait(false); return result.HasValue ? result.Value : null; } catch (Exception e) @@ -35,21 +54,18 @@ public static partial class CommandContextExtensions public static Task GetUserNameAsync(this CommandContext ctx, ulong userId, bool? forDmPurposes = null, string defaultName = "Unknown user") => ctx.Client.GetUserNameAsync(ctx.Channel, userId, forDmPurposes, defaultName); - public static Task GetMessageAsync(this CommandContext ctx, string messageLink) + public static async Task GetMessageAsync(this CommandContext ctx, string messageLink) { if (MessageLinkPattern().Match(messageLink) is Match m && ulong.TryParse(m.Groups["guild"].Value, out var guildId) && ulong.TryParse(m.Groups["channel"].Value, out var channelId) && ulong.TryParse(m.Groups["message"].Value, out var msgId) && ctx.Client.Guilds.TryGetValue(guildId, out var guild) - && guild.GetChannel(channelId) is DiscordChannel channel) - return channel.GetMessageAsync(msgId); - return Task.FromResult((DiscordMessage?)null); + && await guild.GetChannelAsync(channelId).ConfigureAwait(false) is DiscordChannel channel) + return await channel.GetMessageAsync(msgId); + return null; } public static async Task GetMessageAsync(this DiscordClient client, DiscordChannel channel, ulong messageId) - { - - return await channel.GetMessageAsync(messageId).ConfigureAwait(false); - } + => await channel.GetMessageAsync(messageId).ConfigureAwait(false); } \ No newline at end of file diff --git a/CompatBot/Utils/Extensions/DiscordClientExtensions.cs b/CompatBot/Utils/Extensions/DiscordClientExtensions.cs index 7b78c4cd..56b18b36 100644 --- a/CompatBot/Utils/Extensions/DiscordClientExtensions.cs +++ b/CompatBot/Utils/Extensions/DiscordClientExtensions.cs @@ -1,6 +1,7 @@ using System.IO; using CompatApiClient.Utils; using CompatBot.EventHandlers; +using DSharpPlus.Commands.Processors.TextCommands; using DSharpPlus.Exceptions; namespace CompatBot.Utils; @@ -74,7 +75,7 @@ public static class DiscordClientExtensions try { showBoth ??= message.Channel.IsPrivate; - var canReact = message.Channel.IsPrivate || message.Channel.PermissionsFor(message.Channel.Guild.CurrentMember).HasPermission(Permissions.AddReactions); + var canReact = message.Channel.IsPrivate || message.Channel.PermissionsFor(message.Channel.Guild.CurrentMember).HasPermission(DiscordPermission.AddReactions); if (canReact) await message.CreateReactionAsync(emoji).ConfigureAwait(false); if ((!canReact || showBoth.Value) && !string.IsNullOrEmpty(fallbackMessage)) @@ -86,9 +87,9 @@ public static class DiscordClientExtensions } } - public static Task RemoveReactionAsync(this CommandContext ctx, DiscordEmoji emoji) => RemoveReactionAsync(ctx.Message, emoji); + public static Task RemoveReactionAsync(this TextCommandContext ctx, DiscordEmoji emoji) => RemoveReactionAsync(ctx.Message, emoji); - public static Task ReactWithAsync(this CommandContext ctx, DiscordEmoji emoji, string? fallbackMessage = null, bool? showBoth = null) + public static Task ReactWithAsync(this TextCommandContext ctx, DiscordEmoji emoji, string? fallbackMessage = null, bool? showBoth = null) => ReactWithAsync(ctx.Message, emoji, fallbackMessage, showBoth ?? (ctx.Prefix == Config.AutoRemoveCommandPrefix)); public static async Task> GetMessagesBeforeAsync(this DiscordChannel channel, ulong beforeMessageId, int limit = 100, DateTime? timeLimit = null) @@ -116,9 +117,18 @@ public static class DiscordClientExtensions try { if (contents?.Count > 0) - return await logChannel.SendMessageAsync(new DiscordMessageBuilder().WithEmbed(embedBuilder.Build()).AddFiles(contents).WithAllowedMentions(Config.AllowedMentions.Nothing)).ConfigureAwait(false); + return await logChannel.SendMessageAsync( + new DiscordMessageBuilder() + .AddEmbed(embedBuilder.Build()) + .AddFiles(contents) + .WithAllowedMentions(Config.AllowedMentions.Nothing) + ).ConfigureAwait(false); else - return await logChannel.SendMessageAsync(new DiscordMessageBuilder().WithEmbed(embedBuilder.Build()).WithAllowedMentions(Config.AllowedMentions.Nothing)).ConfigureAwait(false); + return await logChannel.SendMessageAsync( + new DiscordMessageBuilder() + .AddEmbed(embedBuilder.Build()) + .WithAllowedMentions(Config.AllowedMentions.Nothing) + ).ConfigureAwait(false); } finally { @@ -137,7 +147,11 @@ public static class DiscordClientExtensions var mentions = reporters.Where(m => m is not null).Select(GetMentionWithNickname!); embedBuilder.AddField("Reporters", string.Join(Environment.NewLine, mentions)); var logChannel = await getLogChannelTask.ConfigureAwait(false); - return await logChannel.SendMessageAsync(new DiscordMessageBuilder().WithEmbed(embedBuilder.Build()).WithAllowedMentions(Config.AllowedMentions.Nothing)).ConfigureAwait(false); + return await logChannel.SendMessageAsync( + new DiscordMessageBuilder() + .AddEmbed(embedBuilder.Build()) + .WithAllowedMentions(Config.AllowedMentions.Nothing) + ).ConfigureAwait(false); } public static async Task ReportAsync(this DiscordClient client, string infraction, string description, ICollection? potentialVictims, ReportSeverity severity) @@ -151,7 +165,11 @@ public static class DiscordClientExtensions if (potentialVictims?.Count > 0) result.AddField("Potential Targets", string.Join(Environment.NewLine, potentialVictims.Select(GetMentionWithNickname)).Trim(EmbedPager.MaxFieldLength)); var logChannel = await client.GetChannelAsync(Config.BotLogId).ConfigureAwait(false); - return await logChannel.SendMessageAsync(new DiscordMessageBuilder().WithEmbed(result.Build()).WithAllowedMentions(Config.AllowedMentions.Nothing)).ConfigureAwait(false); + return await logChannel.SendMessageAsync( + new DiscordMessageBuilder() + .AddEmbed(result.Build()) + .WithAllowedMentions(Config.AllowedMentions.Nothing) + ).ConfigureAwait(false); } public static string GetMentionWithNickname(this DiscordMember member) diff --git a/CompatBot/Utils/Extensions/DiscordGuildExtensions.cs b/CompatBot/Utils/Extensions/DiscordGuildExtensions.cs index bf799bc8..92cd5981 100644 --- a/CompatBot/Utils/Extensions/DiscordGuildExtensions.cs +++ b/CompatBot/Utils/Extensions/DiscordGuildExtensions.cs @@ -8,8 +8,8 @@ public static class DiscordGuildExtensions public static int GetAttachmentSizeLimit(this DiscordGuild? guild) => guild?.PremiumTier switch { - PremiumTier.Tier_3 => 100 * 1024 * 1024, - PremiumTier.Tier_2 => 50 * 1024 * 1024, + DiscordPremiumTier.Tier_3 => 100 * 1024 * 1024, + DiscordPremiumTier.Tier_2 => 50 * 1024 * 1024, _ => Config.AttachmentSizeLimit, }; } \ No newline at end of file diff --git a/CompatBot/Utils/Extensions/DiscordMessageExtensions.cs b/CompatBot/Utils/Extensions/DiscordMessageExtensions.cs index cb43d236..c13d13b1 100644 --- a/CompatBot/Utils/Extensions/DiscordMessageExtensions.cs +++ b/CompatBot/Utils/Extensions/DiscordMessageExtensions.cs @@ -59,7 +59,7 @@ public static class DiscordMessageExtensions if (content is {Length: >0}) msgBuilder.WithContent(content); if (embed is not null) - msgBuilder.WithEmbed(embed); + msgBuilder.AddEmbed(embed); if (refMsg is not null) msgBuilder.WithReply(refMsg.Id); return botMsg.UpdateOrCreateMessageAsync(channel, msgBuilder); diff --git a/CompatBot/Utils/Extensions/EnumerableExtensions.cs b/CompatBot/Utils/Extensions/EnumerableExtensions.cs index b6cc3c48..0f245756 100644 --- a/CompatBot/Utils/Extensions/EnumerableExtensions.cs +++ b/CompatBot/Utils/Extensions/EnumerableExtensions.cs @@ -49,5 +49,12 @@ public static class EnumerableExtensions .GroupBy(x => x.inx / maxItems) .Select(g => g.Select(x => x.item)); } - + + public static async Task> ToListAsync(this IAsyncEnumerable items) + { + var result = new List(); + await foreach(var item in items.ConfigureAwait(false)) + result.Add(item); + return result; + } } \ No newline at end of file diff --git a/CompatBot/Utils/Extensions/InteractivityExtensions.cs b/CompatBot/Utils/Extensions/InteractivityExtensions.cs index a6af596e..26cff3e4 100644 --- a/CompatBot/Utils/Extensions/InteractivityExtensions.cs +++ b/CompatBot/Utils/Extensions/InteractivityExtensions.cs @@ -6,14 +6,14 @@ namespace CompatBot.Utils; public static class InteractivityExtensions { - public static Task<(DiscordMessage? message, DiscordMessage? text, MessageReactionAddEventArgs? reaction)> WaitForMessageOrReactionAsync( + public static Task<(DiscordMessage? message, DiscordMessage? text, MessageReactionAddedEventArgs? reaction)> WaitForMessageOrReactionAsync( this InteractivityExtension interactivity, DiscordMessage message, DiscordUser user, params DiscordEmoji?[] reactions) => WaitForMessageOrReactionAsync(interactivity, message, user, null, reactions); - public static async Task<(DiscordMessage? message, DiscordMessage? text, MessageReactionAddEventArgs? reaction)> WaitForMessageOrReactionAsync( + public static async Task<(DiscordMessage? message, DiscordMessage? text, MessageReactionAddedEventArgs? reaction)> WaitForMessageOrReactionAsync( this InteractivityExtension interactivity, DiscordMessage message, DiscordUser user, @@ -46,7 +46,7 @@ public static class InteractivityExtensions result = null; } DiscordMessage? text = null; - MessageReactionAddEventArgs? reaction = null; + MessageReactionAddedEventArgs? reaction = null; if (waitTextResponseTask.IsCompletedSuccessfully) text = (await waitTextResponseTask).Result; if (waitReactionResponse.IsCompletedSuccessfully) @@ -67,7 +67,7 @@ public static class InteractivityExtensions } } - public static async Task<(DiscordMessage? text, ComponentInteractionCreateEventArgs? reaction)> WaitForMessageOrButtonAsync( + public static async Task<(DiscordMessage? text, ComponentInteractionCreatedEventArgs? reaction)> WaitForMessageOrButtonAsync( this InteractivityExtension interactivity, DiscordMessage message, DiscordUser user, @@ -87,14 +87,14 @@ public static class InteractivityExtensions waitButtonTask ).ConfigureAwait(false); DiscordMessage? text = null; - ComponentInteractionCreateEventArgs? reaction = null; + ComponentInteractionCreatedEventArgs? reaction = null; if (waitTextResponseTask.IsCompletedSuccessfully) text = (await waitTextResponseTask).Result; if (waitButtonTask.IsCompletedSuccessfully) { reaction = (await waitButtonTask).Result; if (reaction is not null) - await reaction.Interaction.CreateResponseAsync(InteractionResponseType.DeferredMessageUpdate).ConfigureAwait(false); + await reaction.Interaction.CreateResponseAsync(DiscordInteractionResponseType.DeferredMessageUpdate).ConfigureAwait(false); } if (text != null && !message.Channel.IsPrivate) try diff --git a/CompatBot/Watchdog.cs b/CompatBot/Watchdog.cs index 00a0cfe3..f031f33b 100644 --- a/CompatBot/Watchdog.cs +++ b/CompatBot/Watchdog.cs @@ -28,8 +28,17 @@ internal static class Watchdog { Config.TelemetryClient?.TrackEvent("socket-deadlock-potential"); Config.Log.Warn("Potential socket deadlock detected, reconnecting…"); - await client.ReconnectAsync(true).ConfigureAwait(false); - await Task.Delay(Config.SocketDisconnectCheckIntervalInSec, Config.Cts.Token).ConfigureAwait(false); + //await client.ReconnectAsync(true).ConfigureAwait(false); + try + { + await client.DisconnectAsync().ConfigureAwait(false); + await client.ConnectAsync().ConfigureAwait(false); + await Task.Delay(Config.SocketDisconnectCheckIntervalInSec, Config.Cts.Token).ConfigureAwait(false); + } + catch (Exception e) + { + Config.Log.Error(e, "Failed to manually reconnect"); + } if (IsOk) { Config.Log.Info("Looks like we're back in business"); @@ -82,7 +91,8 @@ internal static class Watchdog if (Config.TelemetryClient is TelemetryClient tc) { var userToBotDelay = (DateTime.UtcNow - args.Message.Timestamp.UtcDateTime).TotalMilliseconds; - tc.TrackMetric("gw-latency", c.Ping); + var latency = c.GetConnectionLatency(Config.BotGuildId); + tc.TrackMetric("gw-latency", latency.TotalMilliseconds); tc.TrackMetric("user-to-bot-latency", userToBotDelay); tc.TrackMetric("time-since-last-incoming-message", TimeSinceLastIncomingMessage.ElapsedMilliseconds); } @@ -99,7 +109,8 @@ internal static class Watchdog if (Config.TelemetryClient is not TelemetryClient tc) continue; - tc.TrackMetric("gw-latency", client.Ping); + var latency = client.GetConnectionLatency(Config.BotGuildId); + tc.TrackMetric("gw-latency", latency.TotalMilliseconds); tc.TrackMetric("memory-gc-total", gcMemInfo.HeapSizeBytes); tc.TrackMetric("memory-gc-load", gcMemInfo.MemoryLoadBytes); tc.TrackMetric("memory-gc-committed", gcMemInfo.TotalCommittedBytes); diff --git a/SourceGenerators/AttributeUsageAnalyzer.cs b/SourceGenerators/AttributeUsageAnalyzer.cs index abcd8372..4f634f04 100644 --- a/SourceGenerators/AttributeUsageAnalyzer.cs +++ b/SourceGenerators/AttributeUsageAnalyzer.cs @@ -44,7 +44,7 @@ public class AttributeUsageAnalyzer : DiagnosticAnalyzer var hasGroupCommand = false; foreach (var attr in methodAttributes) - if (IsDescendantOfAttribute(attr, "DSharpPlus.CommandsNext.Attributes.GroupCommandAttribute")) + if (IsDescendantOfAttribute(attr, "DSharpPlus.Commands.Attributes.GroupCommandAttribute")) { hasGroupCommand = true; break; @@ -54,7 +54,7 @@ public class AttributeUsageAnalyzer : DiagnosticAnalyzer return; foreach (var attr in methodAttributes) - if (IsDescendantOfAttribute(attr, "DSharpPlus.CommandsNext.Attributes.CheckBaseAttribute")) + if (IsDescendantOfAttribute(attr, "DSharpPlus.Commands.Attributes.CheckBaseAttribute")) { var attrLocation = attr.ApplicationSyntaxReference?.SyntaxTree.GetLocation(attr.ApplicationSyntaxReference.Span); var diagnostic = Diagnostic.Create(AccessCheckAttributeOnGroupCommandRule, attrLocation ?? methodSymbol.Locations[0], attr.AttributeClass?.Name ?? methodSymbol.Name);