Skip to content

Commit

Permalink
Refactor suggestion autocompleter and improve event handling
Browse files Browse the repository at this point in the history
This update streamlines code in SuggestionAutocompleter by grouping suggestion retrieval operations and abstracting formatted AutocompleteResult creation into a separate method. Additionally, it extends EventHandler through addition of AuditLogCreated event. NewLogCommandService is also tweaked to utilize this new event for UserBanned and UserUnbanned events, providing improved accuracy and efficiency during these circumstances.
  • Loading branch information
sylveonnotdeko committed Dec 25, 2023
1 parent 63afa4a commit 157dde4
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 31 deletions.
22 changes: 14 additions & 8 deletions src/Mewdeko/Common/Autocompleters/SuggestionAutocomplete.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,27 @@ namespace Mewdeko.Common.Autocompleters;

public class SuggestionAutocompleter : AutocompleteHandler
{
private readonly SuggestionsService suggest;

public SuggestionAutocompleter(SuggestionsService suggest)
=> this.suggest = suggest;

private readonly SuggestionsService suggest;

public override Task<AutocompletionResult> GenerateSuggestionsAsync(IInteractionContext context, IAutocompleteInteraction interaction, IParameterInfo parameter,
IServiceProvider services)
public override Task<AutocompletionResult> GenerateSuggestionsAsync(IInteractionContext context,
IAutocompleteInteraction interaction, IParameterInfo parameter, IServiceProvider services)
{
var content = (string)interaction.Data.Current.Value;
var suggestions = suggest.Suggestions(context.Guild?.Id ?? 0);

return Task.FromResult(AutocompletionResult.FromSuccess(suggest.Suggestions(context.Guild?.Id ?? 0)
.Where(x => $"{x.SuggestionId}{x.Suggestion}".Contains(content))
return Task.FromResult(AutocompletionResult.FromSuccess(suggestions
.Where(x => x.Suggestion.Contains(content) || x.SuggestionId.ToString().Contains(content))
.OrderByDescending(x => x.Suggestion.StartsWith(content))
.ThenByDescending(x => x.SuggestionId.ToString().StartsWith(content))
.Select(x =>
new AutocompleteResult($"{x.SuggestionId} | {x.Suggestion}".TrimTo(100), x.SuggestionId))));
.Select(CreateAutocompleteResult)));
}

private static AutocompleteResult CreateAutocompleteResult(SuggestionsModel x)
{
var formattedResult = $"{x.SuggestionId} | {x.Suggestion}".TrimTo(100);
return new AutocompleteResult(formattedResult, x.SuggestionId);
}
}
36 changes: 22 additions & 14 deletions src/Mewdeko/Modules/Administration/Services/NewLogCommandService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Mewdeko.Modules.Moderation.Services;
using Discord.Rest;
using Mewdeko.Modules.Moderation.Services;
using Microsoft.EntityFrameworkCore;

namespace Mewdeko.Modules.Administration.Services;
Expand Down Expand Up @@ -76,14 +77,13 @@ public NewLogCommandService(DbService db, IDataCache cache, DiscordSocketClient
handler.MessageDeleted += OnMessageDeleted;
handler.UserJoined += OnUserJoined;
handler.UserLeft += OnUserLeft;
handler.UserBanned += OnUserBanned;
handler.UserUnbanned += OnUserUnbanned;
handler.UserUpdated += OnUserUpdated;
handler.ChannelCreated += OnChannelCreated;
handler.ChannelDestroyed += OnChannelDestroyed;
handler.ChannelUpdated += OnChannelUpdated;
handler.UserVoiceStateUpdated += OnVoicePresence;
handler.UserVoiceStateUpdated += OnVoicePresenceTts;
handler.AuditLogCreated += OnAuditLogCreated;
muteService.UserMuted += OnUserMuted;
muteService.UserUnmuted += OnUserUnmuted;

Expand All @@ -101,6 +101,21 @@ public NewLogCommandService(DbService db, IDataCache cache, DiscordSocketClient
.ToConcurrent();
}

private async Task OnAuditLogCreated(SocketAuditLogEntry args, SocketGuild arsg2)
{
if (args.Action == ActionType.Ban)
{
var data = args.Data as BanAuditLogData;
await OnUserBanned(data.Target, arsg2, args.User);
}

if (args.Action == ActionType.Unban)
{
var data = args.Data as UnbanAuditLogData;
await OnUserUnbanned(data.Target, arsg2, args.User);
}
}


private async Task OnRoleCreated(SocketRole args)
{
Expand Down Expand Up @@ -843,7 +858,7 @@ private async Task OnUserLeft(IGuild guild, IUser arsg2)
}
}

private async Task OnUserBanned(SocketUser args, SocketGuild arsg2)
private async Task OnUserBanned(IUser args, SocketGuild arsg2, SocketUser bannedBy)
{
if (args is not SocketGuildUser usr) return;
if (GuildLogSettings.TryGetValue(arsg2.Id, out var logSetting))
Expand All @@ -856,10 +871,6 @@ private async Task OnUserBanned(SocketUser args, SocketGuild arsg2)
if (channel is null)
return;

var auditLogs = await arsg2.GetAuditLogsAsync(1, actionType: ActionType.Ban).FlattenAsync();

var entry = auditLogs.FirstOrDefault();

var eb = new EmbedBuilder()
.WithOkColor()
.WithTitle("User Banned")
Expand All @@ -870,7 +881,7 @@ private async Task OnUserBanned(SocketUser args, SocketGuild arsg2)
$"`Account Created:` {args.CreatedAt:dd/MM/yyyy}\n" +
$"`Joined Server:` {usr.JoinedAt:dd/MM/yyyy}\n" +
$"`Roles:` {string.Join(", ", usr.Roles.Select(x => x.Mention))}\n" +
$"`Banned By:` {entry.User.Mention} | {entry.User.Id}")
$"`Banned By:` {bannedBy.Mention} | {bannedBy.Id}")
.WithThumbnailUrl(args.RealAvatarUrl().ToString());

var component = new ComponentBuilder().WithButton("View User (May not work)", style: ButtonStyle.Link,
Expand All @@ -880,7 +891,7 @@ private async Task OnUserBanned(SocketUser args, SocketGuild arsg2)
}
}

private async Task OnUserUnbanned(SocketUser args, SocketGuild arsg2)
private async Task OnUserUnbanned(IUser args, SocketGuild arsg2, SocketUser unbannedBy)
{
if (GuildLogSettings.TryGetValue(arsg2.Id, out var logSetting))
{
Expand All @@ -892,9 +903,6 @@ private async Task OnUserUnbanned(SocketUser args, SocketGuild arsg2)
if (channel is null)
return;

var auditLogs = await arsg2.GetAuditLogsAsync(1, actionType: ActionType.Unban).FlattenAsync();

var entry = auditLogs.FirstOrDefault();

var eb = new EmbedBuilder()
.WithOkColor()
Expand All @@ -904,7 +912,7 @@ private async Task OnUserUnbanned(SocketUser args, SocketGuild arsg2)
$"`User Id:` {args.Id}" +
$"`User Global Name:` {args.GlobalName ?? args.Username}" +
$"`Account Created:` {args.CreatedAt:dd/MM/yyyy}\n" +
$"`Unbanned By:` {entry.User.Mention} | {entry.User.Id}")
$"`Unbanned By:` {unbannedBy.Mention} | {unbannedBy.Id}")
.WithThumbnailUrl(args.RealAvatarUrl().ToString());

var component = new ComponentBuilder().WithButton("View User (May not work)", style: ButtonStyle.Link,
Expand Down
40 changes: 31 additions & 9 deletions src/Mewdeko/Services/Impl/EventHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ public class EventHandler

public delegate Task AsyncEventHandler<in TEventArgs, in TArgs>(TEventArgs args, TArgs arsg2);

public delegate Task AsyncEventHandler<in TEventArgs, in TArgs, in TEvent>(TEventArgs args, TArgs args2, TEvent args3);
public delegate Task AsyncEventHandler<in TEventArgs, in TArgs, in TEvent>(TEventArgs args, TArgs args2,
TEvent args3);

public delegate Task AsyncEventHandler<in TEventArgs, in TArgs, in TEvent, in TArgs2>(TEventArgs args, TArgs args2, TEvent args3, TArgs2 args4);
public delegate Task AsyncEventHandler<in TEventArgs, in TArgs, in TEvent, in TArgs2>(TEventArgs args, TArgs args2,
TEvent args3, TArgs2 args4);

// Actual events
public event AsyncEventHandler<SocketMessage>? MessageReceived;
Expand All @@ -22,7 +24,10 @@ public class EventHandler
public event AsyncEventHandler<Cacheable<IMessage, ulong>, Cacheable<IMessageChannel, ulong>>? MessageDeleted;
public event AsyncEventHandler<Cacheable<SocketGuildUser, ulong>, SocketGuildUser>? GuildMemberUpdated;
public event AsyncEventHandler<Cacheable<IMessage, ulong>, SocketMessage, ISocketMessageChannel>? MessageUpdated;
public event AsyncEventHandler<IReadOnlyCollection<Cacheable<IMessage, ulong>>, Cacheable<IMessageChannel, ulong>>? MessagesBulkDeleted;

public event AsyncEventHandler<IReadOnlyCollection<Cacheable<IMessage, ulong>>, Cacheable<IMessageChannel, ulong>>?
MessagesBulkDeleted;

public event AsyncEventHandler<SocketUser, SocketGuild>? UserBanned;
public event AsyncEventHandler<SocketUser, SocketGuild>? UserUnbanned;
public event AsyncEventHandler<SocketUser, SocketUser>? UserUpdated;
Expand All @@ -31,8 +36,13 @@ public class EventHandler
public event AsyncEventHandler<SocketChannel>? ChannelDestroyed;
public event AsyncEventHandler<SocketChannel, SocketChannel>? ChannelUpdated;
public event AsyncEventHandler<SocketRole>? RoleDeleted;
public event AsyncEventHandler<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, SocketReaction>? ReactionAdded;
public event AsyncEventHandler<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, SocketReaction>? ReactionRemoved;

public event AsyncEventHandler<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, SocketReaction>?
ReactionAdded;

public event AsyncEventHandler<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, SocketReaction>?
ReactionRemoved;

public event AsyncEventHandler<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>>? ReactionsCleared;
public event AsyncEventHandler<SocketInteraction>? InteractionCreated;
public event AsyncEventHandler<Cacheable<IUser, ulong>, Cacheable<IMessageChannel, ulong>>? UserIsTyping;
Expand All @@ -43,6 +53,7 @@ public class EventHandler
public event AsyncEventHandler<Cacheable<SocketThreadChannel, ulong>>? ThreadDeleted;
public event AsyncEventHandler<SocketThreadUser>? ThreadMemberJoined;
public event AsyncEventHandler<SocketThreadUser>? ThreadMemberLeft;
public event AsyncEventHandler<SocketAuditLogEntry, SocketGuild>? AuditLogCreated;
public event AsyncEventHandler<DiscordSocketClient>? Ready;

private readonly DiscordSocketClient client;
Expand Down Expand Up @@ -82,9 +93,17 @@ public EventHandler(DiscordSocketClient client)
client.ThreadDeleted += ClientOnThreadDeleted;
client.ThreadMemberJoined += ClientOnThreadMemberJoined;
client.ThreadMemberLeft += ClientOnThreadMemberLeft;
client.AuditLogCreated += ClientOnAuditLogCreated;
client.Ready += ClientOnReady;
}

private Task ClientOnAuditLogCreated(SocketAuditLogEntry arg1, SocketGuild arg2)
{
if (AuditLogCreated is not null)
_ = AuditLogCreated(arg1, arg2);
return Task.CompletedTask;
}

private Task ClientOnReady()
{
if (Ready is not null)
Expand Down Expand Up @@ -130,7 +149,7 @@ private Task ClientOnThreadCreated(SocketThreadChannel arg)

private Task ClientOnJoinedGuild(SocketGuild arg)
{
if (PresenceUpdated is not null)
if (JoinedGuild is not null)
_ = JoinedGuild(arg);
return Task.CompletedTask;
}
Expand Down Expand Up @@ -162,14 +181,16 @@ private Task ClientOnReactionsCleared(Cacheable<IUserMessage, ulong> arg1, Cache
return Task.CompletedTask;
}

private Task ClientOnReactionRemoved(Cacheable<IUserMessage, ulong> arg1, Cacheable<IMessageChannel, ulong> arg2, SocketReaction arg3)
private Task ClientOnReactionRemoved(Cacheable<IUserMessage, ulong> arg1, Cacheable<IMessageChannel, ulong> arg2,
SocketReaction arg3)
{
if (ReactionRemoved is not null)
_ = ReactionRemoved(arg1, arg2, arg3);
return Task.CompletedTask;
}

private Task ClientOnReactionAdded(Cacheable<IUserMessage, ulong> arg1, Cacheable<IMessageChannel, ulong> arg2, SocketReaction arg3)
private Task ClientOnReactionAdded(Cacheable<IUserMessage, ulong> arg1, Cacheable<IMessageChannel, ulong> arg2,
SocketReaction arg3)
{
if (ReactionAdded is not null)
_ = ReactionAdded(arg1, arg2, arg3);
Expand Down Expand Up @@ -232,7 +253,8 @@ private Task ClientOnUserBanned(SocketUser arg1, SocketGuild arg2)
return Task.CompletedTask;
}

private Task ClientOnMessagesBulkDeleted(IReadOnlyCollection<Cacheable<IMessage, ulong>> arg1, Cacheable<IMessageChannel, ulong> arg2)
private Task ClientOnMessagesBulkDeleted(IReadOnlyCollection<Cacheable<IMessage, ulong>> arg1,
Cacheable<IMessageChannel, ulong> arg2)
{
if (MessagesBulkDeleted is not null)
_ = MessagesBulkDeleted(arg1, arg2);
Expand Down

0 comments on commit 157dde4

Please sign in to comment.