Files
Discord.Net/src/Discord.Net.Commands/Attributes/Preconditions/RequireContextAttribute.cs
Christopher F 14fbe40cbc Add Async suffix to command-related Tasks (#804)
commit b7fb44a94fb1e75f696f281d6b201eba3f48e864
Author: Hsu Still <341464@gmail.com>
Date:   Sat Sep 2 14:34:18 2017 +0800

    Fix more async naming violation

commit e6912e2d020c69325826dbfa62c07cd1ef2cc45f
Author: Hsu Still <341464@gmail.com>
Date:   Sat Sep 2 14:23:04 2017 +0800

    Fix incorrect null xmldocs string

commit da8d23222d207853375c3512232d1d7fd3629cad
Author: Hsu Still <341464@gmail.com>
Date:   Sat Sep 2 14:17:12 2017 +0800

    Fix CheckPreconditionsAsync

commit 992407407a42fec9087c9ed18e0bf5de30dff82c
Author: Hsu Still <341464@gmail.com>
Date:   Sat Sep 2 14:07:12 2017 +0800

    Add Async suffix to abstract Task methods
2017-10-09 19:45:12 -04:00

59 lines
2.0 KiB
C#

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace Discord.Commands
{
[Flags]
public enum ContextType
{
Guild = 0x01,
DM = 0x02,
Group = 0x04
}
/// <summary>
/// Require that the command be invoked in a specified context.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class RequireContextAttribute : PreconditionAttribute
{
public ContextType Contexts { get; }
/// <summary>
/// Require that the command be invoked in a specified context.
/// </summary>
/// <param name="contexts">The type of context the command can be invoked in. Multiple contexts can be specified by ORing the contexts together.</param>
/// <example>
/// <code language="c#">
/// [Command("private_only")]
/// [RequireContext(ContextType.DM | ContextType.Group)]
/// public async Task PrivateOnly()
/// {
/// }
/// </code>
/// </example>
public RequireContextAttribute(ContextType contexts)
{
Contexts = contexts;
}
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
{
bool isValid = false;
if ((Contexts & ContextType.Guild) != 0)
isValid = isValid || context.Channel is IGuildChannel;
if ((Contexts & ContextType.DM) != 0)
isValid = isValid || context.Channel is IDMChannel;
if ((Contexts & ContextType.Group) != 0)
isValid = isValid || context.Channel is IGroupChannel;
if (isValid)
return Task.FromResult(PreconditionResult.FromSuccess());
else
return Task.FromResult(PreconditionResult.FromError($"Invalid context for command; accepted contexts: {Contexts}"));
}
}
}