Browse Source

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.
tags/1.0
Finite Reality RogueException 7 years ago
parent
commit
74f6a4b392
5 changed files with 86 additions and 26 deletions
  1. +18
    -6
      src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs
  2. +4
    -1
      src/Discord.Net.Commands/CommandError.cs
  3. +2
    -2
      src/Discord.Net.Commands/CommandMatch.cs
  4. +35
    -17
      src/Discord.Net.Commands/Info/CommandInfo.cs
  5. +27
    -0
      src/Discord.Net.Commands/Results/RuntimeResult.cs

+ 18
- 6
src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs View File

@@ -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);
instance.SetContext(ctx);
var instance = createInstance(services);
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;
} }


+ 4
- 1
src/Discord.Net.Commands/CommandError.cs View File

@@ -18,6 +18,9 @@
UnmetPrecondition, UnmetPrecondition,


//Execute //Execute
Exception
Exception,

//Runtime
Unsuccessful
} }
} }

+ 2
- 2
src/Discord.Net.Commands/CommandMatch.cs View File

@@ -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);
} }
} }

+ 35
- 17
src/Discord.Net.Commands/Info/CommandInfo.cs View File

@@ -36,14 +36,14 @@ namespace Discord.Commands
internal CommandInfo(CommandBuilder builder, ModuleInfo module, CommandService service) internal CommandInfo(CommandBuilder builder, ModuleInfo module, CommandService service)
{ {
Module = module; Module = module;
Name = builder.Name; Name = builder.Name;
Summary = builder.Summary; Summary = builder.Summary;
Remarks = builder.Remarks; Remarks = builder.Remarks;


RunMode = (builder.RunMode == RunMode.Default ? service._defaultRunMode : builder.RunMode); RunMode = (builder.RunMode == RunMode.Default ? service._defaultRunMode : builder.RunMode);
Priority = builder.Priority; Priority = builder.Priority;
Aliases = module.Aliases Aliases = module.Aliases
.Permutate(builder.Aliases, (first, second) => .Permutate(builder.Aliases, (first, second) =>
{ {
@@ -106,7 +106,7 @@ namespace Discord.Commands


return PreconditionResult.FromSuccess(); return PreconditionResult.FromSuccess();
} }
public async Task<ParseResult> ParseAsync(ICommandContext context, int startIndex, SearchResult searchResult, PreconditionResult preconditionResult = null, IServiceProvider services = null) public async Task<ParseResult> ParseAsync(ICommandContext context, int startIndex, SearchResult searchResult, PreconditionResult preconditionResult = null, IServiceProvider services = null)
{ {
services = services ?? EmptyServiceProvider.Instance; services = services ?? EmptyServiceProvider.Instance;
@@ -115,35 +115,35 @@ namespace Discord.Commands
return ParseResult.FromError(searchResult); return ParseResult.FromError(searchResult);
if (preconditionResult != null && !preconditionResult.IsSuccess) if (preconditionResult != null && !preconditionResult.IsSuccess)
return ParseResult.FromError(preconditionResult); return ParseResult.FromError(preconditionResult);
string input = searchResult.Text.Substring(startIndex); string input = searchResult.Text.Substring(startIndex);
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;
} }
var paramList = new object[parseResult.ParamValues.Count]; var paramList = new object[parseResult.ParamValues.Count];
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,10 +163,9 @@ namespace Discord.Commands
switch (RunMode) switch (RunMode)
{ {
case RunMode.Sync: //Always sync case RunMode.Sync: //Always sync
await ExecuteAsyncInternal(context, args, services).ConfigureAwait(false);
break;
return await ExecuteAsyncInternal(context, args, services).ConfigureAwait(false);
case RunMode.Async: //Always async case RunMode.Async: //Always async
var t2 = Task.Run(async () =>
var t2 = Task.Run(async () =>
{ {
await ExecuteAsyncInternal(context, args, services).ConfigureAwait(false); await ExecuteAsyncInternal(context, args, services).ConfigureAwait(false);
}); });
@@ -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)
@@ -240,7 +258,7 @@ namespace Discord.Commands
=> paramsList.Cast<T>().ToArray(); => paramsList.Cast<T>().ToArray();


internal string GetLogText(ICommandContext context) internal string GetLogText(ICommandContext context)
{
{
if (context.Guild != null) if (context.Guild != null)
return $"\"{Name}\" for {context.User} in {context.Guild}/{context.Channel}"; return $"\"{Name}\" for {context.User} in {context.Guild}/{context.Channel}";
else else


+ 27
- 0
src/Discord.Net.Commands/Results/RuntimeResult.cs View 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}";
}
}

Loading…
Cancel
Save