Add and use interaction command hooks for BeforeExecute, AfterExecute, OnException and GetExceptionResponse

This commit is contained in:
Daan Boerlage 2021-10-30 14:43:57 +02:00
parent 9a2bf84a05
commit 24749d9009
Signed by: daan
GPG key ID: FCE070E1E4956606
3 changed files with 43 additions and 7 deletions

View file

@ -1,9 +1,13 @@
using System;
using Geekbot.Core.Interactions.Response;
namespace Geekbot.Core.Interactions namespace Geekbot.Core.Interactions
{ {
public interface IInteractionBase public interface IInteractionBase
{ {
void BeforeExecute(); void BeforeExecute();
void AfterExecute(); void AfterExecute();
void OnException(); void OnException(Exception e);
InteractionResponse GetExceptionResponse();
} }
} }

View file

@ -1,3 +1,4 @@
using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Geekbot.Core.Interactions.ApplicationCommand; using Geekbot.Core.Interactions.ApplicationCommand;
using Geekbot.Core.Interactions.Request; using Geekbot.Core.Interactions.Request;
@ -7,25 +8,41 @@ namespace Geekbot.Core.Interactions
{ {
public abstract class InteractionBase : IInteractionBase public abstract class InteractionBase : IInteractionBase
{ {
protected virtual void BeforeExecute() public InteractionBase() {}
{
}
protected virtual void AfterExecute() public virtual void BeforeExecute()
{ {
} }
protected virtual void OnException() public virtual void AfterExecute()
{ {
} }
public virtual void OnException(Exception exception)
{
}
public virtual InteractionResponse GetExceptionResponse()
{
return new InteractionResponse()
{
Type = InteractionResponseType.ChannelMessageWithSource,
Data = new()
{
Content = "Something went wrong :confused:"
}
};
}
public abstract Command GetCommandInfo(); public abstract Command GetCommandInfo();
public abstract Task<InteractionResponse> Exec(Interaction interaction); public abstract Task<InteractionResponse> Exec(Interaction interaction);
void IInteractionBase.BeforeExecute() => this.BeforeExecute(); void IInteractionBase.BeforeExecute() => this.BeforeExecute();
void IInteractionBase.AfterExecute() => this.AfterExecute(); void IInteractionBase.AfterExecute() => this.AfterExecute();
void IInteractionBase.OnException() => this.OnException(); void IInteractionBase.OnException(Exception e) => this.OnException(e);
InteractionResponse IInteractionBase.GetExceptionResponse() => this.GetExceptionResponse();
} }
} }

View file

@ -41,7 +41,22 @@ namespace Geekbot.Core.Interactions
var type = _commands[interaction.Data.Name]; var type = _commands[interaction.Data.Name];
var command = (InteractionBase)Activator.CreateInstance(type); var command = (InteractionBase)Activator.CreateInstance(type);
return await command.Exec(interaction); InteractionResponse response;
command.BeforeExecute();
try
{
response = await command.Exec(interaction);
}
catch (Exception e)
{
command.OnException(e);
response = command.GetExceptionResponse();
}
finally
{
command.AfterExecute();
}
return response;
} }
} }
} }