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.

RequireOwnerAttribute.cs 2.3 kB

7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Threading.Tasks;
  3. namespace Discord.Commands
  4. {
  5. /// <summary>
  6. /// Requires the command to be invoked by the owner of the bot.
  7. /// </summary>
  8. /// <remarks>
  9. /// This precondition will restrict the access of the command or module to the owner of the Discord application.
  10. /// If the precondition fails to be met, an erroneous <see cref="PreconditionResult"/> will be returned with the
  11. /// message "Command can only be run by the owner of the bot."
  12. /// <note>
  13. /// This precondition will only work if the account has a <see cref="TokenType"/> of <see cref="TokenType.Bot"/>
  14. /// ;otherwise, this precondition will always fail.
  15. /// </note>
  16. /// </remarks>
  17. /// <example>
  18. /// The following example restricts the command to a set of sensitive commands that only the owner of the bot
  19. /// application should be able to access.
  20. /// <code language="cs">
  21. /// [RequireOwner]
  22. /// [Group("admin")]
  23. /// public class AdminModule : ModuleBase
  24. /// {
  25. /// [Command("exit")]
  26. /// public async Task ExitAsync()
  27. /// {
  28. /// Environment.Exit(0);
  29. /// }
  30. /// }
  31. /// </code>
  32. /// </example>
  33. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
  34. public class RequireOwnerAttribute : PreconditionAttribute
  35. {
  36. /// <inheritdoc />
  37. public override async Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
  38. {
  39. switch (context.Client.TokenType)
  40. {
  41. case TokenType.Bot:
  42. var application = await context.Client.GetApplicationInfoAsync().ConfigureAwait(false);
  43. if (context.User.Id != application.Owner.Id)
  44. return PreconditionResult.FromError("Command can only be run by the owner of the bot.");
  45. return PreconditionResult.FromSuccess();
  46. default:
  47. return PreconditionResult.FromError($"{nameof(RequireOwnerAttribute)} is not supported by this {nameof(TokenType)}.");
  48. }
  49. }
  50. }
  51. }