コード例 #1
0
        public override async Task <CheckResult> CheckAsync(ICommandContext ctx, IServiceProvider services)
        {
            var context = (QuiccbanContext)ctx;

            var dbService       = services.GetService <DatabaseService>();
            var responseService = services.GetService <ResponseService>();
            var config          = services.GetService <Config>();

            var dbGuild = await dbService.GetOrCreateGuildAsync(context.Guild);

            if (dbGuild.ModlogChannelId == 0)
            {
                return(new CheckResult(string.Format(responseService.Get("require_modlog_channel"), config.Prefix)));
            }

            var channel = context.Guild.GetTextChannel(dbGuild.ModlogChannelId);

            if (channel == null)
            {
                return(new CheckResult(string.Format(responseService.Get("modlog_channel_doesnt_exist"))));
            }

            ChannelPermissions perms = context.Guild.CurrentUser.GetPermissions(channel);

            if (!perms.Has(ChannelPermission.SendMessages))
            {
                return(new CheckResult(string.Format(responseService.Get("require_modlog_channel_permission"), channel.Name, channel.Mention, ChannelPermission.SendMessages.Humanize())));
            }

            if (!perms.Has(ChannelPermission.ViewChannel))
            {
                return(new CheckResult(string.Format(responseService.Get("require_modlog_channel_permission"), channel.Name, channel.Mention, ChannelPermission.ViewChannel.Humanize())));
            }

            if (!perms.Has(ChannelPermission.ReadMessageHistory))
            {
                return(new CheckResult(string.Format(responseService.Get("require_modlog_channel_permission"), channel.Name, channel.Mention, ChannelPermission.ReadMessageHistory.Humanize())));
            }

            if (!perms.Has(ChannelPermission.EmbedLinks))
            {
                return(new CheckResult(string.Format(responseService.Get("require_modlog_channel_permission"), channel.Name, channel.Mention, ChannelPermission.EmbedLinks.Humanize())));
            }

            return(CheckResult.Successful);
        }
コード例 #2
0
        public static async Task FindBadGuilds(bool ignoreExcessiveAmount = false)
        {
            // Create a copy of the GuildSettings
            List <GuildSettings> allGuildSettings = new List <GuildSettings>(Configuration.LoadedConfiguration.DiscordConfig.GuildSettings);

            // Create a list for deregistration candidates
            List <SocketGuildChannel> deregistrationCandidates = new List <SocketGuildChannel>();

            foreach (GuildSettings guildSettings in allGuildSettings)
            {
                foreach (KeyValuePair <ulong, DynamicSettingsData> pair in guildSettings.ChannelSettings)
                {
                    // Get the channel
                    SocketGuildChannel channel = (SocketGuildChannel)DiscordBot.GetChannel(pair.Key);

                    // Check if the channel no longer exists
                    if (channel == null)
                    {
                        continue;
                    }

                    // Get the Permissions
                    ChannelPermissions permissions = channel.Guild.CurrentUser.GetPermissions(channel);

                    // Check if we can't write to this channel
                    if (!permissions.Has(ChannelPermission.SendMessages))
                    {
                        deregistrationCandidates.Add(channel);
                    }
                }
            }

            // Skip deregistration if there are a large number of guilds to deregister
            if (deregistrationCandidates.Count > 5 && !ignoreExcessiveAmount)
            {
                await DiscordBot.LoggingChannel.SendMessageAsync($"**[DiscordUtil]** Skipping deregistration, there seems to be an excessive amount of guilds to deregister ({deregistrationCandidates.Count})");

                return;
            }

            foreach (SocketGuildChannel guildChannel in deregistrationCandidates)
            {
                // Remove the channel settings
                Configuration.LoadedConfiguration.DiscordConfig.GuildSettings.Where(g => g.GuildId == guildChannel.Guild.Id).FirstOrDefault().ChannelSettings.TryRemove(guildChannel.Id, out DynamicSettingsData data);

                // Send a message to this server that their guild has been deregistered
                Embed embed = new EmbedBuilder()
                              .WithTitle("Warning")
                              .WithDescription(Localizer.Localize("discord.guild.deregister", (Language)data.GetSetting("language")))
                              .WithColor(Color.Orange)
                              .Build();

                await DiscordBot.SendMessageToFirstWritableChannel(guildChannel.Guild, embed : embed);

                await DiscordBot.LoggingChannel.SendMessageAsync($"**[Guild]** Deregistered \"#{guildChannel.Name}\" ({guildChannel.Id}) on \"{guildChannel.Guild.Name}\"");
            }
        }
コード例 #3
0
        void Code()
        {
            // these are all the same
            var channelPermissions = new ChannelPermissions(Permission.ViewChannels | Permission.SendMessages);

            channelPermissions = Permission.ViewChannels | Permission.SendMessages;
            channelPermissions = 3072; // view channel and send messages (raw value)

            // utility
            ulong      rawValue   = channelPermissions.RawValue; // raw value
            Permission permission = channelPermissions;          // implicit permission

            if (channelPermissions.ViewChannels)
            {
                ;                                  // bool properties
            }
            // or Has()
            if (channelPermissions.Has(Permission.ViewChannels))
            {
                ;
            }

            // or stdlib HasFlag()
            if (channelPermissions.Flags.HasFlag(Permission.ViewChannels))
            {
                ;
            }

            // Enumerates all flags
            foreach (Permission perm in channelPermissions)
            {
            }

            // what about overwriting permissions in a channel?
            var overwritePermissions = new OverwritePermissions(allowed: ChannelPermissions.None, denied: channelPermissions);

            overwritePermissions = (Permission.None, channelPermissions);

            // utility
            overwritePermissions = overwritePermissions
                                   .Allow(Permission.SendAttachments)
                                   .Deny(Permission.UseTextToSpeech)
                                   .Unset(Permission.ViewChannels);

            // or
            overwritePermissions.Allowed |= Permission.SendAttachments;
            overwritePermissions.Denied  |= Permission.UseTextToSpeech;
            overwritePermissions.Allowed &= ~Permission.ViewChannels;
            overwritePermissions.Denied  &= ~Permission.ViewChannels;
        }
コード例 #4
0
        public override Task <PreconditionResult> CheckPermissionsAsync(
            ICommandContext context,
            CommandInfo command,
            IServiceProvider services)
        {
            IGuildUser user = context.User as IGuildUser;

            if (context.User.IsWebhook)
            {
                return(Task.FromResult(_webhookNames.Contains(context.User.Username) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Command must be used by an authorized webhook.")));
            }

            if (this.GuildPermission.HasValue)
            {
                if (user == null)
                {
                    return(Task.FromResult(PreconditionResult.FromError(this.NotAGuildErrorMessage ?? "Command must be used in a guild channel.")));
                }
                if (!user.GuildPermissions.Has(this.GuildPermission.Value))
                {
                    return(Task.FromResult(PreconditionResult.FromError(this.ErrorMessage ?? string.Format("User requires guild permission {0}.", (object)this.GuildPermission.Value))));
                }
            }
            Discord.ChannelPermission?channelPermission = this.ChannelPermission;
            if (channelPermission.HasValue)
            {
                ChannelPermissions     channelPermissions = !(context.Channel is IGuildChannel channel) ? ChannelPermissions.All((IChannel)context.Channel) : user.GetPermissions(channel);
                ref ChannelPermissions local = ref channelPermissions;
                channelPermission = this.ChannelPermission;
                long num = (long)channelPermission.Value;
                if (!local.Has((Discord.ChannelPermission)num))
                {
                    string reason = this.ErrorMessage;
                    if (reason == null)
                    {
                        channelPermission = this.ChannelPermission;
                        reason            = string.Format("User requires channel permission {0}.", (object)channelPermission.Value);
                    }
                    return(Task.FromResult(PreconditionResult.FromError(reason)));
                }
            }
コード例 #5
0
        void Code()
        {
            // these are all the same
            ChannelPermissions channelPermissions = new ChannelPermissions(Permission.ViewChannels | Permission.SendMessages);

            channelPermissions = Permission.ViewChannels | Permission.SendMessages;
            channelPermissions = 3072; // view channel and send messages (raw)

            // utility
            var raw = channelPermissions.RawValue; // ulong

            raw = channelPermissions;
            var canViewChannel = channelPermissions.ViewChannels;

            // or Has()
            canViewChannel = channelPermissions.Has(Permission.ViewChannels);
            // or stdlib HasFlag()
            channelPermissions.Permissions.HasFlag(Permission.ViewChannels);
            foreach (Permission permission in channelPermissions)
            {
                // enumerates all flags
            }

            // what about overwriting permissions in a channel?
            // these are also all the same
            OverwritePermissions overwritePermissions = new OverwritePermissions(allowed: ChannelPermissions.None, denied: channelPermissions);

            overwritePermissions = new OverwritePermissions(Permission.None, channelPermissions);
            overwritePermissions = (Permission.None, channelPermissions);
            overwritePermissions = (0, 3072);

            // utility
            overwritePermissions = overwritePermissions.Allow(Permission.SendAttachments)
                                   .Deny(Permission.UseTextToSpeech)
                                   .Unset(Permission.ViewChannels);
            // or
            overwritePermissions += Permission.SendAttachments;
            overwritePermissions -= Permission.UseTextToSpeech;
            overwritePermissions /= Permission.ViewChannels;
        }
コード例 #6
0
 public static bool HasAccess(this ChannelPermissions @this)
 {
     return(@this.Has(ChannelPermission.ViewChannel | ChannelPermission.SendMessages));
 }
コード例 #7
0
        public override async Task <bool> HandleTextMessage(SocketMessage message)
        {
            // Get the guild
            SocketGuild guild = (message.Channel as SocketGuildChannel).Guild;

            // Parse the channel ID
            ulong channelId;

            try
            {
                channelId = MentionUtils.ParseChannel(message.Content);
            }
            catch (ArgumentException)
            {
                await DiscordUtil.SendErrorMessageByLocalizedDescription(guild, this.Channel, "discord.setup.enter_channel.bad_channel");

                return(false);
            }

            // Get the channel
            SocketChannel foundChannel = DiscordBot.GetChannel(channelId);

            // Check if it exists
            if (foundChannel == null)
            {
                await DiscordUtil.SendErrorMessageByLocalizedDescription(guild, this.Channel, "discord.setup.enter_channel.bad_channel");

                return(false);
            }

            // Check this channel's guild
            SocketGuildChannel socketGuildChannel = foundChannel as SocketGuildChannel;

            // Check that this exists and that it is in the user's guild
            if (socketGuildChannel == null || socketGuildChannel.Guild.Id != SetupFlow.Guild.Id)
            {
                await DiscordUtil.SendErrorMessageByLocalizedDescription(guild, this.Channel, "discord.setup.enter_channel.bad_channel");

                return(false);
            }

            // Get the text channel
            SocketTextChannel socketTextChannel = foundChannel as SocketTextChannel;

            // Check if this is a text channel
            if (socketTextChannel == null)
            {
                await DiscordUtil.SendErrorMessageByLocalizedDescription(guild, this.Channel, "discord.setup.enter_channel.bad_channel");

                return(false);
            }

            // Check if this already exists as settings
            if (SetupFlow.GuildSettings.ChannelSettings.Where(p => p.Key == channelId).Count() != 0)
            {
                await DiscordUtil.SendErrorMessageByLocalizedDescription(guild, this.Channel, "discord.setup.enter_channel.already_exists");

                return(false);
            }

            // Get all required permissions
            List <ChannelPermission> requiredPermissions = new ChannelPermissions(Configuration.LoadedConfiguration.DiscordConfig.Permissions).ToList();

            // Get current permissions for this channel
            ChannelPermissions channelPermissions = guild.CurrentUser.GetPermissions(socketTextChannel);

            // Get a list of permissions that the bot does not have
            IEnumerable <ChannelPermission> missingPermissions = requiredPermissions.Where(x => !channelPermissions.Has(x));

            // Check if we are missing any
            if (missingPermissions.Count() > 0)
            {
                // Try to get the default language
                Language language = DiscordUtil.GetDefaultLanguage(guild);

                // Create the description string for the error message
                string description = Localizer.Localize("discord.setup.enter_channel.missing_permissions", language) + "\n\n";

                // Append the permissions
                foreach (ChannelPermission permission in missingPermissions)
                {
                    description += permission.ToString() + "\n";
                }

                // Create an embed
                await DiscordUtil.SendErrorMessageByDescription(guild, this.Channel, description);

                return(false);
            }

            // Set the new message flag
            SetupFlow.ShouldSendNewMessage = true;

            if (SetupFlow.ChannelSettings == null)
            {
                // Create a DynamicSettingsData instance
                SetupFlow.ChannelSettings = new DynamicSettingsData();

                // Set the ID
                SetupFlow.TargetChannelId = channelId;

                // Proceed to language selection
                await SetupFlow.SetPage((int)SetupFlowPage.SelectLanguage);
            }
            else
            {
                // Move the data
                SetupFlow.GuildSettings.ChannelSettings.TryRemove(SetupFlow.TargetChannelId, out DynamicSettingsData data);
                SetupFlow.GuildSettings.ChannelSettings.TryAdd(channelId, data);

                // Set a pre-prompt
                SetupFlow.ModeSelectPrePromptLocalizable = "discord.setup.mode_select.pre_prompt.edits_saved";

                // Change to mode select
                await SetupFlow.SetPage((int)SetupFlowPage.ModeSelect);
            }

            return(false);
        }
コード例 #8
0
        private async Task HandleCommandAsync(SocketMessage rawMsg)
        {
            // Ignore system messages
            if (!(rawMsg is SocketUserMessage msg))
            {
                return;
            }

            // Ignore bot messages
            if (msg.Author.IsBot || msg.Author.IsWebhook)
            {
                return;
            }

            // Ignore messages from blacklisted users
            if (_settings.BlacklistedUsers?.Contains(msg.Author.Id) == true)
            {
                return;
            }

            // Ignore if the bot doesn't have the permission to send messages in the channel
            IGuildChannel guildChannel = msg.Channel as IGuildChannel;

            if (guildChannel != null)
            {
                IGuildUser guildUser = await guildChannel.Guild.GetCurrentUserAsync().ConfigureAwait(false);

                ChannelPermissions channelPermissions = guildUser.GetPermissions(guildChannel);
                if (!channelPermissions.Has(ChannelPermission.SendMessages))
                {
                    return;
                }
            }

            string prefix = _settings.Prefix;

            if (_settings.GuildSpecificSettings &&
                guildChannel != null)
            {
                using (GuildSettingsDatabase db = new GuildSettingsDatabase())
                {
                    prefix = (await db.GetSettingsAsync(guildChannel.Guild.Id).ConfigureAwait(false))?.Prefix ?? _settings.Prefix;
                }
            }

            // Mark where the prefix ends and the command begins
            int argPos = 0;

            // Determine if the message has a valid prefix, adjust argPos
            if (!(msg.HasMentionPrefix(_discordClient.CurrentUser, ref argPos) ||
                  msg.HasStringPrefix(prefix, ref argPos)))
            {
                return;
            }

            // Execute the Command, store the result
            IResult result = await _commandService.ExecuteAsync(
                new SocketCommandContext(_discordClient, msg), argPos, _serviceProvider).ConfigureAwait(false);

            // If the command failed, notify the user
            if (result.Error.HasValue && result.Error != CommandError.UnknownCommand)
            {
                _logger.LogError(result.ErrorReason);

                await msg.Channel.SendMessageAsync(string.Empty,
                                                   embed : new EmbedBuilder()
                {
                    Title       = "Error",
                    Color       = _settings.GetErrorColor(),
                    Description = result.ErrorReason
                }.Build()).ConfigureAwait(false);
            }
        }