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.5 kB

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