예제 #1
0
 public OverwrittenPermissionState GetPermissionState(DiscordPermission permission)
 {
     if (Allow.HasFlag(permission))
     {
         return(OverwrittenPermissionState.Allow);
     }
     else if (Deny.HasFlag(permission))
     {
         return(OverwrittenPermissionState.Deny);
     }
     else
     {
         return(OverwrittenPermissionState.Inherit);
     }
 }
예제 #2
0
        internal DiscordUserGuild(DiscordApiData data)
            : base(data)
        {
            Name    = data.GetString("name");
            IsOwner = data.GetBoolean("owner").Value;

            string iconHash = data.GetString("icon");

            if (iconHash != null)
            {
                Icon = DiscordCdnUrl.ForGuildIcon(Id, iconHash);
            }

            long permissions = data.GetInt64("permissions").Value;

            Permissions = (DiscordPermission)permissions;
        }
예제 #3
0
        static string GetPermissions(DiscordPermission permission)
        {
            StringBuilder sb = new StringBuilder();

            foreach (Enum value in Enum.GetValues(typeof(DiscordPermission)))
            {
                if (permission.HasFlag(value))
                {
                    if (sb.Length == 0)
                    {
                        sb.Append(value.ToString());
                    }
                    else
                    {
                        sb.Append($", {value.ToString()}");
                    }
                }
            }

            return(sb.ToString());
        }
예제 #4
0
        /// <summary>
        /// Returns whether the specified member has the given set of permissions.
        /// </summary>
        /// <param name="permissions">The set of permissions to check if the member has.</param>
        /// <param name="member">The member to check the permissions of.</param>
        /// <param name="guild">The guild this member is in.</param>
        /// <exception cref="ArgumentException">
        /// Thrown if <paramref name="member"/> is not in the specified <paramref name="guild"/>.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="member"/> or <paramref name="guild"/> is null.
        /// </exception>
        public static bool HasPermission(DiscordPermission permissions, DiscordGuildMember member, DiscordGuild guild)
        {
            if (member == null)
            {
                throw new ArgumentNullException(nameof(member));
            }
            if (guild == null)
            {
                throw new ArgumentNullException(nameof(guild));
            }

            if (member.GuildId != guild.Id)
            {
                throw new ArgumentException("Member must be in the specified guild.");
            }

            // If owner, everything is true
            if (member.Id == guild.OwnerId)
            {
                return(true);
            }

            // Apply @everyone permissions
            DiscordRole everyoneRole = guild.Roles[guild.Id];

            DiscordPermission userPermissions = everyoneRole.Permissions;

            // Apply permissions for each role the member has
            foreach (Snowflake roleId in member.RoleIds)
            {
                if (guild.Roles.TryGetValue(roleId, out DiscordRole role))
                {
                    userPermissions = userPermissions | role.Permissions;
                }
            }

            // Check for permission
            return(userPermissions.HasFlag(DiscordPermission.Administrator) || userPermissions.HasFlag(permissions));
        }
예제 #5
0
        /// <summary>
        /// Gets the user's permissions in the guild
        /// </summary>
        /// <returns></returns>
        public DiscordPermission GetPermissions()
        {
            DiscordGuild guild = null;

            if (Client.GetType() == typeof(DiscordSocketClient))
            {
                var socketClient = (DiscordSocketClient)Client;

                if (socketClient.Config.Cache)
                {
                    guild = socketClient.GetCachedGuild(GuildId);
                }
            }

            if (guild == null)
            {
                guild = Client.GetGuild(GuildId);
            }

            DiscordPermission permissions = DiscordPermission.None;

            if (guild.OwnerId == User.Id)
            {
                foreach (DiscordPermission permission in Enum.GetValues(typeof(DiscordPermission)))
                {
                    permissions |= permission;
                }
            }
            else
            {
                foreach (var role in guild.Roles.Where(r => Roles.Contains(r.Id) || r.Name == "@everyone"))
                {
                    permissions |= role.Permissions;
                }
            }

            return(permissions);
        }
예제 #6
0
        private DiscordPermission ComputePermissions(DiscordGuild guild)
        {
            DiscordPermission permissions = DiscordPermission.None;

            if (guild.OwnerId == User.Id)
            {
                permissions = PermissionUtils.GetAllPermissions();
            }
            else
            {
                foreach (var role in guild.Roles.Where(r => Roles.Contains(r.Id) || r.Name == "@everyone"))
                {
                    permissions = permissions.Add(role.Permissions);
                }

                if (permissions.Has(DiscordPermission.Administrator))
                {
                    permissions = PermissionUtils.GetAllPermissions();
                }
            }

            return(permissions);
        }
예제 #7
0
        internal DiscordOverwrite(DiscordHttpClient http, Snowflake channelId, DiscordApiData data)
            : base(data)
        {
            this.http = http;

            ChannelId = channelId;

            string typeStr = data.GetString("type");
            DiscordOverwriteType type;

            if (Enum.TryParse(typeStr, true, out type))
            {
                Type = type;
            }

            long allow = data.GetInt64("allow").Value;

            Allow = (DiscordPermission)allow;

            long deny = data.GetInt64("deny").Value;

            Deny = (DiscordPermission)deny;
        }
예제 #8
0
 /// <summary>
 /// Edits the permissions of this overwrite.
 /// If successful, changes will be immediately reflected for this instance.
 /// <para>Requires <see cref="DiscordPermission.ManageRoles"/>.</para>
 /// </summary>
 /// <exception cref="DiscordHttpApiException"></exception>
 public Task Edit(DiscordPermission allow, DiscordPermission deny)
 {
     return(http.EditChannelPermissions(ChannelId, Id, allow, deny, Type));
 }
예제 #9
0
        /// <summary>
        /// Returns whether the specified member has the given set of permissions
        /// in the context of the specified guild channel.
        /// </summary>
        /// <param name="permissions">The set of permissions to check if the member has.</param>
        /// <param name="member">The member to check the permissions of.</param>
        /// <param name="guild">The guild this member is in.</param>
        /// <param name="channel">
        /// The guild channel to check the permissions against (this will take overwrites into account).
        /// </param>
        /// <exception cref="ArgumentException">
        /// Thrown if <paramref name="member"/> or <paramref name="channel"/> is not in the
        /// specified <paramref name="guild"/>
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="member"/>, <paramref name="guild"/>, or <paramref name="channel"/>
        /// is null.
        /// </exception>
        public static bool HasPermission(DiscordPermission permissions,
                                         DiscordGuildMember member, DiscordGuild guild, DiscordGuildChannel channel)
        {
            if (member == null)
            {
                throw new ArgumentNullException(nameof(member));
            }
            if (guild == null)
            {
                throw new ArgumentNullException(nameof(guild));
            }
            if (channel == null)
            {
                throw new ArgumentNullException(nameof(channel));
            }

            if (channel.GuildId != member.GuildId)
            {
                throw new ArgumentException("Guild channel must be in the same guild as this member.");
            }
            if (channel.GuildId != guild.Id)
            {
                throw new ArgumentException("Guild channel must be in the specified guild.");
            }

            // If owner, everything is true
            if (member.Id == guild.OwnerId)
            {
                return(true);
            }

            // Apply @everyone permissions
            DiscordRole everyoneRole = guild.Roles[guild.Id];

            DiscordPermission userPermissions = everyoneRole.Permissions;

            // Apply permissions for each role the member has
            foreach (Snowflake roleId in member.RoleIds)
            {
                if (guild.Roles.TryGetValue(roleId, out DiscordRole role))
                {
                    userPermissions = userPermissions | role.Permissions;
                }
            }

            // Administrator overrides channel-specific overwrites
            if (userPermissions.HasFlag(DiscordPermission.Administrator))
            {
                return(true);
            }

            // Apply channel @everyone overwrites
            DiscordOverwrite channelEveryoneOverwrite;

            if (channel.PermissionOverwrites.TryGetValue(guild.Id, out channelEveryoneOverwrite))
            {
                userPermissions = (userPermissions & (~channelEveryoneOverwrite.Deny)) | channelEveryoneOverwrite.Allow;
            }

            // Apply channel-specific role overwrites
            DiscordPermission roleOverwriteAllow = 0;
            DiscordPermission roleOverwriteDeny  = 0;

            foreach (Snowflake roleId in member.RoleIds)
            {
                DiscordOverwrite overwrite;
                if (channel.PermissionOverwrites.TryGetValue(roleId, out overwrite))
                {
                    roleOverwriteAllow = roleOverwriteAllow | overwrite.Allow;
                    roleOverwriteDeny  = roleOverwriteDeny | overwrite.Deny;
                }
            }

            userPermissions = (userPermissions & (~roleOverwriteDeny)) | roleOverwriteAllow;

            // Apply channel-specific member overwrite for this channel
            DiscordOverwrite memberOverwrite;

            if (channel.PermissionOverwrites.TryGetValue(member.Id, out memberOverwrite))
            {
                userPermissions = (userPermissions & (~memberOverwrite.Deny)) | memberOverwrite.Allow;
            }

            // Check for correct permissions
            return(userPermissions.HasFlag(DiscordPermission.Administrator) | userPermissions.HasFlag(permissions));
        }
예제 #10
0
 /// <summary>
 /// Adds a bot to a server
 /// </summary>
 /// <param name="botId">client_id from the oauth2 url</param>
 /// <param name="guildId">the guild to add the bot to</param>
 /// <param name="permissions">permissions the bot should have</param>
 /// <param name="captchaKey">captcha key used to validate the request</param>
 public static void AuthorizeBot(this DiscordClient client, ulong botId, ulong guildId, DiscordPermission permissions, string captchaKey)
 {
     client.HttpClient.Post($"/oauth2/authorize?client_id={botId}&scope=bot", JsonConvert.SerializeObject(new DiscordBotAuthProperties()
     {
         GuildId     = guildId,
         Permissions = permissions,
         CaptchaKey  = captchaKey
     }));
 }
예제 #11
0
        /// <inheritdoc />
        public async ValueTask <Result> CheckHasRequiredPermission(
            DiscordPermission permission,
            Snowflake channelId,
            IUser userToCheck,
            CancellationToken ct = default
            )
        {
            var getChannel = await _channelApi.GetChannelAsync(channelId, ct);

            if (!getChannel.IsSuccess)
            {
                return(Result.FromError(getChannel));
            }

            var channel = getChannel.Entity;

            if (!channel.GuildID.HasValue)
            {
                return(new ConditionNotSatisfiedError(
                           "Command requires a guild permission but was executed outside of a guild."));
            }

            var guildId = channel.GuildID.Value;

            var getGuildMember = await _guildApi.GetGuildMemberAsync(guildId, userToCheck.ID, ct);

            if (!getGuildMember.IsSuccess)
            {
                return(Result.FromError(getGuildMember));
            }

            var getGuildRoles = await _guildApi.GetGuildRolesAsync(guildId, ct);

            if (!getGuildRoles.IsSuccess)
            {
                return(Result.FromError(getGuildRoles));
            }

            var guildRoles   = getGuildRoles.Entity;
            var everyoneRole = guildRoles.FirstOrDefault(r => r.Name.Equals("@everyone"));

            if (everyoneRole is null)
            {
                return(new NotFoundError("No @everyone role found."));
            }

            var user = getGuildMember.Entity;

            if (user is null)
            {
                return(new NotFoundError("Executing user not found"));
            }

            var getGuild = await _guildApi.GetGuildAsync(guildId, ct : ct);

            if (!getGuild.IsSuccess)
            {
                return(Result.FromError(getGuild));
            }

            var guildOwnerId = getGuild.Entity.OwnerID;

            // succeed if the user is the Owner of the guild
            if (guildOwnerId.Equals(userToCheck.ID))
            {
                return(Result.FromSuccess());
            }

            var memberRoles = guildRoles.Where(r => user.Roles.Contains(r.ID)).ToList();
            IDiscordPermissionSet computedPermissions;

            if (channel.PermissionOverwrites.HasValue)
            {
                computedPermissions = DiscordPermissionSet.ComputePermissions(
                    userToCheck.ID,
                    everyoneRole,
                    memberRoles,
                    channel.PermissionOverwrites.Value
                    );
            }
            else
            {
                computedPermissions = DiscordPermissionSet.ComputePermissions(
                    userToCheck.ID,
                    everyoneRole,
                    memberRoles
                    );
            }

            // succeed if the user is an Administrator of the guild
            if (computedPermissions.HasPermission(DiscordPermission.Administrator))
            {
                return(Result.FromSuccess());
            }

            var hasPermission = computedPermissions.HasPermission(permission);

            return(!hasPermission
                ? new ConditionNotSatisfiedError(
                       $"Guild User requesting the command does not have the required {permission.ToString()} permission")
                : Result.FromSuccess());
        }
예제 #12
0
 public static DiscordPermission Remove(this DiscordPermission permissions, DiscordPermission permsToRemove)
 {
     return(permissions & ~permsToRemove);
 }
예제 #13
0
        /// <summary>
        /// Adds/edits a permission overwrite to a channel
        /// </summary>
        public void AddPermissionOverwrite(ulong affectedId, PermissionOverwriteType type, DiscordPermission allow, DiscordPermission deny)
        {
            var overwrite = Client.AddPermissionOverwrite(Id, affectedId, type, allow, deny);
            List <DiscordPermissionOverwrite> overwrites = PermissionOverwrites.ToList();

            int i = overwrites.FindIndex(o => o.AffectedId == o.AffectedId);

            if (i == -1)
            {
                overwrites.Add(overwrite);
            }
            else
            {
                overwrites[i] = overwrite;
            }

            PermissionOverwrites = overwrites;
        }
예제 #14
0
 /// <summary>
 /// Creates a new <see cref="DiscordPermissionException"/> instance.
 /// </summary>
 /// <param name="member">The member that didn't have the right permissions.</param>
 /// <param name="guild">The guild the member is in.</param>
 /// <param name="permission">The permissions that caused the exception.</param>
 public DiscordPermissionException(DiscordGuildMember member, DiscordGuild guild, DiscordPermission permission)
     : base($"\"{member.User.Username}\" does not have permissions: {GetPermissions(permission)}")
 {
     Permission = permission;
     Guild      = guild;
     Member     = member;
 }
예제 #15
0
 /// <summary>
 /// Creates a new <see cref="DiscordPermissionException"/> instance.
 /// </summary>
 /// <param name="member">The member that didn't have the right permissions.</param>
 /// <param name="guild">The guild the member is in.</param>
 /// <param name="channel">The channel the permissions were checked against.</param>
 /// <param name="permission">The permissions that caused the exception.</param>
 public DiscordPermissionException(DiscordGuildMember member, DiscordGuild guild, DiscordGuildChannel channel, DiscordPermission permission)
     : base($"\"{member.User.Username}\" does not have permissions: {GetPermissions(permission)} in channel \"{channel.Name}\"")
 {
     Permission = permission;
     Member     = member;
     Guild      = guild;
     Channel    = channel;
 }
예제 #16
0
    /// <inheritdoc />
    public async ValueTask <Result> CheckHasRequiredPermission(
        DiscordPermission permission,
        Snowflake channelId,
        IUser userToCheck,
        CancellationToken ct = default
        )
    {
        var getChannel = await _channelApi.GetChannelAsync(channelId, ct);

        if (!getChannel.IsSuccess)
        {
            return(Result.FromError(getChannel));
        }

        var channel = getChannel.Entity;

        if (!channel.GuildID.HasValue)
        {
            return(new ConditionNotSatisfiedError(
                       "Command requires a guild permission but was executed outside of a guild."));
        }

        var guildId = channel.GuildID.Value;

        var getGuildMember = await _guildApi.GetGuildMemberAsync(guildId, userToCheck.ID, ct);

        if (!getGuildMember.IsSuccess)
        {
            return(Result.FromError(getGuildMember));
        }

        var getGuildRoles = await _guildApi.GetGuildRolesAsync(guildId, ct);

        if (!getGuildRoles.IsSuccess)
        {
            return(Result.FromError(getGuildRoles));
        }

        var guildRoles   = getGuildRoles.Entity;
        var everyoneRole = guildRoles.FirstOrDefault(r => r.Name.Equals("@everyone"));

        if (everyoneRole is null)
        {
            return(new NotFoundError("No @everyone role found."));
        }

        var user = getGuildMember.Entity;

        if (user is null)
        {
            return(new NotFoundError("Executing user not found"));
        }

        var getGuild = await _guildApi.GetGuildAsync(guildId, ct : ct);

        if (!getGuild.IsSuccess)
        {
            return(Result.FromError(getGuild));
        }

        var guildOwnerId = getGuild.Entity.OwnerID;

        // succeed if the user is the Owner of the guild
        if (guildOwnerId.Equals(userToCheck.ID))
        {
            return(Result.FromSuccess());
        }

        var memberRoles         = guildRoles.Where(r => user.Roles.Contains(r.ID)).ToList();
        var computedPermissions = channel.PermissionOverwrites switch
        {
            { HasValue : true, Value : { } overwrites } => DiscordPermissionSet.ComputePermissions(
예제 #17
0
 public void Authorize(ulong guildId, DiscordPermission permissions, string captchaKey)
 {
     Client.AuthorizeBot(Id, guildId, permissions, captchaKey);
 }
예제 #18
0
 public void Authorize(ulong guildId, DiscordPermission permissions, string captchaKey)
 {
     AuthorizeAsync(guildId, permissions, captchaKey).GetAwaiter().GetResult();
 }
예제 #19
0
 public async Task AuthorizeAsync(ulong guildId, DiscordPermission permissions, string captchaKey)
 {
     await Client.AuthorizeBotAsync(Id, guildId, permissions, captchaKey);
 }
예제 #20
0
 public ButtonBuilder WithRequiredPermission(DiscordPermission permission)
 {
     _requiredPermission = permission;
     return(this);
 }
예제 #21
0
 public static DiscordPermission Add(this DiscordPermission permissions, DiscordPermission newPerms)
 {
     return(permissions | newPerms);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RequireUserGuildPermissionAttribute"/> class.
 /// </summary>
 /// <param name="permission">The permission.</param>
 public RequireUserGuildPermissionAttribute(DiscordPermission permission)
 {
     Permission = permission;
 }
예제 #23
0
 private static bool And(DiscordPermission flags, DiscordPermission other)
 {
     return((flags & other) == other);
 }
예제 #24
0
 /// <summary>
 /// Checks whether this member has the given set of permissions
 /// in the context of the specified guild channel.
 /// If they don't, a <see cref="DiscordPermissionException"/> is thrown with details.
 /// </summary>
 /// <param name="permissions">The set of permissions to check if the member has.</param>
 /// <param name="guild">The guild this member is in.</param>
 /// <param name="channel">
 /// The guild channel to check the permissions against (this will take overwrites into account).
 /// </param>
 /// <exception cref="ArgumentException">
 /// Thrown if <paramref name="member"/> or <paramref name="channel"/> is not in the
 /// specified <paramref name="guild"/>
 /// </exception>
 /// <exception cref="ArgumentNullException">
 /// Thrown if <paramref name="member"/>, <paramref name="guild"/>, or <paramref name="channel"/>
 /// is null.
 /// </exception>
 public static void AssertPermission(this DiscordGuildMember member, DiscordPermission permissions, DiscordGuild guild, DiscordGuildChannel channel)
 => DiscordPermissionHelper.AssertPermission(permissions, member, guild, channel);
예제 #25
0
 public bool Has(DiscordPermission permission)
 {
     return(DiscordPermissionCalculator.Has(_value, permission));
 }
예제 #26
0
 public void Remove(DiscordPermission permission)
 {
     _value = DiscordPermissionCalculator.Remove(_value, permission);
 }
예제 #27
0
        /// <summary>
        /// Adds/edits a permission overwrite to a channel
        /// </summary>
        /// <param name="channelId">ID of the channel</param>
        /// <param name="overwrite">The permission overwrite to add/edit</param>
        public static DiscordPermissionOverwrite AddPermissionOverwrite(this DiscordClient client, ulong channelId, ulong affectedId, PermissionOverwriteType type, DiscordPermission allow, DiscordPermission deny)
        {
            var overwrite = new DiscordPermissionOverwrite()
            {
                AffectedId = affectedId, Type = type, Allow = allow, Deny = deny
            };

            client.HttpClient.Put($"/channels/{channelId}/permissions/{overwrite.AffectedId}", overwrite);

            return(overwrite);
        }
예제 #28
0
 /// <summary>
 /// Sets the permissions granted by the role.
 /// </summary>
 public ModifyRoleOptions SetPermissions(DiscordPermission permissions)
 {
     Permissions = permissions;
     return(this);
 }
예제 #29
0
 public void Add(DiscordPermission permission)
 {
     _value = DiscordPermissionCalculator.Add(_value, permission);
 }
예제 #30
0
 /// <summary>
 /// Returns whether this member has the given set of permissions
 /// in the context of the specified guild channel.
 /// </summary>
 /// <param name="permissions">The set of permissions to check if the member has.</param>
 /// <param name="guild">The guild this member is in.</param>
 /// <param name="channel">
 /// The guild channel to check the permissions against (this will take overwrites into account).
 /// </param>
 /// <exception cref="ArgumentException">
 /// Thrown if <paramref name="member"/> or <paramref name="channel"/> is not in the
 /// specified <paramref name="guild"/>
 /// </exception>
 /// <exception cref="ArgumentNullException">
 /// Thrown if <paramref name="member"/>, <paramref name="guild"/>, or <paramref name="channel"/>
 /// is null.
 /// </exception>
 public static bool HasPermission(this DiscordGuildMember member, DiscordPermission permissions, DiscordGuild guild, DiscordGuildChannel channel)
 => DiscordPermissionHelper.HasPermission(permissions, member, guild, channel);