Allow commands to return a Task<RuntimeResult> (#466)
* Allow commands to return a Task<RuntimeResult>
This allows bot developers to centralize command result logic by
using result data whether the command as successful or not.
Example usage:
```csharp
var _result = await Commands.ExecuteAsync(context, argPos);
if (_result is RuntimeResult result)
{
await message.Channel.SendMessageAsync(result.Reason);
}
else if (!_result.IsSuccess)
{
// Previous error handling
}
```
The RuntimeResult class can be subclassed too, for example:
```csharp
var _result = await Commands.ExecuteAsync(context, argPos);
if (_result is MySubclassedResult result)
{
var builder = new EmbedBuilder();
for (var pair in result.Data)
{
builder.AddField(pair.Key, pair.Value, true);
}
await message.Channel.SendMessageAsync("", embed: builder);
}
else if (_result is RuntimeResult result)
{
await message.Channel.SendMessageAsync(result.Reason);
}
else if (!_result.IsSuccess)
{
// Previous error handling
}
```
* Make RuntimeResult's ctor protected
* Make RuntimeResult abstract
It never really made sense to have it instantiable in the first place,
frankly.
This commit is contained in:
committed by
RogueException
parent
b96748f9c3
commit
74f6a4b392
@@ -197,22 +197,34 @@ namespace Discord.Commands
|
|||||||
|
|
||||||
var createInstance = ReflectionUtils.CreateBuilder<IModuleBase>(typeInfo, service);
|
var createInstance = ReflectionUtils.CreateBuilder<IModuleBase>(typeInfo, service);
|
||||||
|
|
||||||
builder.Callback = async (ctx, args, map, cmd) =>
|
async Task<IResult> ExecuteCallback(ICommandContext context, object[] args, IServiceProvider services, CommandInfo cmd)
|
||||||
{
|
{
|
||||||
var instance = createInstance(map);
|
var instance = createInstance(services);
|
||||||
instance.SetContext(ctx);
|
instance.SetContext(context);
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
instance.BeforeExecute(cmd);
|
instance.BeforeExecute(cmd);
|
||||||
|
|
||||||
var task = method.Invoke(instance, args) as Task ?? Task.Delay(0);
|
var task = method.Invoke(instance, args) as Task ?? Task.Delay(0);
|
||||||
await task.ConfigureAwait(false);
|
if (task is Task<RuntimeResult> resultTask)
|
||||||
|
{
|
||||||
|
return await resultTask.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await task.ConfigureAwait(false);
|
||||||
|
return ExecuteResult.FromSuccess();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
instance.AfterExecute(cmd);
|
instance.AfterExecute(cmd);
|
||||||
(instance as IDisposable)?.Dispose();
|
(instance as IDisposable)?.Dispose();
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
|
builder.Callback = ExecuteCallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void BuildParameter(ParameterBuilder builder, System.Reflection.ParameterInfo paramInfo, int position, int count, CommandService service)
|
private static void BuildParameter(ParameterBuilder builder, System.Reflection.ParameterInfo paramInfo, int position, int count, CommandService service)
|
||||||
@@ -293,7 +305,7 @@ namespace Discord.Commands
|
|||||||
private static bool IsValidCommandDefinition(MethodInfo methodInfo)
|
private static bool IsValidCommandDefinition(MethodInfo methodInfo)
|
||||||
{
|
{
|
||||||
return methodInfo.IsDefined(typeof(CommandAttribute)) &&
|
return methodInfo.IsDefined(typeof(CommandAttribute)) &&
|
||||||
(methodInfo.ReturnType == typeof(Task) || methodInfo.ReturnType == typeof(void)) &&
|
(methodInfo.ReturnType == typeof(Task) || methodInfo.ReturnType == typeof(Task<RuntimeResult>)) &&
|
||||||
!methodInfo.IsStatic &&
|
!methodInfo.IsStatic &&
|
||||||
!methodInfo.IsGenericMethod;
|
!methodInfo.IsGenericMethod;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,9 @@
|
|||||||
UnmetPrecondition,
|
UnmetPrecondition,
|
||||||
|
|
||||||
//Execute
|
//Execute
|
||||||
Exception
|
Exception,
|
||||||
|
|
||||||
|
//Runtime
|
||||||
|
Unsuccessful
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,9 +20,9 @@ namespace Discord.Commands
|
|||||||
=> Command.CheckPreconditionsAsync(context, services);
|
=> Command.CheckPreconditionsAsync(context, services);
|
||||||
public Task<ParseResult> ParseAsync(ICommandContext context, SearchResult searchResult, PreconditionResult preconditionResult = null, IServiceProvider services = null)
|
public Task<ParseResult> ParseAsync(ICommandContext context, SearchResult searchResult, PreconditionResult preconditionResult = null, IServiceProvider services = null)
|
||||||
=> Command.ParseAsync(context, Alias.Length, searchResult, preconditionResult, services);
|
=> Command.ParseAsync(context, Alias.Length, searchResult, preconditionResult, services);
|
||||||
public Task<ExecuteResult> ExecuteAsync(ICommandContext context, IEnumerable<object> argList, IEnumerable<object> paramList, IServiceProvider services)
|
public Task<IResult> ExecuteAsync(ICommandContext context, IEnumerable<object> argList, IEnumerable<object> paramList, IServiceProvider services)
|
||||||
=> Command.ExecuteAsync(context, argList, paramList, services);
|
=> Command.ExecuteAsync(context, argList, paramList, services);
|
||||||
public Task<ExecuteResult> ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services)
|
public Task<IResult> ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services)
|
||||||
=> Command.ExecuteAsync(context, parseResult, services);
|
=> Command.ExecuteAsync(context, parseResult, services);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -120,16 +120,16 @@ namespace Discord.Commands
|
|||||||
return await CommandParser.ParseArgs(this, context, services, input, 0).ConfigureAwait(false);
|
return await CommandParser.ParseArgs(this, context, services, input, 0).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<ExecuteResult> ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services)
|
public Task<IResult> ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services)
|
||||||
{
|
{
|
||||||
if (!parseResult.IsSuccess)
|
if (!parseResult.IsSuccess)
|
||||||
return Task.FromResult(ExecuteResult.FromError(parseResult));
|
return Task.FromResult((IResult)ExecuteResult.FromError(parseResult));
|
||||||
|
|
||||||
var argList = new object[parseResult.ArgValues.Count];
|
var argList = new object[parseResult.ArgValues.Count];
|
||||||
for (int i = 0; i < parseResult.ArgValues.Count; i++)
|
for (int i = 0; i < parseResult.ArgValues.Count; i++)
|
||||||
{
|
{
|
||||||
if (!parseResult.ArgValues[i].IsSuccess)
|
if (!parseResult.ArgValues[i].IsSuccess)
|
||||||
return Task.FromResult(ExecuteResult.FromError(parseResult.ArgValues[i]));
|
return Task.FromResult((IResult)ExecuteResult.FromError(parseResult.ArgValues[i]));
|
||||||
argList[i] = parseResult.ArgValues[i].Values.First().Value;
|
argList[i] = parseResult.ArgValues[i].Values.First().Value;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,13 +137,13 @@ namespace Discord.Commands
|
|||||||
for (int i = 0; i < parseResult.ParamValues.Count; i++)
|
for (int i = 0; i < parseResult.ParamValues.Count; i++)
|
||||||
{
|
{
|
||||||
if (!parseResult.ParamValues[i].IsSuccess)
|
if (!parseResult.ParamValues[i].IsSuccess)
|
||||||
return Task.FromResult(ExecuteResult.FromError(parseResult.ParamValues[i]));
|
return Task.FromResult((IResult)ExecuteResult.FromError(parseResult.ParamValues[i]));
|
||||||
paramList[i] = parseResult.ParamValues[i].Values.First().Value;
|
paramList[i] = parseResult.ParamValues[i].Values.First().Value;
|
||||||
}
|
}
|
||||||
|
|
||||||
return ExecuteAsync(context, argList, paramList, services);
|
return ExecuteAsync(context, argList, paramList, services);
|
||||||
}
|
}
|
||||||
public async Task<ExecuteResult> ExecuteAsync(ICommandContext context, IEnumerable<object> argList, IEnumerable<object> paramList, IServiceProvider services)
|
public async Task<IResult> ExecuteAsync(ICommandContext context, IEnumerable<object> argList, IEnumerable<object> paramList, IServiceProvider services)
|
||||||
{
|
{
|
||||||
services = services ?? EmptyServiceProvider.Instance;
|
services = services ?? EmptyServiceProvider.Instance;
|
||||||
|
|
||||||
@@ -163,8 +163,7 @@ namespace Discord.Commands
|
|||||||
switch (RunMode)
|
switch (RunMode)
|
||||||
{
|
{
|
||||||
case RunMode.Sync: //Always sync
|
case RunMode.Sync: //Always sync
|
||||||
await ExecuteAsyncInternal(context, args, services).ConfigureAwait(false);
|
return await ExecuteAsyncInternal(context, args, services).ConfigureAwait(false);
|
||||||
break;
|
|
||||||
case RunMode.Async: //Always async
|
case RunMode.Async: //Always async
|
||||||
var t2 = Task.Run(async () =>
|
var t2 = Task.Run(async () =>
|
||||||
{
|
{
|
||||||
@@ -180,12 +179,26 @@ namespace Discord.Commands
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ExecuteAsyncInternal(ICommandContext context, object[] args, IServiceProvider services)
|
private async Task<IResult> ExecuteAsyncInternal(ICommandContext context, object[] args, IServiceProvider services)
|
||||||
{
|
{
|
||||||
await Module.Service._cmdLogger.DebugAsync($"Executing {GetLogText(context)}").ConfigureAwait(false);
|
await Module.Service._cmdLogger.DebugAsync($"Executing {GetLogText(context)}").ConfigureAwait(false);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await _action(context, args, services, this).ConfigureAwait(false);
|
var task = _action(context, args, services, this);
|
||||||
|
if (task is Task<IResult> resultTask)
|
||||||
|
{
|
||||||
|
var result = await resultTask.ConfigureAwait(false);
|
||||||
|
if (result is RuntimeResult execResult)
|
||||||
|
return execResult;
|
||||||
|
}
|
||||||
|
else if (task is Task<ExecuteResult> execTask)
|
||||||
|
{
|
||||||
|
return await execTask.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
await task.ConfigureAwait(false);
|
||||||
|
|
||||||
|
return ExecuteResult.FromSuccess();
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -202,8 +215,13 @@ namespace Discord.Commands
|
|||||||
else
|
else
|
||||||
ExceptionDispatchInfo.Capture(ex).Throw();
|
ExceptionDispatchInfo.Capture(ex).Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return ExecuteResult.FromError(CommandError.Exception, ex.Message);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await Module.Service._cmdLogger.VerboseAsync($"Executed {GetLogText(context)}").ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
await Module.Service._cmdLogger.VerboseAsync($"Executed {GetLogText(context)}").ConfigureAwait(false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private object[] GenerateArgs(IEnumerable<object> argList, IEnumerable<object> paramsList)
|
private object[] GenerateArgs(IEnumerable<object> argList, IEnumerable<object> paramsList)
|
||||||
|
|||||||
27
src/Discord.Net.Commands/Results/RuntimeResult.cs
Normal file
27
src/Discord.Net.Commands/Results/RuntimeResult.cs
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Discord.Commands
|
||||||
|
{
|
||||||
|
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||||
|
public abstract class RuntimeResult : IResult
|
||||||
|
{
|
||||||
|
protected RuntimeResult(CommandError? error, string reason)
|
||||||
|
{
|
||||||
|
Error = error;
|
||||||
|
Reason = reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
public CommandError? Error { get; }
|
||||||
|
public string Reason { get; }
|
||||||
|
|
||||||
|
public bool IsSuccess => !Error.HasValue;
|
||||||
|
|
||||||
|
string IResult.ErrorReason => Reason;
|
||||||
|
|
||||||
|
public override string ToString() => Reason ?? (IsSuccess ? "Successful" : "Unsuccessful");
|
||||||
|
private string DebuggerDisplay => IsSuccess ? $"Success: {Reason ?? "No Reason"}" : $"{Error}: {Reason}";
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user