From a8673244359472bf4d95119d62d0d3fe9a81b392 Mon Sep 17 00:00:00 2001 From: Plerx <50530305+Plerx2493@users.noreply.github.com> Date: Sun, 11 Aug 2024 21:01:26 +0200 Subject: [PATCH] Use the new dsp eventhandling Signed-off-by: Plerx <50530305+Plerx2493@users.noreply.github.com> --- .../EventListener.ActionButtons.cs | 8 +-- .../EventListener.GuildChanged.cs | 8 ++- .../ModularAssistentForDiscordServer.csproj | 22 ++++---- .../ModularDiscordBot.cs | 50 +++++++++++++++--- .../Services/AntiPhishingService.cs | 10 ++-- .../Services/DiscordCommandService.cs | 51 +++---------------- .../Services/LoggingService.cs | 17 ++----- .../Services/MessageSnipeService.cs | 22 ++------ .../Services/StarboardService.cs | 26 +++++++--- .../Services/VoiceAlertService.cs | 8 +-- 10 files changed, 109 insertions(+), 113 deletions(-) diff --git a/ModularAssistentForDiscordServer/EventListeners/EventListener.ActionButtons.cs b/ModularAssistentForDiscordServer/EventListeners/EventListener.ActionButtons.cs index c3a9e07..cbbcb45 100644 --- a/ModularAssistentForDiscordServer/EventListeners/EventListener.ActionButtons.cs +++ b/ModularAssistentForDiscordServer/EventListeners/EventListener.ActionButtons.cs @@ -113,7 +113,7 @@ private static async Task SetTranslationLanguage(ComponentInteractionCreatedEven style: DiscordTextInputStyle.Paragraph)); await args.Interaction.CreateResponseAsync(DiscordInteractionResponseType.Modal, modal); - InteractivityExtension interactive = sender.GetInteractivity(); + InteractivityExtension interactive = sender.ServiceProvider.GetRequiredService(); InteractivityResult result = await interactive.WaitForModalAsync($"setLanguage-{args.User.Id}", TimeSpan.FromMinutes(5)); @@ -157,9 +157,9 @@ await e.Interaction.CreateResponseAsync(DiscordInteractionResponseType.ChannelMe .AddComponents(new DiscordTextInputComponent("Please enter your answer:", "answer-text", required: true, style: DiscordTextInputStyle.Paragraph)); await e.Interaction.CreateResponseAsync(DiscordInteractionResponseType.Modal, modal); - - - InteractivityExtension interactive = client.GetInteractivity(); + + + InteractivityExtension interactive = client.ServiceProvider.GetRequiredService(); InteractivityResult result = await interactive.WaitForModalAsync($"AnswerDM-{substring[1]}"); diff --git a/ModularAssistentForDiscordServer/EventListeners/EventListener.GuildChanged.cs b/ModularAssistentForDiscordServer/EventListeners/EventListener.GuildChanged.cs index 3a7bde4..6d8eecc 100644 --- a/ModularAssistentForDiscordServer/EventListeners/EventListener.GuildChanged.cs +++ b/ModularAssistentForDiscordServer/EventListeners/EventListener.GuildChanged.cs @@ -24,10 +24,12 @@ internal static partial class EventListener { public static async Task OnGuildCreated(DiscordClient sender, GuildCreatedEventArgs args) { + DiscordMember owner = await args.Guild.GetGuildOwnerAsync(); + DiscordEmbedBuilder embed = new DiscordEmbedBuilder() .WithTitle($"New guild added: {args.Guild.Name}") .AddField("Id:", args.Guild.Id.ToString()) - .AddField("Owner:", args.Guild.Owner.Username + "#" + args.Guild.Owner.Discriminator) + .AddField("Owner:", owner.GlobalName ?? owner.Username) .AddField("Membercount:", args.Guild.MemberCount.ToString()) .AddField("Added:", Formatter.Timestamp(DateTimeOffset.Now)) .AddField("Created:", Formatter.Timestamp(args.Guild.CreationTimestamp)) @@ -40,10 +42,12 @@ await ModularDiscordBot.Services public static async Task OnGuildDeleted(DiscordClient sender, GuildDeletedEventArgs args) { + DiscordUser owner = await sender.GetUserAsync(args.Guild.OwnerId); + DiscordEmbedBuilder embed = new DiscordEmbedBuilder() .WithTitle($"Guild removed: {args.Guild.Name}") .AddField("Id:", args.Guild.Id.ToString()) - .AddField("Owner:", args.Guild.Owner.Username + "#" + args.Guild.Owner.Discriminator) + .AddField("Owner:", owner.GlobalName) .AddField("Membercount:", args.Guild.MemberCount.ToString()) .AddField("Removed:", Formatter.Timestamp(DateTimeOffset.Now)) .AddField("Created:", Formatter.Timestamp(args.Guild.CreationTimestamp)) diff --git a/ModularAssistentForDiscordServer/ModularAssistentForDiscordServer.csproj b/ModularAssistentForDiscordServer/ModularAssistentForDiscordServer.csproj index fad65f2..532198c 100644 --- a/ModularAssistentForDiscordServer/ModularAssistentForDiscordServer.csproj +++ b/ModularAssistentForDiscordServer/ModularAssistentForDiscordServer.csproj @@ -25,10 +25,10 @@ - - - - + + + + @@ -42,14 +42,14 @@ - - - - - - + + + + + + - + diff --git a/ModularAssistentForDiscordServer/ModularDiscordBot.cs b/ModularAssistentForDiscordServer/ModularDiscordBot.cs index 9a96a79..fec88a8 100644 --- a/ModularAssistentForDiscordServer/ModularDiscordBot.cs +++ b/ModularAssistentForDiscordServer/ModularDiscordBot.cs @@ -15,8 +15,18 @@ using DeepL; using DSharpPlus; using DSharpPlus.Clients; +using DSharpPlus.Commands; +using DSharpPlus.Commands.Processors.TextCommands; +using DSharpPlus.Commands.Processors.TextCommands.Parsing; using DSharpPlus.Extensions; +using DSharpPlus.Interactivity; +using DSharpPlus.Interactivity.Enums; +using DSharpPlus.Interactivity.Extensions; using DSharpPlus.Net; +using MADS.Commands.ContextMenu; +using MADS.Commands.Slash; +using MADS.Commands.Text.Base; +using MADS.CommandsChecks; using MADS.Entities; using MADS.EventListeners; using MADS.Extensions; @@ -53,6 +63,34 @@ await Host.CreateDefaultBuilder() }) .AddSingleton(config) .AddDiscordClient(config.Token, DiscordIntents.All ^ DiscordIntents.GuildPresences) + .AddCommandsExtension(extension => + { + List commandTypes = + [ + typeof(StealEmojiMessage), typeof(TranslateMessage), typeof(UserInfoUser), typeof(About), typeof(BotStats), + typeof(Jumppad), typeof(MessageSnipe), typeof(MoveEmoji), typeof(Ping), typeof(Purge), typeof(Quotes), + typeof(Reminder), typeof(RoleSelection), typeof(StarboardConfig), typeof(Translation), typeof(VoiceAlerts), + typeof(Eval), typeof(ExitGuild) + ]; + + extension.AddProcessors(new TextCommandProcessor(new TextCommandConfiguration() + { + PrefixResolver = new DefaultPrefixResolver(true, config.Prefix).ResolvePrefixAsync + })); + extension.AddCommands(commandTypes); + extension.AddCheck(); + extension.CommandErrored += EventListener.OnCommandsErrored; + }) + .AddInteractivityExtension(new InteractivityConfiguration + { + PollBehaviour = PollBehaviour.KeepEmojis, + Timeout = TimeSpan.FromMinutes(10), + ButtonBehavior = ButtonPaginationBehavior.DeleteButtons, + PaginationBehaviour = PaginationBehaviour.Ignore, + ResponseBehavior = InteractionResponseBehavior.Ignore, + ResponseMessage = "invalid interaction", + PaginationDeletion = PaginationDeletion.DeleteEmojis + }) .AddDiscordRestClient(config) .ConfigureEventHandlers(x => { @@ -64,6 +102,12 @@ await Host.CreateDefaultBuilder() x.HandleComponentInteractionCreated(EventListener.OnRoleSelection); x.HandleZombied(EventListener.OnZombied); x.HandleMessageCreated(EventListener.DmHandler); + + x.AddEventHandlers(ServiceLifetime.Singleton); + x.AddEventHandlers(ServiceLifetime.Singleton); + x.AddEventHandlers(ServiceLifetime.Singleton); + x.AddEventHandlers(ServiceLifetime.Singleton); + x.AddEventHandlers(); }) .Configure(x => { @@ -100,20 +144,14 @@ await Host.CreateDefaultBuilder() options.StartDelay = TimeSpan.FromSeconds(10); options.AwaitApplicationStarted = true; }) - .AddSingleton() - .AddHostedService(s => s.GetRequiredService()) .AddSingleton() - .AddSingleton() .AddHostedService(s => s.GetRequiredService()) .AddSingleton() .AddHostedService(s => s.GetRequiredService()) - .AddSingleton() .AddHostedService(s => s.GetRequiredService()) .AddSingleton(new Translator(_config.DeeplApiKey ?? "")) .AddSingleton() - .AddSingleton() .AddSingleton() - .AddSingleton() .AddHttpClient(); Services = services.BuildServiceProvider(); diff --git a/ModularAssistentForDiscordServer/Services/AntiPhishingService.cs b/ModularAssistentForDiscordServer/Services/AntiPhishingService.cs index 62b0fb1..ce3c41c 100644 --- a/ModularAssistentForDiscordServer/Services/AntiPhishingService.cs +++ b/ModularAssistentForDiscordServer/Services/AntiPhishingService.cs @@ -24,7 +24,7 @@ namespace MADS.Services; -public partial class AntiPhishingService +public partial class AntiPhishingService : IEventHandler, IEventHandler { private readonly DiscordClient _discordClient; private readonly HttpClient _antiFishClient; @@ -65,10 +65,6 @@ public AntiPhishingService(DiscordClient discordClient, ILogger HandleMessage(sender, eventArgs); + + public Task HandleEventAsync(DiscordClient sender, MessageUpdatedEventArgs eventArgs) => HandleMessageUpdate(sender, eventArgs); } \ No newline at end of file diff --git a/ModularAssistentForDiscordServer/Services/DiscordCommandService.cs b/ModularAssistentForDiscordServer/Services/DiscordCommandService.cs index 84e997b..1eedb33 100644 --- a/ModularAssistentForDiscordServer/Services/DiscordCommandService.cs +++ b/ModularAssistentForDiscordServer/Services/DiscordCommandService.cs @@ -39,9 +39,9 @@ public class DiscordCommandService : IHostedService public readonly CommandsExtension Commands; public readonly DiscordClient DiscordClient; public DateTime StartTime; - + private static readonly ILogger _logger = Log.ForContext(); - + public DiscordCommandService ( DiscordClient discordClient, @@ -52,49 +52,12 @@ MadsConfig config DiscordClient = discordClient; StartTime = DateTime.Now; DbContextFactory = dbContextFactory; - - List commandTypes = - [ - typeof(StealEmojiMessage), typeof(TranslateMessage), typeof(UserInfoUser), typeof(About), typeof(BotStats), - typeof(Jumppad), typeof(MessageSnipe), typeof(MoveEmoji), typeof(Ping), typeof(Purge), typeof(Quotes), - typeof(Reminder), typeof(RoleSelection), typeof(StarboardConfig), typeof(Translation), typeof(VoiceAlerts), - typeof(Eval), typeof(ExitGuild) - ]; - - - CommandsConfiguration commandsConfiguration = new() - { -#if !RELEASE - DebugGuildId = 938120155974750288 -#endif - }; - Commands = DiscordClient.UseCommands(commandsConfiguration); - Commands.AddProcessorsAsync(new TextCommandProcessor(new TextCommandConfiguration() - { - PrefixResolver = new DefaultPrefixResolver(true, config.Prefix).ResolvePrefixAsync - })); - Commands.AddCommands(commandTypes); - Commands.AddCheck(); - Commands.CommandErrored += EventListener.OnCommandsErrored; - - //Interactivity - InteractivityConfiguration interactivityConfig = new() - { - PollBehaviour = PollBehaviour.KeepEmojis, - Timeout = TimeSpan.FromMinutes(10), - ButtonBehavior = ButtonPaginationBehavior.DeleteButtons, - PaginationBehaviour = PaginationBehaviour.Ignore, - ResponseBehavior = InteractionResponseBehavior.Ignore, - ResponseMessage = "invalid interaction", - PaginationDeletion = PaginationDeletion.DeleteEmojis - }; - DiscordClient.UseInteractivity(interactivityConfig); } - + public async Task StartAsync(CancellationToken cancellationToken) { _logger.Warning("DiscordClientService started"); - + //Update database to latest migration await using MadsContext context = await DbContextFactory.CreateDbContextAsync(cancellationToken); IEnumerable pendingMigrations = await context.Database.GetPendingMigrationsAsync(cancellationToken); @@ -106,13 +69,13 @@ public async Task StartAsync(CancellationToken cancellationToken) sw.Stop(); _logger.Warning("Applied pending migrations in {Time} ms", sw.ElapsedMilliseconds); } - + DiscordActivity act = new("Messing with code", DiscordActivityType.Custom); - + //connect client await DiscordClient.ConnectAsync(act, DiscordUserStatus.Online); } - + public Task StopAsync(CancellationToken cancellationToken) { return DiscordClient.DisconnectAsync(); diff --git a/ModularAssistentForDiscordServer/Services/LoggingService.cs b/ModularAssistentForDiscordServer/Services/LoggingService.cs index 7bdafd5..382aa7b 100644 --- a/ModularAssistentForDiscordServer/Services/LoggingService.cs +++ b/ModularAssistentForDiscordServer/Services/LoggingService.cs @@ -27,23 +27,12 @@ namespace MADS.Services; -public class LoggingService +public class LoggingService : IEventHandler, IEventHandler { - private readonly DiscordCommandService? _modularDiscordBot; private DiscordWebhookClient _discordWebhookClient = new(); public LoggingService(DiscordCommandService modularDiscordBot) { - _modularDiscordBot = modularDiscordBot; - -#pragma warning disable DSP0001 // Type or member is obsolete - //Button response with modal - _modularDiscordBot.DiscordClient.ComponentInteractionCreated += HandleFeedbackButton; - - //Modal processing - _modularDiscordBot.DiscordClient.ModalSubmitted += HandleFeedbackModal; -#pragma warning restore DSP0001 // Type or member is obsolete - SetupWebhookLogging(); } @@ -120,4 +109,8 @@ public async Task LogToWebhook(DiscordMessageBuilder message) await _discordWebhookClient.BroadcastMessageAsync(messageBuilder); } + + public Task HandleEventAsync(DiscordClient sender, ComponentInteractionCreatedEventArgs eventArgs) => HandleFeedbackButton(sender, eventArgs); + + public Task HandleEventAsync(DiscordClient sender, ModalSubmittedEventArgs eventArgs) => HandleFeedbackModal(sender, eventArgs); } \ No newline at end of file diff --git a/ModularAssistentForDiscordServer/Services/MessageSnipeService.cs b/ModularAssistentForDiscordServer/Services/MessageSnipeService.cs index 53fe630..6c52238 100644 --- a/ModularAssistentForDiscordServer/Services/MessageSnipeService.cs +++ b/ModularAssistentForDiscordServer/Services/MessageSnipeService.cs @@ -24,7 +24,7 @@ namespace MADS.Services; -public class MessageSnipeService : IHostedService +public class MessageSnipeService : IEventHandler, IEventHandler { private readonly IMemoryCache _memoryCache; private readonly MemoryCacheEntryOptions _options; @@ -41,22 +41,6 @@ public MessageSnipeService(IMemoryCache memoryCache, DiscordCommandService disco _options.SetAbsoluteExpiration(TimeSpan.FromHours(12)) .SetSize(1) .RegisterPostEvictionCallback(PostEvictionCallback); - -#pragma warning disable DSP0001 // Type or member is obsolete - Discord.MessageDeleted += MessageSniperDeleted; - Discord.MessageUpdated += MessageSniperEdited; -#pragma warning restore DSP0001 // Type or member is obsolete - } - - public Task StartAsync(CancellationToken cancellationToken) - { - _logger.Warning("Sniper active!"); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; } private Task MessageSniperDeleted @@ -163,4 +147,8 @@ public bool TryGetEditedMessage(ulong channelId, out DiscordMessage? message) _memoryCache.Remove(id); return true; } + + public Task HandleEventAsync(DiscordClient sender, MessageUpdatedEventArgs eventArgs) => MessageSniperEdited(sender, eventArgs); + + public Task HandleEventAsync(DiscordClient sender, MessageDeletedEventArgs eventArgs) => MessageSniperDeleted(sender, eventArgs); } \ No newline at end of file diff --git a/ModularAssistentForDiscordServer/Services/StarboardService.cs b/ModularAssistentForDiscordServer/Services/StarboardService.cs index d6aa128..b3f7734 100644 --- a/ModularAssistentForDiscordServer/Services/StarboardService.cs +++ b/ModularAssistentForDiscordServer/Services/StarboardService.cs @@ -25,7 +25,12 @@ namespace MADS.Services; -public class StarboardService : IHostedService +public class StarboardService : + IHostedService, + IEventHandler, + IEventHandler, + IEventHandler, + IEventHandler { private readonly DiscordClient _client; private readonly IDbContextFactory _dbFactory; @@ -41,13 +46,6 @@ public StarboardService(DiscordCommandService command, IDbContextFactory(); _dbFactory = dbFactory; - -#pragma warning disable DSP0001 - _client.MessageReactionAdded += HandleReactionAdded; - _client.MessageReactionRemoved += HandleReactionRemoved; - _client.MessageReactionsCleared += HandleReactionsCleared; - _client.MessageReactionRemovedEmoji += HandleReactionEmojiRemoved; -#pragma warning restore DSP0001 } public Task StartAsync(CancellationToken cancellationToken) @@ -469,4 +467,16 @@ DiscordEmoji emoji return messageBuilder; } + + public Task HandleEventAsync(DiscordClient sender, MessageReactionAddedEventArgs eventArgs) => + HandleReactionAdded(sender, eventArgs); + + public Task HandleEventAsync(DiscordClient sender, MessageReactionRemovedEventArgs eventArgs) => + HandleReactionRemoved(sender, eventArgs); + + public Task HandleEventAsync(DiscordClient sender, MessageReactionsClearedEventArgs eventArgs) => + HandleReactionsCleared(sender, eventArgs); + + public Task HandleEventAsync(DiscordClient sender, MessageReactionRemovedEmojiEventArgs eventArgs) => + HandleReactionEmojiRemoved(sender, eventArgs); } \ No newline at end of file diff --git a/ModularAssistentForDiscordServer/Services/VoiceAlertService.cs b/ModularAssistentForDiscordServer/Services/VoiceAlertService.cs index 80e0326..fd208f7 100644 --- a/ModularAssistentForDiscordServer/Services/VoiceAlertService.cs +++ b/ModularAssistentForDiscordServer/Services/VoiceAlertService.cs @@ -24,7 +24,7 @@ namespace MADS.Services; -public class VoiceAlertService : IHostedService +public class VoiceAlertService : IHostedService, IEventHandler { private readonly IDbContextFactory _contextFactory; private readonly DiscordClient _discordClient; @@ -40,9 +40,6 @@ public VoiceAlertService(IDbContextFactory contextFactory, DiscordC _discordClient = discordCommandService.DiscordClient; _contextFactory = contextFactory; _eventChannel = Channel.CreateUnbounded(); -#pragma warning disable DSP0001 // Type or member is obsolete - _discordClient.VoiceStateUpdated += AddEvent; -#pragma warning restore DSP0001 // Type or member is obsolete } public Task StartAsync(CancellationToken cancellationToken) @@ -232,4 +229,7 @@ public async Task> GetVoiceAlertsAsync(ulong userId) .FirstOrDefaultAsync(x => x.Id == userId); return user?.VoiceAlerts ?? Enumerable.Empty(); } + + public Task HandleEventAsync(DiscordClient sender, VoiceStateUpdatedEventArgs eventArgs) => + AddEvent(sender, eventArgs); } \ No newline at end of file