You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

RequireContextAttribute.cs 2.1 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Threading.Tasks;
  3. using Microsoft.Extensions.DependencyInjection;
  4. namespace Discord.Commands
  5. {
  6. [Flags]
  7. public enum ContextType
  8. {
  9. Guild = 0x01,
  10. DM = 0x02,
  11. Group = 0x04
  12. }
  13. /// <summary>
  14. /// Require that the command be invoked in a specified context.
  15. /// </summary>
  16. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
  17. public class RequireContextAttribute : PreconditionAttribute
  18. {
  19. public ContextType Contexts { get; }
  20. /// <summary>
  21. /// Require that the command be invoked in a specified context.
  22. /// </summary>
  23. /// <param name="contexts">The type of context the command can be invoked in. Multiple contexts can be specified by ORing the contexts together.</param>
  24. /// <example>
  25. /// <code language="c#">
  26. /// [Command("private_only")]
  27. /// [RequireContext(ContextType.DM | ContextType.Group)]
  28. /// public async Task PrivateOnly()
  29. /// {
  30. /// }
  31. /// </code>
  32. /// </example>
  33. public RequireContextAttribute(ContextType contexts)
  34. {
  35. Contexts = contexts;
  36. }
  37. public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
  38. {
  39. bool isValid = false;
  40. if ((Contexts & ContextType.Guild) != 0)
  41. isValid = isValid || context.Channel is IGuildChannel;
  42. if ((Contexts & ContextType.DM) != 0)
  43. isValid = isValid || context.Channel is IDMChannel;
  44. if ((Contexts & ContextType.Group) != 0)
  45. isValid = isValid || context.Channel is IGroupChannel;
  46. if (isValid)
  47. return Task.FromResult(PreconditionResult.FromSuccess());
  48. else
  49. return Task.FromResult(PreconditionResult.FromError($"Invalid context for command; accepted contexts: {Contexts}"));
  50. }
  51. }
  52. }