Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the new dsp eventhandling #38

Merged
merged 1 commit into from
Aug 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<InteractivityExtension>();
InteractivityResult<ModalSubmittedEventArgs> result =
await interactive.WaitForModalAsync($"setLanguage-{args.User.Id}", TimeSpan.FromMinutes(5));

Expand Down Expand Up @@ -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<InteractivityExtension>();
InteractivityResult<ModalSubmittedEventArgs> result =
await interactive.WaitForModalAsync($"AnswerDM-{substring[1]}");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@

<ItemGroup>
<PackageReference Include="DeepL.net" Version="1.9.0" />
<PackageReference Include="DSharpPlus" Version="5.0.0-nightly-02317" />
<PackageReference Include="DSharpPlus.Commands" Version="5.0.0-nightly-02317" />
<PackageReference Include="DSharpPlus.Interactivity" Version="5.0.0-nightly-02312" />
<PackageReference Include="DSharpPlus.Rest" Version="5.0.0-nightly-02312" />
<PackageReference Include="DSharpPlus" Version="5.0.0-nightly-02351" />
<PackageReference Include="DSharpPlus.Commands" Version="5.0.0-nightly-02351" />
<PackageReference Include="DSharpPlus.Interactivity" Version="5.0.0-nightly-02351" />
<PackageReference Include="DSharpPlus.Rest" Version="5.0.0-nightly-02351" />
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="FlexLabs.EntityFrameworkCore.Upsert" Version="8.0.0" />
<PackageReference Include="Humanizer" Version="3.0.0-beta.54" />
Expand All @@ -42,14 +42,14 @@
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
<PackageReference Include="Quartz" Version="3.11.0" />
<PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.11.0" />
<PackageReference Include="Quartz.Extensions.Hosting" Version="3.11.0" />
<PackageReference Include="Quartz.Jobs" Version="3.11.0" />
<PackageReference Include="Quartz.Serialization.Json" Version="3.11.0" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Quartz" Version="3.13.0" />
<PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.13.0" />
<PackageReference Include="Quartz.Extensions.Hosting" Version="3.13.0" />
<PackageReference Include="Quartz.Jobs" Version="3.13.0" />
<PackageReference Include="Quartz.Serialization.Json" Version="3.13.0" />
<PackageReference Include="Serilog" Version="4.0.2-dev-02220" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.1-dev-10377" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.1-dev-10398" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Testcontainers" Version="3.9.0" />
<PackageReference Include="Testcontainers.MariaDb" Version="3.9.0" />
Expand Down
50 changes: 44 additions & 6 deletions ModularAssistentForDiscordServer/ModularDiscordBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -53,6 +63,34 @@ await Host.CreateDefaultBuilder()
})
.AddSingleton(config)
.AddDiscordClient(config.Token, DiscordIntents.All ^ DiscordIntents.GuildPresences)
.AddCommandsExtension(extension =>
{
List<Type> 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<EnsureDBEntitiesCheck>();
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 =>
{
Expand All @@ -64,6 +102,12 @@ await Host.CreateDefaultBuilder()
x.HandleComponentInteractionCreated(EventListener.OnRoleSelection);
x.HandleZombied(EventListener.OnZombied);
x.HandleMessageCreated(EventListener.DmHandler);

x.AddEventHandlers<LoggingService>(ServiceLifetime.Singleton);
x.AddEventHandlers<MessageSnipeService>(ServiceLifetime.Singleton);
x.AddEventHandlers<StarboardService>(ServiceLifetime.Singleton);
x.AddEventHandlers<VoiceAlertService>(ServiceLifetime.Singleton);
x.AddEventHandlers<AntiPhishingService>();
})
.Configure<RestClientOptions>(x =>
{
Expand Down Expand Up @@ -100,20 +144,14 @@ await Host.CreateDefaultBuilder()
options.StartDelay = TimeSpan.FromSeconds(10);
options.AwaitApplicationStarted = true;
})
.AddSingleton<MessageSnipeService>()
.AddHostedService(s => s.GetRequiredService<MessageSnipeService>())
.AddSingleton<QuotesService>()
.AddSingleton<StarboardService>()
.AddHostedService(s => s.GetRequiredService<StarboardService>())
.AddSingleton<ReminderService>()
.AddHostedService(s => s.GetRequiredService<ReminderService>())
.AddSingleton<VoiceAlertService>()
.AddHostedService(s => s.GetRequiredService<VoiceAlertService>())
.AddSingleton(new Translator(_config.DeeplApiKey ?? ""))
.AddSingleton<TranslateInformationService>()
.AddSingleton<LoggingService>()
.AddSingleton<UserManagerService>()
.AddSingleton<AntiPhishingService>()
.AddHttpClient();

Services = services.BuildServiceProvider();
Expand Down
10 changes: 5 additions & 5 deletions ModularAssistentForDiscordServer/Services/AntiPhishingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

namespace MADS.Services;

public partial class AntiPhishingService
public partial class AntiPhishingService : IEventHandler<MessageCreatedEventArgs>, IEventHandler<MessageUpdatedEventArgs>
{
private readonly DiscordClient _discordClient;
private readonly HttpClient _antiFishClient;
Expand Down Expand Up @@ -65,10 +65,6 @@ public AntiPhishingService(DiscordClient discordClient, ILogger<AntiPhishingServ

_phishggClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent",
"MadsDiscordBot (https://github.com/Plerx2493/Mads, v1)");


discordClient.MessageCreated += HandleMessage;
discordClient.MessageUpdated += HandleMessageUpdate;
}

private Task HandleMessageUpdate(DiscordClient sender, MessageUpdatedEventArgs args)
Expand Down Expand Up @@ -194,4 +190,8 @@ private async Task HandleMessage(DiscordClient sender, MessageCreatedEventArgs a

return responses;
}

public Task HandleEventAsync(DiscordClient sender, MessageCreatedEventArgs eventArgs) => HandleMessage(sender, eventArgs);

public Task HandleEventAsync(DiscordClient sender, MessageUpdatedEventArgs eventArgs) => HandleMessageUpdate(sender, eventArgs);
}
51 changes: 7 additions & 44 deletions ModularAssistentForDiscordServer/Services/DiscordCommandService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<DiscordCommandService>();

public DiscordCommandService
(
DiscordClient discordClient,
Expand All @@ -52,49 +52,12 @@ MadsConfig config
DiscordClient = discordClient;
StartTime = DateTime.Now;
DbContextFactory = dbContextFactory;

List<Type> 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<EnsureDBEntitiesCheck>();
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<string> pendingMigrations = await context.Database.GetPendingMigrationsAsync(cancellationToken);
Expand All @@ -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();
Expand Down
17 changes: 5 additions & 12 deletions ModularAssistentForDiscordServer/Services/LoggingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,12 @@

namespace MADS.Services;

public class LoggingService
public class LoggingService : IEventHandler<ComponentInteractionCreatedEventArgs>, IEventHandler<ModalSubmittedEventArgs>
{
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();
}

Expand Down Expand Up @@ -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);
}
22 changes: 5 additions & 17 deletions ModularAssistentForDiscordServer/Services/MessageSnipeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

namespace MADS.Services;

public class MessageSnipeService : IHostedService
public class MessageSnipeService : IEventHandler<MessageUpdatedEventArgs>, IEventHandler<MessageDeletedEventArgs>
{
private readonly IMemoryCache _memoryCache;
private readonly MemoryCacheEntryOptions _options;
Expand All @@ -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
Expand Down Expand Up @@ -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);
}
Loading
Loading