Esempio n. 1
0
        string[] listPerms(ChannelPermission?channel, GuildPermission?guild)
        {
            var ls    = new List <string>();
            var flags = new List <ulong>();

            if (channel != null)
            {
                var a = new ChannelPermissions((ulong)channel);
                foreach (var x in a.ToList())
                {
                    ls.Add(x.ToString());
                    flags.Add((ulong)x);
                }
            }
            if (guild != null)
            {
                var b = new GuildPermissions((ulong)guild);
                foreach (var x in b.ToList())
                {
                    if (!flags.Contains((ulong)x))
                    {
                        ls.Add(x.ToString());
                    }
                }
            }
            return(ls.ToArray());
        }
        /// <summary>
        /// Checks whether the bot has the necessary permissions in the specified channel
        /// </summary>
        /// <param name="guildId">The guild id</param>
        /// <param name="channelId">The channel id</param>
        /// <returns>Returns true if the permissions are set correctly</returns>
        public bool?HasRequiredPermissions(ulong guildId, ulong channelId)
        {
            Logger.Info($"Checking channel permissions {guildId}/{channelId}");

            SocketTextChannel channel = GetTextChannel(channelId);

            if (channel == null)
            {
                return(null);
            }

            ChannelPermissions?permissions = GetGuild(guildId)?.CurrentUser?.GetPermissions(GetTextChannel(channelId));

            if (permissions == null)
            {
                return(null);
            }

            ChannelPermissions channelPermissions = (ChannelPermissions)permissions;

            return(channelPermissions.ViewChannel &&
                   channelPermissions.ReadMessageHistory &&
                   channelPermissions.SendMessages &&
                   channelPermissions.EmbedLinks);
        }
Esempio n. 3
0
        private async Task HandleCommandAsync(SocketMessage arg)
        {
            SocketUserMessage msg = arg as SocketUserMessage;
            if (msg == null) return;
            if (msg.Content == string.Empty) return;
            if (msg.Author.Id == Program.DiscordClient.CurrentUser.Id || msg.Author.IsBot) return;

            UserEntry usr = await Program.Users.GetUserByDiscordID(msg.Author.Id);
            if (usr == null) return;

            // Create a command context
            SocketCommandContext context = new SocketCommandContext(Program.DiscordClient, msg);

            // Create permissions list
            ChannelPermissions asd = (context.User as SocketGuildUser).GetPermissions(arg.Channel as IGuildChannel);



            if (msg.Content[0] == Program.CommandCharacter)
            {
                List<string> args = new List<string>();
                args.AddRange(msg.Content.Split(' '));
                string cmd = args[0];
                cmd = cmd.Remove(0, 1);
                args.RemoveAt(0);
                Program.BotEvents.RaiseOnCommandRecieved(new BotWideCommandArguments()
                {
                    source = MESSAGESOURCE.DISCORD,
                    channelID = msg.Channel.Id,
                    guildID = context.Guild.Id,
                    messageID = context.Message.Id,
                    isBroadcaster = false,
                    isModerator = false,
                    canManageMessages = asd.ManageMessages,
                    user = usr,
                    userDisplayName = arg.Author.Username,
                    command = cmd.ToLower(),
                    message = msg.Content,
                    arguments = args
                });


            }
            else
            {
                Program.BotEvents.RaiseOnMessageReceived(new BotWideMessageArguments()
                {
                    source = MESSAGESOURCE.DISCORD,
                    channelID = msg.Channel.Id,
                    guildID = context.Guild.Id, 
                    isBroadcaster = false,
                    isModerator = false,
                    canManageMessages = asd.ManageMessages,
                    user = usr,
                    userDisplayName = arg.Author.Username,
                    message = msg.Content
                });
            }
        }
Esempio n. 4
0
 public RequireAuthorChannelPermissionsAttribute(Permission permissions)
 {
     Permissions = ChannelPermissions.Mask(permissions, out var remainingPermissions);
     if (remainingPermissions != Permission.None)
     {
         Throw.ArgumentOutOfRangeException(nameof(permissions), $"The permissions specified for {GetType()} contain non-channel permissions: {remainingPermissions}.");
     }
 }
Esempio n. 5
0
        private bool HasSufficientTextPerms(SocketGuildChannel channel)
        {
            SocketGuildChannel guildChannel = (SocketGuildChannel)channel;

            ChannelPermissions perms = GetBotPerms(guildChannel);

            //Return true if we have the perms ViewChannel and SendMessages and EmbedLinks and AttachFiles
            return(perms.ViewChannel && perms.SendMessages && perms.EmbedLinks && perms.AttachFiles);
        }
        public async void ReadSinceTimestamp(SocketGuild guild, DateTime lastReceivedTime, ISocketMessageChannel replyChannel)
        {
            await BotLog(new LogMessage(LogSeverity.Info, "Replicator", "Reading new messages since last login"));

            DiscordServerInfo serverInfo = AvailableServers[guild.Id];

            serverInfo.Locked = true;
            foreach (var channel in guild.TextChannels)
            {
                await replyChannel.SendMessageAsync($"Reading new messages in channel {channel.Mention}");

                ChannelPermissions permissions = guild.GetUser(_client.CurrentUser.Id).GetPermissions(channel);
                if (permissions.ReadMessageHistory && permissions.ViewChannel)
                {
                    var      lastMessage = (await channel.GetMessagesAsync(1).Flatten().ToList())[0];
                    DateTime currentTime = lastMessage.Timestamp.UtcDateTime;
                    if (lastMessage != null)
                    {
                        while (currentTime >= lastReceivedTime)
                        {
                            var messageCollection = await channel.GetMessagesAsync(lastMessage, Direction.Before, 10).Flatten().ToList();

                            foreach (var message in messageCollection)
                            {
                                if (string.IsNullOrEmpty(message.Content) || message.Content[0] != '!')
                                {
                                    lastMessage = message;
                                    currentTime = lastMessage.Timestamp.UtcDateTime;
                                    if (currentTime >= lastReceivedTime)
                                    {
                                        break;
                                    }
                                    if (serverInfo.AvailableMessages.ContainsKey(lastMessage.Id))
                                    {
                                        break;
                                    }
                                    serverInfo.GuildTotalMessages += 1;
                                    if (TestValidMessage(message, serverInfo))
                                    {
                                        serverInfo.AvailableMessages.Add(message.Id, message.Content);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    await replyChannel.SendMessageAsync($"No permission to read in channel {channel.Mention}");
                }
            }
            await replyChannel.SendMessageAsync("Read all new messages");

            serverInfo.Locked = false;
            serverInfo.LastMessageReceived = DateTime.UtcNow;
            serverInfo.Flush();
        }
Esempio n. 7
0
        public RequireMemberChannelPermissions(params Permission[] permissions)
        {
            if (permissions == null)
            {
                throw new ArgumentNullException(nameof(permissions));
            }

            Permissions = permissions.Aggregate(Permission.None, (total, permission) => total | permission);
        }
        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}\"");
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Casts the <see cref="ChannelPermissions"/> struct to the <see cref="ChannelPermission"/> enum.
        /// </summary>
        /// <param name="perms">The <see cref="ChannelPermissions"/> struct.</param>
        /// <returns>The <see cref="ChannelPermission"/> enum</returns>
        public static ChannelPermission ToEnum(this ChannelPermissions perms)
        {
            ChannelPermission outPerms = 0;

            foreach (ChannelPermission perm in perms.ToList())
            {
                outPerms |= perm;
            }
            return(outPerms);
        }
Esempio n. 10
0
        public async Task SetDoneEmoji(ICommandContext context)
        {
            ChannelPermissions botPerms = await GetBotPerms(context);

            if (botPerms.ManageMessages)
            {
                await context.Message.RemoveAllReactionsAsync();
            }
            //await context.Message.AddReactionAsync(EmojiExtensions.FromText(":white_check_mark:"));
        }
Esempio n. 11
0
        public static bool CheckChannelPermission(this IMessageChannel channel, ChannelPermission permission, IGuildUser guildUser)
        {
            var guildchannel = channel as IGuildChannel;

            ChannelPermissions perms;

            perms = guildchannel != null?guildUser.GetPermissions(guildchannel) : ChannelPermissions.All(null);

            return(perms.Has(permission));
        }
Esempio n. 12
0
        public static async Task <ICommandResult> Analytics(DiscordUserMessageContext context, bool includeMessageText = false)
        {
            await(await context.Channel.SendMessageAsync("This is going to take a while")).AddReactionAsync(CommandTools.LoadingEmote);

            using (context.Channel.EnterTypingState())
            {
                // Channel Name => User Name => Date => Hour
                List <string> data = new List <string>();
                data.Add($"MessageID\tChannel\tUser\tIsBot\tTimestamp\tUnixTimestamp\tEditedTimestamp\tUnixEditedTimestamp\tMessageLength\tEmbedType\tHasAttachment\tReactionCount{(includeMessageText ? "\tMessage Text" : "")}");
                var channels = await context.Guild.GetTextChannelsAsync();

                foreach (ITextChannel channel in channels)
                {
                    ChannelPermissions permissions = (await context.Guild.GetCurrentUserAsync()).GetPermissions(channel);
                    if (!permissions.ViewChannel || !permissions.ReadMessageHistory)
                    {
                        continue;
                    }

                    var pages = channel.GetMessagesAsync(int.MaxValue);
                    pages.ForEach(
                        page =>
                    {
                        foreach (IMessage message in page)
                        {
                            var timestampLocal = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(message.Timestamp, context.Bot.DefaultTimeZone);
                            DateTimeOffset?editedTimestampLocal = null;
                            if (message.EditedTimestamp != null)
                            {
                                editedTimestampLocal = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(message.EditedTimestamp.Value, context.Bot.DefaultTimeZone);
                            }
                            data.Add($"{message.Id}\t{message.Channel.Name}\t{message.Author}\t{message.Author.IsBot}\t{timestampLocal.DateTime:G}\t{timestampLocal.ToUnixTimeSeconds()}\t{editedTimestampLocal?.ToString("G") ?? ""}\t{editedTimestampLocal?.ToUnixTimeSeconds().ToString() ?? ""}\t{new System.Globalization.StringInfo(message.Content).LengthInTextElements}\t{message.Embeds.FirstOrDefault()?.Type.ToString() ?? ""}\t{message.Attachments.Count > 0}\t{(message as IUserMessage)?.Reactions.Count ?? 0}{(includeMessageText ? $"\t{message.Content.Replace("\n", "␊").Replace("\r", "")}" : "")}");
                        }
                    });
                }

                File.WriteAllLines(Config.BasePath + $"analytics-{context.Guild.Id}.txt", data);

                if (!includeMessageText)
                {
                    using (var stream = File.OpenRead(Config.BasePath + $"analytics-{context.Guild.Id}.txt"))
                    {
                        await context.Channel.SendFileAsync(stream, $"analytics-{context.Guild.Id}-{DateTimeOffset.Now.ToUnixTimeSeconds()}.txt");
                    }
                }
                else
                {
                    await context.Reply($"Finished creating analytics file. Saved as `analytics-{context.Guild.Id}.txt` ({Math.Round(new FileInfo(Config.BasePath + $"analytics-{context.Guild.Id}.txt").Length / 1048576d, 2)} MB)");
                }
            }
            return(new SuccessResult());
        }
Esempio n. 13
0
        public static async Task DiscordResponse(BotWideResponseArguments args)
        {
            SocketChannel   sChannel = Program.DiscordClient.GetChannel(args.discordChannel);
            SocketGuildUser sUser    = (sChannel as SocketGuildChannel).Guild.GetUser(args.user._discordUID);
            // Create permissions list
            ChannelPermissions asd = sUser.GetPermissions(sChannel as IGuildChannel);

            if (!asd.SendMessages)
            {
                // Can't send to channel so aborting
                return;
            }
            await(sChannel as ISocketMessageChannel).SendMessageAsync(args.message);
        }
Esempio n. 14
0
        PreconditionResult CheckUser(IUser user, IChannel channel)
        {
            var guildUser = user as IGuildUser;

            // If user is server owner or has the administrator role
            // they get a free pass.
            if (guildUser != null &&
                (guildUser.IsServerOwner() ||
                 guildUser.GuildPermissions
                 .Has(Discord.GuildPermission.Administrator)))
            {
                return(PreconditionResult.FromSuccess());
            }
            if (GuildPermission != null)
            {
                if (guildUser == null)
                {
                    return(PreconditionResult.FromError("Command must be used in a guild channel"));
                }
                foreach (GuildPermission guildPermission in GuildPermission)
                {
                    if (!guildUser.GuildPermissions.Has(guildPermission))
                    {
                        return(PreconditionResult.FromError($"Command requires guild permission {guildPermission.ToString().SplitCamelCase().Code()}"));
                    }
                }
            }

            if (ChannelPermission != null)
            {
                var guildChannel = channel as IGuildChannel;
                ChannelPermissions perms;
                if (guildChannel != null)
                {
                    perms = guildUser.GetPermissions(guildChannel);
                }
                else
                {
                    perms = ChannelPermissions.All(guildChannel);
                }
                foreach (ChannelPermission channelPermission in ChannelPermission)
                {
                    if (!perms.Has(channelPermission))
                    {
                        return(PreconditionResult.FromError($"Command requires channel permission {channelPermission.ToString().SplitCamelCase().Code()}"));
                    }
                }
            }
            return(PreconditionResult.FromSuccess());
        }
Esempio n. 15
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;
        }
Esempio n. 16
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context,
                                                                              CommandInfo command, IServiceProvider services)
        {
            if (
                services.GetService <Configuration>().OwnerIds.Contains(context.User.Id))
            {
                return(PreconditionResult.FromSuccess());
            }
            IGuildUser guildUser = null;

            if (context.Guild != null)
            {
                guildUser = await context.Guild.GetCurrentUserAsync().ConfigureAwait(false);
            }

            if (GuildPermission.HasValue)
            {
                if (guildUser == null)
                {
                    return(PreconditionResult.FromError(
                               $"This command can only be used in a {"server".InlineCode()} channel"));
                }
                if (!guildUser.GuildPermissions.Has(GuildPermission.Value))
                {
                    return(PreconditionResult.FromError(
                               $"I need the permission {GuildPermission.Value.Humanize(LetterCasing.Title).ToLower().InlineCode()} to do this"));
                }
            }

            if (!ChannelPermission.HasValue)
            {
                return(PreconditionResult.FromSuccess());
            }
            ChannelPermissions perms;

            if (context.Channel is IGuildChannel guildChannel)
            {
                perms = guildUser.GetPermissions(guildChannel);
            }
            else
            {
                perms = ChannelPermissions.All(context.Channel);
            }

            return(!perms.Has(ChannelPermission.Value)
                ? PreconditionResult.FromError(
                       $"I need the channel permission {ChannelPermission.Value.Humanize(LetterCasing.Title).ToLower().InlineCode()} to do this")
                : PreconditionResult.FromSuccess());
        }
Esempio n. 17
0
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command,
                                                                        IServiceProvider services)
        {
            if (services.GetService <Configuration>().OwnerIds.Contains(context.User.Id))
            {
                return(Task.FromResult(PreconditionResult.FromSuccess()));
            }
            var guildUser = context.User as IGuildUser;

            if (GuildPermission.HasValue)
            {
                if (guildUser == null)
                {
                    return(Task.FromResult(
                               PreconditionResult.FromError(
                                   $"This command is only available in {"server".InlineCode()} channels")));
                }
                if (!guildUser.GuildPermissions.Has(GuildPermission.Value))
                {
                    return(Task.FromResult(
                               PreconditionResult.FromError(
                                   $"You need the permission {GuildPermission.Value.Humanize(LetterCasing.Title).ToLower().InlineCode()} to do this")));
                }
            }

            if (!ChannelPermission.HasValue)
            {
                return(Task.FromResult(PreconditionResult.FromSuccess()));
            }
            ChannelPermissions perms;

            if (context.Channel is IGuildChannel guildChannel)
            {
                perms = guildUser.GetPermissions(guildChannel);
            }
            else
            {
                perms = ChannelPermissions.All(context.Channel);
            }

            if (!perms.Has(ChannelPermission.Value))
            {
                return(Task.FromResult(PreconditionResult.FromError(
                                           $"You need the channel permission {ChannelPermission.Value.Humanize(LetterCasing.Title).ToLower().InlineCode()} to do this")));
            }

            return(Task.FromResult(PreconditionResult.FromSuccess()));
        }
Esempio n. 18
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext ctx, CommandInfo command, IServiceProvider services)
        {
            var context = (ShadeContext)ctx;

            // Includes owner and trusted users.
            var isTrusted = await new RequireTrustedUserAttribute().CheckPermissionsAsync(ctx, command, services);

            if (isTrusted.IsSuccess)
            {
                return(PreconditionResult.FromSuccess());
            }

            var guildUser = context.PermissionUser;

            if (GuildPermission.HasValue)
            {
                if (guildUser == null)
                {
                    return(PreconditionResult.FromError(NotAGuildErrorMessage ?? "Command must be used in a guild channel."));
                }
                if (!guildUser.GuildPermissions.Has(GuildPermission.Value))
                {
                    return(PreconditionResult.FromError(ErrorMessage ?? $"User requires guild permission {GuildPermission.Value}."));
                }
            }

            if (ChannelPermission.HasValue)
            {
                ChannelPermissions perms;
                if (context.Channel is IGuildChannel guildChannel)
                {
                    perms = guildUser.GetPermissions(guildChannel);
                }
                else
                {
                    perms = ChannelPermissions.All(context.Channel);
                }

                if (!perms.Has(ChannelPermission.Value))
                {
                    return(PreconditionResult.FromError(ErrorMessage ?? $"User requires channel permission {ChannelPermission.Value}."));
                }
            }

            return(PreconditionResult.FromSuccess());
        }
        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);
        }
Esempio n. 20
0
        public static async Task <Leaderboard> GenerateFullLeaderboard(IGuild guild, DiscordBot bot, DateTimeOffset creationTime)
        {
            var leaderboard = new Leaderboard(guild.Id, LeaderboardType.Full, bot, creationTime);

            leaderboard.OldLeaderboard = bot.Leaderboards.Leaderboards.GetValueOrDefault(guild.Id);

            var channels = await guild.GetTextChannelsAsync();

            foreach (ITextChannel channel in channels)
            {
                ChannelPermissions permissions = (await guild.GetCurrentUserAsync()).GetPermissions(channel);
                if (!permissions.ViewChannel || !permissions.ReadMessageHistory)
                {
                    continue;
                }

                int messagesInChannel = 0;

                var pages = channel.GetMessagesAsync(int.MaxValue);
                pages.ForEach(
                    page =>
                {
                    foreach (IMessage message in page.Where(message => message.Timestamp <= creationTime))
                    {
                        if (!leaderboard.UserMessages.ContainsKey(message.Author.Id))
                        {
                            leaderboard.UserMessages.Add(message.Author.Id, 0);
                            leaderboard.UserLookup.Add(message.Author.Id, message.Author.NicknameOrUsername());
                        }

                        leaderboard.UserMessages[message.Author.Id]++;
                        messagesInChannel++;
                    }
                });

                leaderboard.ChannelMessages[channel.Id] = messagesInChannel;
                leaderboard.TotalMessages += messagesInChannel;
                leaderboard.ChannelLookup.Add(channel.Id, channel.Name);
            }

            bot.Leaderboards.Leaderboards[guild.Id] = leaderboard;
            bot.Leaderboards.SaveConfig();

            return(leaderboard);
        }
Esempio n. 21
0
        public async Task Someone([Remainder] string text)
        {
            SocketGuildUser             guildUser   = (SocketGuildUser)Context.User;
            ChannelPermissions          permissions = guildUser.GetPermissions((IGuildChannel)Context.Channel);
            IReadOnlyCollection <IUser> users       = await Context.Channel.GetUsersAsync().ElementAt(0);

            Random random = new Random();
            int    r      = random.Next(users.Count);

            if (permissions.MentionEveryone)
            {
                await ReplyAsync(users.ElementAt(r).Mention + " " + text);
            }
            else
            {
                await ReplyAsync(Utilities.MessageUtil.CleanMention(users.ElementAt(r).Mention + " " + text));
            }
        }
Esempio n. 22
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            IGuildUser guildUser = null;

            if (context.Guild != null)
            {
                guildUser = await context.Guild.GetCurrentUserAsync().ConfigureAwait(false);
            }

            if (GuildPermission.HasValue)
            {
                if (guildUser == null)
                {
                    return(PreconditionResult.FromError("Command must be used in a guild channel"));
                }
                if (!guildUser.GuildPermissions.Has(GuildPermission.Value))
                {
                    return(PreconditionResult.FromError($"Bot requires guild permission {GuildPermission.Value}"));
                }
            }

            if (ChannelPermission.HasValue)
            {
                var guildChannel = context.Channel as IGuildChannel;

                ChannelPermissions perms;
                if (guildChannel != null)
                {
                    perms = guildUser.GetPermissions(guildChannel);
                }
                else
                {
                    perms = ChannelPermissions.All(guildChannel);
                }

                if (!perms.Has(ChannelPermission.Value))
                {
                    return(PreconditionResult.FromError($"Bot requires channel permission {ChannelPermission.Value}"));
                }
            }

            return(PreconditionResult.FromSuccess());
        }
        private async Task MessageReceivedAsync(SocketMessage message)
        {
            SocketGuild messageGuild = (message.Author as IGuildUser).Guild as SocketGuild;

            AvailableServers.TryGetValue(messageGuild.Id, out DiscordServerInfo serverInfo);
            ChannelPermissions permissions = messageGuild.GetUser(_client.CurrentUser.Id).GetPermissions(message.Channel as IGuildChannel);
            Random             rand        = new Random();

            if (serverInfo.Enabled && !serverInfo.Locked && (string.IsNullOrEmpty(message.Content) || message.Content[0] != '!') && message.Author.Id != _client.CurrentUser.Id)
            {
                serverInfo.LastMessageReceived = DateTime.UtcNow;
                if (permissions.SendMessages && permissions.ViewChannel)
                {
                    if (message.MentionedUsers.Any(u => u.Id == _client.CurrentUser.Id))
                    {
                        if (serverInfo.TargetTotalMessages != 0)
                        {
                            await message.Channel.SendMessageAsync(serverInfo.AvailableMessages.Values.ElementAt(rand.Next(0, serverInfo.TargetTotalMessages)));
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                if (permissions.ViewChannel && permissions.ReadMessageHistory)
                {
                    serverInfo.GuildTotalMessages += 1;
                    if (TestValidMessage(message, serverInfo))
                    {
                        serverInfo.AvailableMessages.Add(message.Id, message.Content);
                    }
                }
                if (permissions.ViewChannel && permissions.SendMessages)
                {
                    if (rand.NextDouble() < serverInfo.Proability)
                    {
                        await message.Channel.SendMessageAsync(serverInfo.AvailableMessages.Values.ElementAt(rand.Next(0, serverInfo.TargetTotalMessages)));
                    }
                }
            }
        }
        /// <inheritdoc />
        public override async Task <PreconditionResult> CheckRequirementsAsync(IInteractionContext context, ICommandInfo command, IServiceProvider services)
        {
            IGuildUser guildUser = null;

            if (context.Guild != null)
            {
                guildUser = await context.Guild.GetCurrentUserAsync().ConfigureAwait(false);
            }

            if (GuildPermission.HasValue)
            {
                if (guildUser == null)
                {
                    return(PreconditionResult.FromError(NotAGuildErrorMessage ?? "Command must be used in a guild channel."));
                }
                if (!guildUser.GuildPermissions.Has(GuildPermission.Value))
                {
                    return(PreconditionResult.FromError(ErrorMessage ?? $"Bot requires guild permission {GuildPermission.Value}."));
                }
            }

            if (ChannelPermission.HasValue)
            {
                ChannelPermissions perms;
                if (context.Channel is IGuildChannel guildChannel)
                {
                    perms = guildUser.GetPermissions(guildChannel);
                }
                else
                {
                    perms = ChannelPermissions.All(context.Channel);
                }

                if (!perms.Has(ChannelPermission.Value))
                {
                    return(PreconditionResult.FromError(ErrorMessage ?? $"Bot requires channel permission {ChannelPermission.Value}."));
                }
            }

            return(PreconditionResult.FromSuccess());
        }
Esempio n. 25
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)));
                }
            }
Esempio n. 26
0
        public async Task Usage()
        {
            ChannelPermissions perms;
            var user = Context.User as IGuildUser;

            await ReplyAsync($"Command is {Current ?? "_not set_"}");

            if (Context.Channel is IGuildChannel guildChannel)
            {
                perms = user.GetPermissions(guildChannel);
            }
            else
            {
                perms = ChannelPermissions.All(Context.Channel);
            }

            if (perms.Has(ChannelPermission.ManageChannels))
            {
                await ReplyAsync($"!enable {string.Join("|", Config.Command)}");
            }
        }
Esempio n. 27
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;
        }
        public async void ReadAllMessages(SocketGuild guild, int maxChannelRead, ISocketMessageChannel replyChannel)
        {
            var serverInfo = AvailableServers[guild.Id];

            serverInfo.AvailableMessages  = new Dictionary <ulong, string>();
            serverInfo.GuildTotalMessages = 0;
            serverInfo.Locked             = true;

            foreach (var channel in guild.TextChannels)
            {
                await replyChannel.SendMessageAsync($"Attempting to read messages in channel {channel.Mention}");

                ChannelPermissions permissions = guild.GetUser(_client.CurrentUser.Id).GetPermissions(channel);
                if (permissions.ReadMessageHistory && permissions.ViewChannel)
                {
                    var messageCollection = channel.GetMessagesAsync(maxChannelRead).Flatten();
                    foreach (var message in await messageCollection.ToList())
                    {
                        if (string.IsNullOrEmpty(message.Content) || message.Content[0] != '!')
                        {
                            serverInfo.GuildTotalMessages += 1;
                            if (TestValidMessage(message, serverInfo))
                            {
                                serverInfo.AvailableMessages.Add(message.Id, message.Content);
                            }
                        }
                    }
                }
                else
                {
                    await replyChannel.SendMessageAsync($"No permission to read in channel {channel.Mention}");
                }
            }
            serverInfo.Locked              = false;
            serverInfo.Enabled             = true;
            serverInfo.LastMessageReceived = DateTime.UtcNow;
            serverInfo.Flush();
            await replyChannel.SendMessageAsync("Read all messages on the server and Replicator is now active");
        }
Esempio n. 29
0
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var guildUser = context.User as IGuildUser;

            if (GuildPermission.HasValue)
            {
                if (guildUser == null)
                {
                    return(Task.FromResult(PreconditionResult.FromError("Command must be used in a guild channel")));
                }
                if (!guildUser.GuildPermissions.Has(GuildPermission.Value))
                {
                    return(Task.FromResult(PreconditionResult.FromError($"User requires guild permission {GuildPermission.Value}")));
                }
            }

            if (ChannelPermission.HasValue)
            {
                var guildChannel = context.Channel as IGuildChannel;

                ChannelPermissions perms;
                if (guildChannel != null)
                {
                    perms = guildUser.GetPermissions(guildChannel);
                }
                else
                {
                    perms = ChannelPermissions.All(guildChannel);
                }

                if (!perms.Has(ChannelPermission.Value))
                {
                    return(Task.FromResult(PreconditionResult.FromError($"User requires channel permission {ChannelPermission.Value}")));
                }
            }

            return(Task.FromResult(PreconditionResult.FromSuccess()));
        }
        public override async Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IDependencyMap map)
        {
            var guildUser = await context.Guild.GetCurrentUserAsync();

            if (GuildPermission.HasValue)
            {
                if (guildUser == null)
                {
                    return(PreconditionResult.FromError("Command must be used in a guild channel"));
                }
                if (!guildUser.GuildPermissions.Has(GuildPermission.Value))
                {
                    return(PreconditionResult.FromError($"Command requires guild permission {GuildPermission.Value}"));
                }
            }

            if (ChannelPermission.HasValue)
            {
                var guildChannel = context.Channel as IGuildChannel;

                ChannelPermissions perms;
                if (guildChannel != null)
                {
                    perms = guildUser.GetPermissions(guildChannel);
                }
                else
                {
                    perms = ChannelPermissions.All(guildChannel);
                }

                if (!perms.Has(ChannelPermission.Value))
                {
                    return(PreconditionResult.FromError($"Command requires channel permission {ChannelPermission.Value}"));
                }
            }

            return(PreconditionResult.FromSuccess());
        }
Esempio n. 31
0
 public static Task SetChannelPermissions(this DiscordClient client, Channel channel, Role role, ChannelPermissions allow, ChannelPermissions deny)
 {
     throw new InvalidOperationException();
 }
 public RealtimePermission(string c, ChannelPermissions p)
 {
     Channel = c;
     Permission = p;
 }
Esempio n. 33
0
 public static Task SetChannelPermissions(this DiscordClient client, Channel channel, Role role, ChannelPermissions allow = null, ChannelPermissions deny = null)
 {
     if (channel == null) throw new ArgumentNullException(nameof(channel));
     return channel.AddPermissionsRule(role, allow, deny);
 }