Skip to content

Commit

Permalink
[Bot -> Services] Cleanup work in command service.
Browse files Browse the repository at this point in the history
  • Loading branch information
AnalogFeelings committed Apr 13, 2024
1 parent 894b253 commit b6ecafb
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 51 deletions.
1 change: 1 addition & 0 deletions SammBot.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/BLANK_LINES_INSIDE_REGION/@EntryValue">0</s:Int64>
<s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderRegionName/@EntryValue">License Information (GPLv3)</s:String>
<s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderText/@EntryValue">Samm-Bot - A lightweight Discord.NET bot for moderation and other purposes.
Copyright (C) 2021-${CurrentDate.Year} Analog Feelings
Expand Down
94 changes: 43 additions & 51 deletions Source/SammBot.Bot/Services/CommandService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,39 +25,48 @@
using SammBot.Library;
using SammBot.Library.Extensions;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;

namespace SammBot.Bot.Services;

public class CommandService
{
private DiscordShardedClient ShardedClient { get; }
private IServiceProvider ServiceProvider { get; }
private MatchaLogger Logger { get; }

private InteractionService InteractionService { get; }
private EventLoggingService EventLoggingService { get; }
private readonly DiscordShardedClient _shardedClient;
private readonly IServiceProvider _serviceProvider;
private readonly MatchaLogger _logger;
private readonly InteractionService _interactionService;
private readonly EventLoggingService _eventLoggingService;

public CommandService(IServiceProvider services)
{
ServiceProvider = services;
_serviceProvider = services;

InteractionService = ServiceProvider.GetRequiredService<InteractionService>();
ShardedClient = ServiceProvider.GetRequiredService<DiscordShardedClient>();
Logger = ServiceProvider.GetRequiredService<MatchaLogger>();
EventLoggingService = ServiceProvider.GetRequiredService<EventLoggingService>();
_interactionService = _serviceProvider.GetRequiredService<InteractionService>();
_shardedClient = _serviceProvider.GetRequiredService<DiscordShardedClient>();
_logger = _serviceProvider.GetRequiredService<MatchaLogger>();
_eventLoggingService = _serviceProvider.GetRequiredService<EventLoggingService>();
}

public async Task InitializeHandlerAsync()
{
await InteractionService.AddModulesAsync(Assembly.GetEntryAssembly(), ServiceProvider);
await _interactionService.AddModulesAsync(Assembly.GetEntryAssembly(), _serviceProvider);

_shardedClient.InteractionCreated += HandleInteractionAsync;
_interactionService.InteractionExecuted += OnInteractionExecutedAsync;

ShardedClient.InteractionCreated += HandleInteractionAsync;
_shardedClient.UserJoined += _eventLoggingService.OnUserJoinedAsync;
_shardedClient.UserLeft += _eventLoggingService.OnUserLeftAsync;

InteractionService.InteractionExecuted += OnInteractionExecutedAsync;
_shardedClient.MessageDeleted += _eventLoggingService.OnMessageDeleted;
_shardedClient.MessagesBulkDeleted += _eventLoggingService.OnMessagesBulkDeleted;

AddEventHandlersAsync();
_shardedClient.RoleCreated += _eventLoggingService.OnRoleCreated;
_shardedClient.RoleUpdated += _eventLoggingService.OnRoleUpdated;

_shardedClient.UserBanned += _eventLoggingService.OnUserBanned;
_shardedClient.UserUnbanned += _eventLoggingService.OnUserUnbanned;
}

private async Task OnInteractionExecutedAsync(ICommandInfo slashCommand, IInteractionContext context, IResult result)
Expand All @@ -66,23 +75,15 @@ private async Task OnInteractionExecutedAsync(ICommandInfo slashCommand, IIntera
{
if (!result.IsSuccess)
{
string finalMessage;

EmbedBuilder replyEmbed = new EmbedBuilder().BuildErrorEmbed((ShardedInteractionContext)context);

switch (result.Error)
replyEmbed.Description = result.Error switch
{
case InteractionCommandError.BadArgs:
finalMessage = $"You provided an incorrect number of parameters!\nUse the `/help " +
$"{slashCommand.Module.Name} {slashCommand.Name}` command to see all of the parameters.";
break;
default:
finalMessage = result.ErrorReason;
break;
}

replyEmbed.Description = finalMessage;

InteractionCommandError.BadArgs => $"You provided an incorrect number of parameters!\nUse the `/help " +
$"{slashCommand.Module.Name} {slashCommand.Name}` command to see all of the parameters.",
_ => result.ErrorReason
};

if (context.Interaction.HasResponded)
await context.Interaction.FollowupAsync(embed: replyEmbed.Build(), ephemeral: true, allowedMentions: Constants.AllowOnlyUsers);
else
Expand All @@ -91,41 +92,32 @@ private async Task OnInteractionExecutedAsync(ICommandInfo slashCommand, IIntera
}
catch (Exception ex)
{
await Logger.LogAsync(LogSeverity.Error, "An exception occurred during post-execution handling: {0}", ex);
await _logger.LogAsync(LogSeverity.Error, "An exception occurred during post-execution handling: {0}", ex);
}
}

private async Task HandleInteractionAsync(SocketInteraction interaction)
{
ShardedInteractionContext context = new ShardedInteractionContext(ShardedClient, interaction);
ShardedInteractionContext context = new ShardedInteractionContext(_shardedClient, interaction);

if (SettingsManager.Instance.LoadedConfig.OnlyOwnerMode)
{
IApplication botApplication = await ShardedClient.GetApplicationInfoAsync();
IApplication botApplication = await _shardedClient.GetApplicationInfoAsync();

if (interaction.User.Id != botApplication.Owner.Id) return;
}

string formattedLog = SettingsManager.Instance.LoadedConfig.CommandLogFormat.Replace("%username%", interaction.User.GetFullUsername())
.Replace("%channelname%", interaction.Channel.Name);

await Logger.LogAsync(LogSeverity.Debug, formattedLog);

await InteractionService.ExecuteCommandAsync(context, ServiceProvider);
}

private void AddEventHandlersAsync()
{
ShardedClient.UserJoined += EventLoggingService.OnUserJoinedAsync;
ShardedClient.UserLeft += EventLoggingService.OnUserLeftAsync;

ShardedClient.MessageDeleted += EventLoggingService.OnMessageDeleted;
ShardedClient.MessagesBulkDeleted += EventLoggingService.OnMessagesBulkDeleted;
#if DEBUG
Dictionary<string, object> template = new Dictionary<string, object>()
{
["username"] = interaction.User.GetFullUsername(),
["channelname"] = interaction.Channel.Name
};
string formattedLog = SettingsManager.Instance.LoadedConfig.CommandLogFormat.TemplateReplace(template);

ShardedClient.RoleCreated += EventLoggingService.OnRoleCreated;
ShardedClient.RoleUpdated += EventLoggingService.OnRoleUpdated;
await _logger.LogAsync(LogSeverity.Debug, formattedLog);
#endif

ShardedClient.UserBanned += EventLoggingService.OnUserBanned;
ShardedClient.UserUnbanned += EventLoggingService.OnUserUnbanned;
await _interactionService.ExecuteCommandAsync(context, _serviceProvider);
}
}

0 comments on commit b6ecafb

Please sign in to comment.