Ejemplo n.º 1
0
        /*public static ulong ResolveChannel(IGuildUser user, IGuildChannel channel)
         * {
         *  return ResolveChannel(user, channel, ResolveGuild(user));
         * }*/
        public static ulong ResolveChannel(IGuildUser user, IGuildChannel channel, ulong guildPermissions)
        {
            ulong resolvedPermissions = 0;

            ulong mask = ChannelPermissions.All(channel).RawValue;

            if (/*user.Id == user.Guild.OwnerId || */ GetValue(guildPermissions, GuildPermission.Administrator))
            {
                resolvedPermissions = mask; //Owners and administrators always have all permissions
            }
            else
            {
                //Start with this user's guild permissions
                resolvedPermissions = guildPermissions;

                OverwritePermissions?perms;
                var roles = user.Roles;
                if (roles.Count > 0)
                {
                    ulong deniedPermissions = 0UL, allowedPermissions = 0UL;
                    foreach (var role in roles)
                    {
                        perms = channel.GetPermissionOverwrite(role);
                        if (perms != null)
                        {
                            deniedPermissions  |= perms.Value.DenyValue;
                            allowedPermissions |= perms.Value.AllowValue;
                        }
                    }
                    resolvedPermissions = (resolvedPermissions & ~deniedPermissions) | allowedPermissions;
                }
                perms = channel.GetPermissionOverwrite(user);
                if (perms != null)
                {
                    resolvedPermissions = (resolvedPermissions & ~perms.Value.DenyValue) | perms.Value.AllowValue;
                }

                //TODO: C#7 Typeswitch candidate
                var textChannel  = channel as ITextChannel;
                var voiceChannel = channel as IVoiceChannel;
                if (textChannel != null && !GetValue(resolvedPermissions, ChannelPermission.ReadMessages))
                {
                    resolvedPermissions = 0; //No read permission on a text channel removes all other permissions
                }
                else if (voiceChannel != null && !GetValue(resolvedPermissions, ChannelPermission.Connect))
                {
                    resolvedPermissions = 0; //No connect permission on a voice channel removes all other permissions
                }
                resolvedPermissions &= mask; //Ensure we didnt get any permissions this channel doesnt support (from guildPerms, for example)
            }

            return(resolvedPermissions);
        }
Ejemplo n.º 2
0
        private static async Task ConfigureChannelMuteRolePermissionsAsync(IGuildChannel channel, IRole muteRole)
        {
            try
            {
                var permissionOverwrite = channel.GetPermissionOverwrite(muteRole);

                if (permissionOverwrite != null)
                {
                    var deniedPermissions = permissionOverwrite.GetValueOrDefault().ToDenyList();

                    if (!_mutePermissions.ToDenyList().Except(deniedPermissions).Any())
                    {
                        Log.Debug("Skipping setting mute permissions for channel #{Channel} as they're already set.", channel.Name);
                        return;
                    }

                    Log.Debug("Removing permission overwrite for channel #{Channel}.", channel.Name);
                    await channel.RemovePermissionOverwriteAsync(muteRole);
                }

                await channel.AddPermissionOverwriteAsync(muteRole, _mutePermissions);

                Log.Debug("Set mute permissions for role {Role} in channel #{Channel}.", muteRole.Name, channel.Name);
            }
            catch (Exception e)
            {
                Log.Error(e, "Failed setting channel mute role on #{Channel}", channel.Name);
                throw;
            }
        }
Ejemplo n.º 3
0
        public async Task LockAllChannels()
        {
            IRole defaultRole = Context.Guild.EveryoneRole;
            IReadOnlyCollection <IGuildChannel> guildChannels = await Context.Guild.GetChannelsAsync();

            for (int idLoc = 0; idLoc < GlobalConfiguration.LockableChannelIds.Length; idLoc++)
            {
                ulong         channelId = ulong.Parse(GlobalConfiguration.LockableChannelIds[idLoc]);
                IGuildChannel channel   = guildChannels.FirstOrDefault(c => c.Id == channelId);
                if (channel != null)
                {
                    OverwritePermissions permissions = channel.GetPermissionOverwrite(defaultRole) ?? new OverwritePermissions();
                    permissions = permissions.Modify(sendMessages: PermValue.Inherit, addReactions: PermValue.Inherit);
                    await channel.AddPermissionOverwriteAsync(defaultRole, permissions);
                }
                else
                {
                    _logger.LogWarning(string.Format("Channel '{0}' was not found for locking.", channelId));
                }
            }

            await ReplyAsync("all the chawnnels hawv bween unlocked~!! uwu p-please reward me.. ///");

            _logger.LogInformation(Context.User.ToString() + " unlocked all channels [ " + string.Join(", ", GlobalConfiguration.LockableChannelIds) + " ].");
        }
Ejemplo n.º 4
0
        public async Task <ModifyEntityResult> SetDedicatedChannelVisibilityForRoleAsync
        (
            [NotNull] IGuildChannel dedicatedChannel,
            [NotNull] IRole role,
            bool isVisible
        )
        {
            var permissions       = OverwritePermissions.InheritAll;
            var existingOverwrite = dedicatedChannel.GetPermissionOverwrite(role);

            if (!(existingOverwrite is null))
            {
                permissions = existingOverwrite.Value;
            }

            permissions = permissions.Modify
                          (
                readMessageHistory: isVisible ? PermValue.Allow : PermValue.Deny,
                viewChannel: isVisible ? PermValue.Allow : PermValue.Deny
                          );

            await dedicatedChannel.AddPermissionOverwriteAsync(role, permissions);

            // Ugly hack - there seems to be some kind of race condition on Discord's end.
            await Task.Delay(20);

            return(ModifyEntityResult.FromSuccess());
        }
Ejemplo n.º 5
0
        bool IsPublic(IGuildChannel channel)
        {
            var permissions = channel.GetPermissionOverwrite(_client.GetGuild(LimitedToGuild).EveryoneRole);

            return(!permissions.HasValue ||
                   (permissions.Value.ViewChannel != PermValue.Deny && permissions.Value.SendMessages != PermValue.Deny));
        }
Ejemplo n.º 6
0
        public async Task <ModifyEntityResult> SetDedicatedChannelWritabilityForUserAsync
        (
            [NotNull] IGuildChannel dedicatedChannel,
            [NotNull] IUser participant,
            bool isVisible
        )
        {
            var permissions       = OverwritePermissions.InheritAll;
            var existingOverwrite = dedicatedChannel.GetPermissionOverwrite(participant);

            if (!(existingOverwrite is null))
            {
                permissions = existingOverwrite.Value;
            }

            permissions = permissions.Modify
                          (
                sendMessages: isVisible ? PermValue.Allow : PermValue.Deny,
                addReactions: isVisible ? PermValue.Allow : PermValue.Deny,
                embedLinks: isVisible ? PermValue.Allow : PermValue.Deny,
                attachFiles: isVisible ? PermValue.Allow : PermValue.Deny,
                useExternalEmojis: isVisible ? PermValue.Allow : PermValue.Deny
                          );

            await dedicatedChannel.AddPermissionOverwriteAsync(participant, permissions);

            // Ugly hack - there seems to be some kind of race condition on Discord's end.
            await Task.Delay(20);

            return(ModifyEntityResult.FromSuccess());
        }
Ejemplo n.º 7
0
        public async Task Unlock(IGuildChannel channel, IGuildUser agent)
        {
            try
            {
                IRole role       = channel.Guild.EveryoneRole;
                var   permission = channel.GetPermissionOverwrite(role);
                if (permission.HasValue && permission.Value.ViewChannel == PermValue.Deny)
                {
                    await channel.AddPermissionOverwriteAsync(role, new OverwritePermissions(viewChannel : PermValue.Allow));

                    {
                        var eb = new EmbedBuilder()
                        {
                            Author = new EmbedAuthorBuilder()
                            {
                                IconUrl = $"{agent.GetAvatarUrl()}",
                                Name    = $"Channel unlocked"
                            },
                            Description = $"{agent.Username}#{agent.Discriminator} ({agent.Mention}) unlocked a channel!",
                            Fields      =
                            {
                                new EmbedFieldBuilder()
                                {
                                    Name     = "Perpetrator",
                                    Value    = $"• **Agent:** {agent.Username}#{agent.Discriminator}\n• **Agent ID:** {agent.Id}",
                                    IsInline = false
                                },
                                new EmbedFieldBuilder()
                                {
                                    Name     = "Source",
                                    Value    = $"• **Server:** {agent.Guild.Name}\n• **Channel:** <#{channel.Id}>",
                                    IsInline = false
                                }
                            },
                            Footer = new EmbedFooterBuilder()
                            {
                                Text = $"{DateTime.Now}",
                            },
                        };
                        eb.WithColor(Color.Blue);
                        DiscordReply("", eb);
                        await Utils.LogChannel.SendMessageAsync("", false, eb.Build());
                    }
                }
                else
                {
                    DiscordReply("This channel is already unlocked.");
                }
            }
            catch
            {
                Console.WriteLine($"Error while trying to set or remove lockdown on channel.");
                DiscordReply("Unable to lock this channel down");
            }
        }
Ejemplo n.º 8
0
        public async Task LockModule()
        {
            IGuildChannel channel = (IGuildChannel)Context.Channel;

            PermValue permission        = channel.GetPermissionOverwrite(Context.Guild.EveryoneRole)?.SendMessages ?? PermValue.Allow;
            PermValue flippedPermission = permission == PermValue.Allow ? PermValue.Deny : PermValue.Allow;

            await ReplyAsync(flippedPermission == PermValue.Allow? "> Channel Has Been Unlocked" : "> Channel Has Been Locked");

            await channel.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, new OverwritePermissions(sendMessages : flippedPermission));
        }
Ejemplo n.º 9
0
        public static bool IsPublic(this IGuildChannel channel)
        {
            if (channel?.Guild is IGuild guild)
            {
                var permissions = channel.GetPermissionOverwrite(guild.EveryoneRole);

                return(!permissions.HasValue || permissions.Value.ViewChannel != PermValue.Deny);
            }

            return(false);
        }
Ejemplo n.º 10
0
        public async Task LockCurrentChannel()
        {
            IGuildChannel        channel     = (IGuildChannel)Context.Channel;
            IRole                defaultRole = channel.Guild.EveryoneRole;
            OverwritePermissions permissions = channel.GetPermissionOverwrite(defaultRole) ?? new OverwritePermissions();

            permissions = permissions.Modify(sendMessages: PermValue.Inherit, addReactions: PermValue.Inherit);
            await channel.AddPermissionOverwriteAsync(defaultRole, permissions);

            await ReplyAsync("uwu!! #" + channel.Name + " is nyow unlowcked!1!  uguuuu yes im so c-c-ccreative");

            _logger.LogInformation(Context.User.ToString() + " unlocked channel #" + channel.Name + " [" + channel.Id + "].");
        }
Ejemplo n.º 11
0
        public async Task LockCurrentChannel()
        {
            IGuildChannel        channel     = (IGuildChannel)Context.Channel;
            IRole                defaultRole = channel.Guild.EveryoneRole;
            OverwritePermissions permissions = channel.GetPermissionOverwrite(defaultRole) ?? new OverwritePermissions();

            permissions = permissions.Modify(sendMessages: PermValue.Deny, addReactions: PermValue.Deny);
            await channel.AddPermissionOverwriteAsync(defaultRole, permissions);

            await ReplyAsync("i-i nylocked #" + channel.Name + " f-for you s-s-s-senpai :0 a-are you p-proud??! >//////<");

            _logger.LogInformation(Context.User.ToString() + " locked channel #" + channel.Name + " [" + channel.Id + "].");
        }
Ejemplo n.º 12
0
        private async Task ConfigureChannelMuteRolePermissionsAsync(IGuildChannel channel, IRole muteRole)
        {
            var permissionOverwrite = channel.GetPermissionOverwrite(muteRole);

            if (permissionOverwrite != null)
            {
                if ((permissionOverwrite.Value.AllowValue == _mutePermissions.AllowValue) &&
                    (permissionOverwrite.Value.DenyValue == _mutePermissions.DenyValue))
                {
                    Log.Debug("Skipping setting mute permissions for channel #{Channel} as they're already set.", channel.Name);
                    return;
                }

                Log.Debug("Removing permission overwrite for channel #{Channel}.", channel.Name);
                await channel.RemovePermissionOverwriteAsync(muteRole);
            }

            await channel.AddPermissionOverwriteAsync(muteRole, _mutePermissions);

            Log.Debug("Set mute permissions for role {Role} in channel #{Channel}.", muteRole.Name, channel.Name);
        }
Ejemplo n.º 13
0
        public async Task Unmute(IGuildUser user, IGuildChannel channel = null)
        {
            //If there's no specified channel, use the channel the command was sent in
            if (channel == null)
            {
                channel = (ITextChannel)Context.Channel;
            }

            //Ensure this is a text channel
            if (channel == null)
            {
                await Context.Channel.SendErrorAsync($"{channel.Name} is not a text channel.");

                return;
            }

            //Try and get the perms for teh user
            var userPerms = channel.GetPermissionOverwrite(user);

            //If there *are* user perms, it's safe to check to unmute them otherwise they aren't muted
            if (userPerms == null)
            {
                await Context.Channel.SendErrorAsync($"{user.NicknameUsername()} is not muted.");

                return;
            }

            //Check to see if they're muted
            if (userPerms.Value.SendMessages != PermValue.Deny)
            {
                await Context.Channel.SendErrorAsync($"{user.NicknameUsername()} is not muted.");

                return;
            }

            //Delete their perms, they're gucci
            await channel.RemovePermissionOverwriteAsync(user);

            await Context.Channel.SendSuccessAsync($"{user.NicknameUsername()} has been unmuted.");
        }
Ejemplo n.º 14
0
        public async Task MuteUserAsync(IGuildUser user, IGuildChannel channel)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (channel == null)
            {
                throw new ArgumentNullException(nameof(channel));
            }

            // Fetches the previous overwrite and bail if one is found
            var previousOverwrite = channel.GetPermissionOverwrite(user);

            if (previousOverwrite.HasValue && previousOverwrite.Value.SendMessages == PermValue.Deny)
            {
                throw new InvalidOperationException($"User {user.Username} had already been muted in this channel.");
            }

            // Creates a new OverwritePermissions with send message set to deny and pass it into the method
            await channel.AddPermissionOverwriteAsync(user, new OverwritePermissions(sendMessages : PermValue.Deny));
        }
Ejemplo n.º 15
0
        /*public static ulong ResolveChannel(IGuildUser user, IGuildChannel channel)
         * {
         *  return ResolveChannel(user, channel, ResolveGuild(user));
         * }*/
        public static ulong ResolveChannel(IGuild guild, IGuildUser user, IGuildChannel channel, ulong guildPermissions)
        {
            ulong mask = ChannelPermissions.All(channel).RawValue;
            ulong resolvedPermissions;

            if (GetValue(guildPermissions, GuildPermission.Administrator)) //Includes owner
            {
                resolvedPermissions = mask;                                //Owners and administrators always have all permissions
            }
            else
            {
                //Start with this user's guild permissions
                resolvedPermissions = guildPermissions;

                //Give/Take Everyone permissions
                var perms = channel.GetPermissionOverwrite(guild.EveryoneRole);
                if (perms != null)
                {
                    resolvedPermissions = (resolvedPermissions & ~perms.Value.DenyValue) | perms.Value.AllowValue;
                }

                //Give/Take Role permissions
                ulong deniedPermissions = 0UL, allowedPermissions = 0UL;
                foreach (var roleId in user.RoleIds)
                {
                    IRole role;
                    if (roleId != guild.EveryoneRole.Id && (role = guild.GetRole(roleId)) != null)
                    {
                        perms = channel.GetPermissionOverwrite(role);
                        if (perms != null)
                        {
                            allowedPermissions |= perms.Value.AllowValue;
                            deniedPermissions  |= perms.Value.DenyValue;
                        }
                    }
                }
                resolvedPermissions = (resolvedPermissions & ~deniedPermissions) | allowedPermissions;

                //Give/Take User permissions
                perms = channel.GetPermissionOverwrite(user);
                if (perms != null)
                {
                    resolvedPermissions = (resolvedPermissions & ~perms.Value.DenyValue) | perms.Value.AllowValue;
                }

                if (channel is ITextChannel)
                {
                    if (!GetValue(resolvedPermissions, ChannelPermission.ViewChannel))
                    {
                        //No read permission on a text channel removes all other permissions
                        resolvedPermissions = 0;
                    }
                    else if (!GetValue(resolvedPermissions, ChannelPermission.SendMessages))
                    {
                        //No send permissions on a text channel removes all send-related permissions
                        resolvedPermissions &= ~(ulong)ChannelPermission.SendTTSMessages;
                        resolvedPermissions &= ~(ulong)ChannelPermission.MentionEveryone;
                        resolvedPermissions &= ~(ulong)ChannelPermission.EmbedLinks;
                        resolvedPermissions &= ~(ulong)ChannelPermission.AttachFiles;
                    }
                }
                resolvedPermissions &= mask; //Ensure we didn't get any permissions this channel doesn't support (from guildPerms, for example)
            }

            return(resolvedPermissions);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Determines wether the supplied user has the manage messages permission.
 /// </summary>
 public static bool CanManageMessages(IGuildUser guildUser, IGuildChannel channel)
 => guildUser?.GuildPermissions.ManageMessages == true && channel?.GetPermissionOverwrite(guildUser)?.ManageMessages != PermValue.Deny;
Ejemplo n.º 17
0
 public static bool TestPermission(this IGuildChannel Channel, ChannelPermission Permission, IRole Role)
 => Channel.GetPermissionOverwrite(Role)?.ToAllowList().Contains(Permission) ?? false;