Beispiel #1
0
        public void GetModerationType_Follower_WhiteListing_Test()
        {
            #region Stubs
            var settings = new ModerationSettings
            {
                FollowersWhiteListing = "@[email protected]"
            };
            #endregion

            var repo = new ModerationRepository(settings);

            #region Validations
            Assert.AreEqual(ModerationTypeEnum.WhiteListing, repo.GetModerationType(ModerationEntityTypeEnum.Follower));
            Assert.AreEqual(ModerationTypeEnum.None, repo.GetModerationType(ModerationEntityTypeEnum.TwitterAccount));
            #endregion
        }
Beispiel #2
0
        public void CheckStatus_Follower_BothListing_Test()
        {
            #region Stubs
            var settings = new ModerationSettings
            {
                FollowersWhiteListing = "@[email protected]",
                FollowersBlackListing = "@[email protected]"
            };
            #endregion

            var repo = new ModerationRepository(settings);

            #region Validations
            Assert.AreEqual(ModeratedTypeEnum.WhiteListed, repo.CheckStatus(ModerationEntityTypeEnum.Follower, "@[email protected]"));
            Assert.AreEqual(ModeratedTypeEnum.None, repo.CheckStatus(ModerationEntityTypeEnum.Follower, "@[email protected]"));
            #endregion
        }
Beispiel #3
0
        public async Task AddWarnRole(SocketRole role)
        {
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>(true);

            if (!settings.ableToWarn.Contains(role.Id))
            {
                settings.ableToWarn.Add(role.Id);
            }
            else
            {
                _ = ReplyAsync("People with the role \"" + role.Name + "\" can already warn people");
            }

            settings.SaveToFile(Context.Guild);

            await ReplyAsync("People with the role \"" + role.Name + "\" can now warn people");
        }
Beispiel #4
0
        public override void Recreate()
        {
            PacketModified.Append(Unknown0);

            RoomData.WriteTo(PacketModified);

            PacketModified.Append(Unknown1);
            PacketModified.Append(Unknown2);
            PacketModified.Append(Unknown3);
            PacketModified.Append(Unknown4);

            ModerationSettings.WriteTo(PacketModified);

            PacketModified.Append(Unknown5);

            ChatSettings.WriteTo(PacketModified);
        }
        private NewChannelsState GetNewChannelState(ModerationSettings currentSettings, FilterType type,
                                                    List <ulong> channelIds)
        {
            var currentWhitelistedChannels = currentSettings?.WhitelistedChannels.Where(c => c.WhitelistType == type);

            var channelsToAdd = new List <WhitelistedChannel>();

            var channelsToRemove = new List <WhitelistedChannel>();

            if (channelIds is null)
            {
                channelIds = new List <ulong>();
            }

            if (currentWhitelistedChannels is null)
            {
                currentWhitelistedChannels = new List <WhitelistedChannel>();
            }

            foreach (var channelId in channelIds)
            {
                if (!currentWhitelistedChannels.Any(c => c.ChannelId == channelId))
                {
                    channelsToAdd.Add(new WhitelistedChannel
                    {
                        ChannelId     = channelId,
                        GuildId       = currentSettings.GuildId,
                        WhitelistType = type
                    });
                }
            }

            foreach (var channel in currentWhitelistedChannels)
            {
                if (!channelIds.Any(c => c == channel.ChannelId))
                {
                    channelsToRemove.Add(channel);
                }
            }

            return(new NewChannelsState
            {
                ChannelsToAdd = channelsToAdd,
                ChannelsToRemove = channelsToRemove
            });
        }
Beispiel #6
0
        public async Task ToggleAutoMod()
        {
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>(true);

            if (settings.channelsWithoutAutoMod.Contains(Context.Channel.Id))
            {
                settings.channelsWithoutAutoMod.Remove(Context.Channel.Id);
                await ReplyAsync("Enabled automod in this channel");
            }
            else
            {
                settings.channelsWithoutAutoMod.Add(Context.Channel.Id);
                await ReplyAsync("Disabled automod in this channel");
            }

            settings.SaveToFile(Context.Guild);
        }
Beispiel #7
0
        public void CheckStatus_TwitterAccount_BothListing_Test()
        {
            #region Stubs
            var settings = new ModerationSettings
            {
                TwitterAccountsWhiteListing = "handle",
                TwitterAccountsBlackListing = "handle"
            };
            #endregion

            var repo = new ModerationRepository(settings);

            #region Validations
            Assert.AreEqual(ModeratedTypeEnum.WhiteListed, repo.CheckStatus(ModerationEntityTypeEnum.TwitterAccount, "handle"));
            Assert.AreEqual(ModeratedTypeEnum.None, repo.CheckStatus(ModerationEntityTypeEnum.TwitterAccount, "handle2"));
            #endregion
        }
        private NewRolesState GetNewRolesState(ModerationSettings currentSettings, FilterType type, List <ulong> roleIds)
        {
            var currentWhitelistedRoles = currentSettings?.WhitelistedRoles.Where(r => r.WhitelistType == type);

            var rolesToRemove = new List <WhitelistedRole>();

            var rolesToAdd = new List <WhitelistedRole>();

            if (roleIds is null)
            {
                roleIds = new List <ulong>();
            }

            if (currentWhitelistedRoles is null)
            {
                currentWhitelistedRoles = new List <WhitelistedRole>();
            }

            foreach (var roleId in roleIds)
            {
                if (!currentWhitelistedRoles.Any(c => c.RoleId == roleId))
                {
                    rolesToAdd.Add(new WhitelistedRole
                    {
                        GuildId       = currentSettings.GuildId,
                        RoleId        = roleId,
                        WhitelistType = type
                    });
                }
            }

            foreach (var role in currentWhitelistedRoles)
            {
                if (!roleIds.Any(r => r == role.RoleId))
                {
                    rolesToRemove.Add(role);
                }
            }

            return(new NewRolesState
            {
                RolesToAdd = rolesToAdd,
                RolesToRemove = rolesToRemove
            });
        }
Beispiel #9
0
        public async Task AddWarnIgnoredRole(SocketRole role)
        {
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>(true);

            if (settings.cantBeWarned == null)
            {
                settings.cantBeWarned = new List <ulong>();
            }
            else if (settings.cantBeWarned.Contains(role.Id))
            {
                await ReplyAsync($"Role '{role.Name}' is already not able to be warned");

                return;
            }
            settings.cantBeWarned.Add(role.Id);
            settings.SaveToFile(Context.Guild);
            await ReplyAsync($"Role '{role.Name}' will not be able to be warned now");
        }
Beispiel #10
0
        public async Task RemoveAllowedLink(string link)
        {
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>(true);

            if (settings.allowedLinks == null || !settings.allowedLinks.Contains(link))
            {
                await ReplyAsync("Link is already not allowed");

                return;
            }
            settings.allowedLinks.Remove(link);
            if (settings.allowedLinks.Count == 0)
            {
                settings.allowedLinks = null;
            }
            settings.SaveToFile(Context.Guild);
            await ReplyAsync("People will no longer be allowed to use " + link);
        }
Beispiel #11
0
        public async Task ToggleInviteWarn()
        {
            IUserMessage message = await ReplyAsync("Trying to toggle");

            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>(true);

            if (settings == null)
            {
                settings = new ModerationSettings();
                Console.WriteLine(DateTime.Now.ToShortTimeString() + " Creating new mod settings");
            }
            settings.invitesAllowed = !settings.invitesAllowed;
            Console.WriteLine(DateTime.Now.ToShortTimeString() + " setting invites to " + settings.invitesAllowed);

            settings.SaveToFile(Context.Guild);

            await message.ModifyAsync(msg => msg.Content = "set invites allowed to " + settings.invitesAllowed.ToString().ToLower());
        }
Beispiel #12
0
        public async Task AddAllowedLinkRole(SocketRole role)
        {
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>(true);

            if (settings.allowedToLink == null)
            {
                settings.allowedToLink = new List <ulong>();
            }
            if (settings.allowedToLink.Contains(role.Id))
            {
                await ReplyAsync($"Role '{role.Name}' was already exempt from link filtering");

                return;
            }
            settings.allowedToLink.Add(role.Id);
            settings.SaveToFile(Context.Guild);

            await ReplyAsync($"Role '{role.Name}' is now exempt from link filtering");
        }
        public async Task DynamicSlowmode(double factor)
        {
            if (factor < 0)
            {
                await ReplyAsync("Why would you need a factor that low?");

                return;
            }

            SocketTextChannel  channel   = Context.Channel as SocketTextChannel;
            ModerationSettings settings  = Context.Guild.LoadFromFile <ModerationSettings>(true);
            string             channelId = Convert.ToString(channel.Id);

            if (factor == 0)
            {
                settings.dynamicSlowmode.Remove(channelId);
                await ReplyAsync(channel.Mention + " no longer has dynamic slowmode.");
            }
            else
            {
                if (!settings.dynamicSlowmode.ContainsKey(channelId))
                {
                    settings.dynamicSlowmode.Add(channelId, factor);
                }
                else
                {
                    if (settings.dynamicSlowmode[channelId] == factor)
                    {
                        await ReplyAsync(channel.Mention + " already has a dynamic slowmode with a factor of " + factor + ".");

                        return;
                    }

                    settings.dynamicSlowmode[channelId] = factor;
                }

                await ReplyAsync(channel.Mention + " now has a dynamic slowmode with a factor of " + factor + ".");
            }

            settings.SaveToFile();
        }
Beispiel #14
0
        public async Task SetMaxEmojis(string amount)
        {
            ModerationSettings settings = null;

            switch (amount.ToLower())
            {
            case "null":
            case "none":
            case "disable":
                settings = Context.Guild.LoadFromFile <ModerationSettings>(false);
                if (settings?.maxEmojis == null)
                {
                    await ReplyAsync("Emoji moderation is already disabled");
                }
                else
                {
                    settings.maxEmojis = null;
                    settings.SaveToFile(Context.Guild);
                    await ReplyAsync("Emoji moderation is now disabled");
                }
                break;

            case "all":
                settings           = Context.Guild.LoadFromFile <ModerationSettings>(true);
                settings.maxEmojis = 0;
                settings.SaveToFile(Context.Guild);
                string extraInfo = "";
                if (settings.allowedToLink.NotEmpty())
                {
                    extraInfo = " except by role allowed to link";
                }
                await ReplyAsync("Emojis are now no longer allowed" + extraInfo);

                break;

            default:
                await ReplyAsync("Input not understood");

                break;
            }
        }
Beispiel #15
0
        public async Task RemoveAllowedLinkRole(SocketRole role)
        {
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>();

            if (settings == null || settings.allowedToLink == null)
            {
                await ReplyAsync($"No role is currently excused from posting links");

                return;
            }
            if (settings.allowedToLink.Contains(role.Id))
            {
                settings.allowedToLink.Remove(role.Id);
                settings.SaveToFile(Context.Guild);
                await ReplyAsync($"Role '{role.Name}' is no longer exempt from link filtering");

                return;
            }

            await ReplyAsync($"Role '{role.Name}' wasn't exempt from link filtering");
        }
Beispiel #16
0
        public async Task SetMaxPunishment(string length)
        {
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>(true);

            if (length == "none")
            { //Maybe add more options that mean none
                if (settings.maxTempAction == null)
                {
                    await ReplyAsync("The maximum temp punishment is already none");

                    return;
                }
                else
                {
                    settings.maxTempAction = null;
                    settings.SaveToFile();
                    await ReplyAsync("The maximum temp punishment is now none");
                }
                return;
            }
            TimeSpan?span = length.ToTime();

            if (span != null)
            {
                if (span == settings.maxTempAction)
                {
                    await ReplyAsync("The maximum temp punishment is already " + ((TimeSpan)span).LimitedHumanize(4));
                }
                else
                {
                    settings.maxTempAction = span;
                    settings.SaveToFile();
                    await ReplyAsync("The maximum temp punishment is now " + ((TimeSpan)span).LimitedHumanize(4));
                }
            }
            else
            {
                await ReplyAsync("Your time is incorrectly setup");
            }
        }
        public async Task TempMuteWarnUser([RequireHierarchy] UserRef userRef, TimeSpan time, float size, [Remainder] string reason)
        {
            if (time.TotalMinutes < 1)
            {
                await ReplyAsync("Can't temp-mute for less than a minute");

                return;
            }
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>();

            if (!(Context.Message.Author as IGuildUser).HasAdmin())
            {
                if (settings?.maxTempAction != null && time > settings.maxTempAction)
                {
                    await ReplyAsync("You are not allowed to punish for that long");

                    return;
                }
            }
            if (settings == null || settings.mutedRole == 0 || Context.Guild.GetRole(settings.mutedRole) == null)
            {
                await ReplyAsync("Muted role is null or invalid");

                return;
            }
            await userRef.Warn(size, reason, Context.Channel as ITextChannel, "Discord");

            TempActionList actions = Context.Guild.LoadFromFile <TempActionList>(true);

            if (actions.tempMutes.Any(tempMute => tempMute.User == userRef.ID))
            {
                await ReplyAsync($"{userRef.Name()} is already temp-muted, (the warn did go through)");

                return;
            }

            await userRef.TempMute(time, reason, Context, settings, actions);

            Context.Message.DeleteOrRespond($"Temporarily muted {userRef.Mention()} for {time.LimitedHumanize(3)} because of {reason}", Context.Guild);
        }
        public async Task Check()
        {
            try
            {
                foreach (SocketGuild guild in _client.Guilds)
                {
                    ModerationSettings settings = guild.LoadFromFile <ModerationSettings>();
                    if (settings?.dynamicSlowmode == null)
                    {
                        continue;
                    }
                    foreach (KeyValuePair <string, double> channelSetting in settings.dynamicSlowmode)
                    {
                        // Key: channel id
                        // Value: factor
                        SocketTextChannel channel = guild.GetTextChannel(Convert.ToUInt64(channelSetting.Key));

                        var messages = await channel.GetMessagesAsync(200).FlattenAsync();

                        messages = messages.Where(msg => msg.GetTimeAgo() < TimeSpan.FromMinutes(1));

                        var count = messages.Count() * channelSetting.Value;
                        //API limit
                        if (count >= 21599)
                        {
                            count = 21599;
                        }
                        if (count < 2)
                        {
                            count = 1;
                        }
                        await channel.ModifyAsync(c => c.SlowModeInterval = Convert.ToInt32(count));
                    }
                }
            }
            catch (Exception e)
            {
                await new LogMessage(LogSeverity.Error, "Slow", "Something went wrong in slowmode", e).Log();
            }
        }
        private NewWhitelistedLinksState GetNewLinksState(ModerationSettings currentSettings, HashSet <string> links)
        {
            var linksToAdd = new List <WhitelistedLink>();

            var linksToRemove = new List <WhitelistedLink>();

            var whitelistedLinks = currentSettings?.LinkFilter?.WhitelistedLinks ?? new List <WhitelistedLink>();

            if (links is null)
            {
                links = new HashSet <string>();
            }

            foreach (var link in links)
            {
                if (!whitelistedLinks.Any(l => l.Link == link))
                {
                    linksToAdd.Add(new WhitelistedLink
                    {
                        GuildId = currentSettings.GuildId,
                        Link    = link.ToLower()
                    });
                }
            }

            foreach (var link in whitelistedLinks)
            {
                if (!links.Contains(link.Link))
                {
                    linksToRemove.Add(link);
                }
            }

            return(new NewWhitelistedLinksState
            {
                LinksToAdd = linksToAdd,
                LinksToRemove = linksToRemove
            });
        }
        private NewBannedWordsState GetNewBannedWordsState(ModerationSettings currentSettings, HashSet <string> words)
        {
            var wordsToAdd = new List <BannedWord>();

            var wordsToRemove = new List <BannedWord>();

            var bannedWords = currentSettings?.ProfanityFilter?.BannedWords ?? new List <BannedWord>();

            if (words is null)
            {
                words = new HashSet <string>();
            }

            foreach (var word in words)
            {
                if (!bannedWords.Any(l => l.Word == word))
                {
                    wordsToAdd.Add(new BannedWord
                    {
                        Word    = word.ToLower(),
                        GuildId = currentSettings.GuildId
                    });
                }
            }

            foreach (var word in bannedWords)
            {
                if (!words.Contains(word.Word))
                {
                    wordsToRemove.Add(word);
                }
            }

            return(new NewBannedWordsState
            {
                WordsToAdd = wordsToAdd,
                WordsToRemove = wordsToRemove
            });
        }
Beispiel #21
0
        public async Task SetMutedRole(SocketRole role)
        {
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>(true);

            if (settings == null)
            {
                settings = new ModerationSettings();
            }
            if (settings.mutedRole != role.Id)
            {
                settings.mutedRole = role.Id;
            }
            else
            {
                _ = ReplyAsync("The role \"" + role.Name + "\" is already the muted role");
                return;
            }

            settings.SaveToFile(Context.Guild);

            await ReplyAsync("The role \"" + role.Name + "\" is now the muted role");
        }
Beispiel #22
0
        public static bool CantBeWarned(this SocketGuildUser user)
        {
            if (HasAdmin(user))
            {
                return(true);
            }

            ModerationSettings settings = user.Guild.LoadFromFile <ModerationSettings>();

            if (settings != null)
            {
                List <SocketRole> rolesUnableToBeWarned = new List <SocketRole>();
                foreach (ulong roleID in settings.cantBeWarned)
                {
                    rolesUnableToBeWarned.Add(user.Guild.GetRole(roleID));
                }
                if (user.Roles.Intersect(rolesUnableToBeWarned).Any())
                {
                    return(true);
                }
            }
            return(false);
        }
Beispiel #23
0
 public RoomData()
 {
     ModerationSettings = new ModerationSettings(this);
 }
Beispiel #24
0
        public async Task ModerationInfo()
        {
            ModerationSettings settings = SettingFunctions.LoadModSettings(Context.Guild, false);

            if (settings == null)
            {
                _ = ReplyAsync("Moderation settings are null");
                return;
            }

            var    embed           = new EmbedBuilder();
            string rolesAbleToWarn = "";

            foreach (SocketRole role in Context.Guild.Roles)
            {
                if (role.Permissions.KickMembers && !role.IsManaged)
                {
                    if (rolesAbleToWarn != "")
                    {
                        rolesAbleToWarn += "\n";
                    }
                    if (role.IsMentionable)
                    {
                        rolesAbleToWarn += role.Mention;
                    }
                    else
                    {
                        rolesAbleToWarn += role.Name;
                    }
                }
            }
            if (settings.ableToWarn != null && settings.ableToWarn.Count > 0)
            {
                foreach (ulong roleID in settings.ableToWarn)
                {
                    SocketRole role = Context.Guild.GetRole(roleID);
                    if (role != null)
                    {
                        if (rolesAbleToWarn != "")
                        {
                            rolesAbleToWarn += "\n";
                        }
                        if (role.IsMentionable)
                        {
                            rolesAbleToWarn += role.Mention;
                        }
                        else
                        {
                            rolesAbleToWarn += role.Name;
                        }
                    }
                    else
                    {
                        settings.ableToWarn.Remove(roleID);
                    }
                }
            }
            embed.AddField("Roles that can warn", rolesAbleToWarn, true);
            embed.AddField("Will invites lead to warn", !settings.invitesAllowed, true);
            await ReplyAsync(embed : embed.Build());
        }
Beispiel #25
0
        public async Task CheckMessage(SocketMessage message)
        {
            try {
                if (message.Author.IsBot || !(message.Channel is SocketGuildChannel) || !(message is SocketUserMessage))
                {
                    return; //Makes sure it's not logging a message from a bot and that it's in a discord server
                }
                SocketCommandContext context = new SocketCommandContext(client, message as SocketUserMessage);
                SocketGuildChannel   chnl    = message.Channel as SocketGuildChannel;

                if (chnl?.Guild == null)
                {
                    return;
                }
                var Guild = chnl.Guild;
                ModerationSettings modSettings = Guild.LoadFromFile <ModerationSettings>();
                SocketGuildUser    gUser       = message.Author as SocketGuildUser;
                List <BadWord>     badWords    = Guild.LoadFromFile <BadWordList>()?.badWords;

                if (modSettings != null)
                {
                    if (modSettings.channelsWithoutAutoMod != null && modSettings.channelsWithoutAutoMod.Contains(chnl.Id) || (message.Author as SocketGuildUser).CantBeWarned())
                    {
                        return; //Returns if channel is set as not using automod
                    }
                    //Checks if a message contains an invite
                    if (!modSettings.invitesAllowed && message.Content.ToLower().Contains("discord.gg/") || message.Content.ToLower().Contains("discordapp.com/invite/"))
                    {
                        await context.Punish("Posted Invite");

                        return;
                    }

                    //Checks for links
                    if ((modSettings.allowedLinks != null && modSettings.allowedLinks.Count > 0) && (modSettings.allowedToLink == null || !gUser.RoleIDs().Intersect(modSettings.allowedToLink).Any()))
                    {
                        const string    linkRegex = @"^((?:https?|steam):\/\/[^\s<]+[^<.,:;" + "\"\'\\]\\s])";
                        MatchCollection matches   = Regex.Matches(message.Content, linkRegex, RegexOptions.IgnoreCase);
                        //if (matches != null && matches.Count > 0) await new LogMessage(LogSeverity.Info, "Filter", "Link detected").Log();
                        foreach (Match match in matches)
                        {
                            if (!modSettings.allowedLinks.Any(s => match.ToString().ToLower().Contains(s.ToLower())))
                            {
                                await context.Punish("Using unauthorized links", 1);

                                return;
                            }
                        }
                    }

                    //Check for emojis
                    if (modSettings.badUEmojis.NotEmpty() && modSettings.badUEmojis.Any(s => message.Content.Contains(s)))
                    {
                        await context.Punish("Bad emoji used", 0.8f);

                        return;
                    }

                    if (modSettings.allowedCaps > 0 && message.Content.Length > 5)
                    {
                        uint amountCaps = 0;
                        foreach (char c in message.Content)
                        {
                            if (char.IsUpper(c))
                            {
                                amountCaps++;
                            }
                        }
                        if (((amountCaps / (float)message.Content.Length) * 100) >= modSettings.allowedCaps)
                        {
                            await context.Punish("Excessive caps", 0.3f);

                            return;
                        }
                    }
                } //End of stuff from mod settings

                //Checks for bad words
                if (badWords != null)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (char c in message.Content)
                    {
                        if (sb.ToString().Length + 1 == message.Content.Length)
                        {
                            sb.Append(c);
                            break;
                        }
                        switch (c)
                        {
                        case '1':
                        case '!':
                            sb.Append('i');
                            break;

                        case '0':
                            sb.Append('o');
                            break;

                        case '8':
                            sb.Append('b');
                            break;

                        case '3':
                            sb.Append('e');
                            break;

                        case '$':
                            sb.Append('s');
                            break;

                        case '@':
                        case '4':
                            sb.Append('a');
                            break;

                        default:
                            if (!char.IsPunctuation(c) && !char.IsSymbol(c))
                            {
                                sb.Append(c);
                            }
                            break;
                        }
                    }

                    string strippedMessage = sb.ToString().ToLower();

                    foreach (BadWord badWord in badWords)
                    {
                        if (badWord.partOfWord)
                        {
                            if (strippedMessage.Contains(badWord.word.ToLower()))
                            {
                                if (badWord.euphemism != null && badWord.euphemism != "")
                                {
                                    await context.Punish("Bad word used (" + badWord.euphemism + ")");
                                }
                                else
                                {
                                    await context.Punish("Bad word used");
                                }

                                return;
                            }
                        }
                        else
                        {
                            string[] messageParts = strippedMessage.Split(' ');
                            foreach (string word in messageParts)
                            {
                                if (word == badWord.word.ToLower())
                                {
                                    if (badWord.euphemism != null && badWord.euphemism != "")
                                    {
                                        await context.Punish("Bad word used (" + badWord.euphemism + ")", badWord.size);
                                    }
                                    else
                                    {
                                        await context.Punish("Bad word used", badWord.size);
                                    }
                                    return;
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                await new LogMessage(LogSeverity.Error, "Filter", "Something went wrong with the message filter", e).Log();
            }
        }
Beispiel #26
0
        public static async Task CheckTempActs(DiscordSocketClient client, bool debug = false, CancellationToken?ct = null)
        {
            RequestOptions requestOptions = RequestOptions.Default;

            requestOptions.RetryMode = RetryMode.AlwaysRetry;
            try
            {
                currentInfo.checkedGuilds = 0;
                foreach (SocketGuild sockGuild in client.Guilds)
                {
                    ct?.ThrowIfCancellationRequested();
                    currentInfo.checkedMutes = 0;
                    if (currentInfo.checkedGuilds > client.Guilds.Count)
                    {
                        await new LogMessage(LogSeverity.Error, "TempAct", $"Check went past all guilds (at #{currentInfo.checkedGuilds}) but has been stopped. This doesn't seem physically possible.").Log();
                        return;
                    }
                    RestGuild restGuild = await client.Rest.SuperGetRestGuild(sockGuild.Id);

                    if (debug)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.Write($"\nChecking {sockGuild.Name} discord ");
                    }
                    TempActionList actions  = sockGuild.LoadFromFile <TempActionList>(false);
                    bool           needSave = false;
                    currentInfo.checkedGuilds++;
                    if (actions != null)
                    {
                        if (actions.tempBans?.Count is not null or 0)
                        {
                            currentInfo.editedBans = new List <TempAct>(actions.tempBans);
                            foreach (TempAct tempBan in actions.tempBans)
                            {
                                try
                                {
                                    RestBan ban = await sockGuild.GetBanAsync(tempBan.User, requestOptions);

                                    if (ban == null)
                                    { //If manual unban
                                        var user = await client.Rest.GetUserAsync(tempBan.User);

                                        currentInfo.editedBans.Remove(tempBan);
                                        user?.TryNotify($"As you might know, you have been manually unbanned in {sockGuild.Name} discord");
                                        //_ = new LogMessage(LogSeverity.Warning, "TempAction", "Tempbanned person isn't banned").Log();
                                        if (user == null)
                                        {
                                            DiscordLogging.LogManualEndTempAct(sockGuild, tempBan.User, "bann", tempBan.DateBanned);
                                        }
                                        else
                                        {
                                            DiscordLogging.LogManualEndTempAct(sockGuild, user, "bann", tempBan.DateBanned);
                                        }
                                    }
                                    else if (DateTime.UtcNow >= tempBan.DateBanned.Add(tempBan.Length))
                                    {
                                        RestUser rUser = ban.User;
                                        await sockGuild.RemoveBanAsync(tempBan.User, requestOptions);

                                        currentInfo.editedBans.Remove(tempBan);
                                        DiscordLogging.LogEndTempAct(sockGuild, rUser, "bann", tempBan.Reason, tempBan.Length);
                                    }
                                }
                                catch (Exception e)
                                {
                                    await new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unbanning someone, continuing", e).Log();
                                }
                            }

                            //if all tempbans DON'T equal all edited tempbans (basically if there was a change
                            if (currentInfo.editedBans.Count != actions.tempBans.Count)
                            {
                                if (debug)
                                {
                                    Console.Write($"{actions.tempBans.Count - currentInfo.editedBans.Count} tempbans are over, ");
                                }
                                needSave         = true;
                                actions.tempBans = currentInfo.editedBans;
                            }
                            else if (debug)
                            {
                                Console.Write($"tempbans checked, none over, ");
                            }
                        }
                        else if (debug)
                        {
                            Console.Write($"no tempbans, ");
                        }
                        ModerationSettings settings = sockGuild.LoadFromFile <ModerationSettings>();
                        if (settings is not null && sockGuild.GetRole(settings.mutedRole) != null && actions.tempMutes?.Count is not null or 0)
                        {
                            var            mutedRole   = sockGuild.GetRole(settings.mutedRole);
                            List <TempAct> editedMutes = new List <TempAct>(actions.tempMutes);
                            foreach (TempAct tempMute in actions.tempMutes)
                            {
                                currentInfo.checkedMutes++;
                                try
                                {
                                    IGuildUser gUser = sockGuild.GetUser(tempMute.User) ?? await restGuild.SuperGetUser(tempMute.User);

                                    if (gUser != null && !gUser.RoleIds.Contains(settings.mutedRole))
                                    { //User missing muted role, must have been manually unmuted
                                        _ = gUser.TryNotify($"As you might know, you have been manually unmuted in {sockGuild.Name} discord");
                                        editedMutes.Remove(tempMute);
                                        DiscordLogging.LogManualEndTempAct(sockGuild, gUser, "mut", tempMute.DateBanned);
                                        _ = (!editedMutes.Contains(tempMute)).AssertAsync("Tempmute not removed?!");
                                    }
                                    else if (DateTime.UtcNow >= tempMute.DateBanned.Add(tempMute.Length))
                                    { //Normal mute end
                                        if (gUser != null)
                                        {
                                            await gUser.RemoveRoleAsync(mutedRole, requestOptions);
                                        } // if user not in guild || if user doesn't contain muted role (successfully removed?
                                        if (gUser == null || !gUser.RoleIds.Contains(settings.mutedRole))
                                        { //Doesn't remove tempmute if unmuting fails
                                            IUser user = gUser; //Gets user to try to message
                                            user ??= await client.SuperGetUser(tempMute.User);

                                            if (user != null)
                                            { // if possible to message, message and log
                                                DiscordLogging.LogEndTempAct(sockGuild, user, "mut", tempMute.Reason, tempMute.Length);
                                                _ = user.Notify("auto untempmuted", tempMute.Reason, sockGuild, client.CurrentUser);
                                            }
                                            editedMutes.Remove(tempMute);
                                        }
                                        else if (gUser != null)
                                        {
                                            await new LogMessage(LogSeverity.Warning, "TempAct", "User should've had role removed").Log();
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    await new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unmuting someone, continuing", e).Log();
                                }
                            }

                            //NOTE: Assertions fail if NOT true
                            _ = (currentInfo.checkedMutes == actions.tempMutes.Count).AssertAsync($"Checked incorrect number tempmutes ({currentInfo.checkedMutes}/{actions.tempMutes.Count}) in guild {sockGuild} owned by {sockGuild.Owner}");

                            if (editedMutes.Count != actions.tempMutes.Count)
                            {
                                if (debug)
                                {
                                    Console.Write($"{actions.tempMutes.Count - editedMutes.Count}/{actions.tempMutes.Count} tempmutes are over");
                                }
                                actions.tempMutes = editedMutes;
                                needSave          = true;
                            }
                            else if (debug)
                            {
                                Console.Write($"none of {actions.tempMutes.Count} tempmutes over");
                            }
                        }
                        else if (debug)
                        {
                            Console.Write("no tempmutes to check or no settings");
                        }
                        if (needSave)
                        {
                            actions.SaveToFile();
                        }
                    }
Beispiel #27
0
 public static void Append(this ServerMessage message, ModerationSettings modSettings)
 {
     message.AppendInteger(modSettings.WhoCanMute.Value);
     message.AppendInteger(modSettings.WhoCanKick.Value);
     message.AppendInteger(modSettings.WhoCanBan.Value);
 }
Beispiel #28
0
        public async Task ListAutoMod(string extension = "", [Remainder] string whoCaresWhatGoesHere = null)
        {
            try {
                ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>();
                BadWords           badWords = new BadWords(Context.Guild);

                var embed = new EmbedBuilder();
                embed.Author = new EmbedAuthorBuilder().WithName("Automod information for " + Context.Guild.Name + " discord");
                string message = "";

                bool useExplicit = false;
                if (extension != null && extension.ToLower() == "explicit" || extension.ToLower() == "e")
                {
                    if ((Context.Message.Author as SocketGuildUser).CanWarn())
                    {
                        useExplicit = true;
                    }
                    else
                    {
                        await ReplyAsync("You lack the permissions for viewing explicit bad words");

                        return;
                    }
                }

                if (settings == null)
                {
                    embed.AddField("Moderation settings", "Are null", true);
                }
                else
                {
                    embed.AddField("Warn for posting invite", !settings.invitesAllowed, true);
                    if (settings.allowedLinks == null || settings.allowedLinks.Count == 0)
                    {
                        embed.AddField("Allowed links", "Links aren't moderated  ", true);
                    }
                    else
                    {
                        message = settings.allowedLinks.ListItems("\n");
                        if (message.NotEmpty())
                        {
                            embed.AddField("Allowed links", message, true);
                        }
                        if (settings.allowedToLink != null && settings.allowedToLink.Count > 0)
                        {
                            message = Context.Guild.Roles.Where(
                                role => (role.Permissions.Administrator && !role.IsManaged) || settings.allowedToLink.Contains(role.Id)).Select(role => role.Name).ToArray().ListItems("\n");
                            if (message.NotEmpty())
                            {
                                embed.AddField("Roles that can post links", message, true);
                            }
                        }
                    }
                    if (settings.allowedCaps > 0)
                    {
                        embed.AddField("Allowed caps", $"{settings.allowedCaps}% in msgs more than 5 long");
                    }
                    else
                    {
                        embed.AddField("Allowed caps", "Capitalization is not filtered");
                    }
                    string badUniEmojis = settings.badUEmojis?.ListItems("");
                    if (!badUniEmojis.IsNullOrEmpty())
                    {
                        embed.AddField("Banned Emojis", badUniEmojis, true);
                    }
                }
                if (badWords != null && badWords.all != null && badWords.all.Count > 0)
                {
                    List <string> words = new List <string>();
                    foreach (List <BadWord> group in badWords.grouped)
                    {
                        BadWord first = group.FirstOrDefault();
                        if (first != null)
                        {
                            string word = "";
                            if (useExplicit)
                            {
                                if (group.Count == 1 || group.All(badWord => badWord.size == first.size))
                                {
                                    word = $"[{first.size}x] ";
                                }
                                else
                                {
                                    var sizes = group.Select(badword => badword.size);
                                    word = $"[{sizes.Min()}-{sizes.Max()}x] ";
                                }
                                if (first.euphemism.NotEmpty())
                                {
                                    word += $"{first.euphemism} ";
                                }
                                word += $"({group.Select(badWord => badWord.word).ToArray().ListItems(", ")})";
                            }
                            else if (!first.euphemism.IsNullOrEmpty())
                            {
                                word = first.euphemism;
                            }
                            if (first.partOfWord && (!first.euphemism.IsNullOrEmpty() || useExplicit))
                            {
                                word += "⌝";
                            }
                            words.Add(word);
                        }
                        else
                        {
                            _ = new LogMessage(LogSeverity.Error, "Filter", "Empty badword list in badwords").Log();
                        }
                    }

                    /*foreach (BadWord badWord in badWords.all) { Old code
                     *  string word = "";
                     *  if (useExplicit) {
                     *      word = $"[{badWord.size}x] " ;
                     *      if (badWord.euphemism.NotEmpty()) word += $"{badWord.euphemism} ";
                     *      word += $"({badWord.word})";
                     *  }
                     *  else if (!badWord.euphemism.IsNullOrEmpty()) word = badWord.euphemism;
                     *  if (badWord.partOfWord && (useExplicit || !badWord.euphemism.IsNullOrEmpty())) {
                     *      word += "⌝";
                     *  }
                     *  words.Add(word);
                     * }*/
                    message = words.ListItems("\n");
                    embed.AddField("Badword euphemisms (not an exhaustive list)", message, false);
                }
                IDMChannel channel = Context.Message.Author.GetOrCreateDMChannelAsync().Result;
                if (channel != null)
                {
                    _ = channel.SendMessageAsync("The symbol '⌝' next to a word means that you can be warned for a word that contains the bad word", embed: embed.Build());
                }
                else
                {
                    _ = ReplyAsync(Context.Message.Author.Mention + " we can't send a message to your DMs");
                }
            } catch (Exception e) {
                _ = new LogMessage(LogSeverity.Error, "Settings", "Error", e).Log();
            }
        }
Beispiel #29
0
        public static async Task TempActChecker(DiscordSocketClient client, bool debug = false)
        {
            try {
                int checkedGuilds = 0;
                foreach (SocketGuild guild in client.Guilds)
                {
                    if (debug)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.Write($"\nChecking {guild.Name} discord ");
                    }
                    TempActionList actions  = guild.LoadFromFile <TempActionList>(false);
                    bool           needSave = false;
                    checkedGuilds++;
                    if (actions != null)
                    {
                        if (!actions.tempBans.IsNullOrEmpty())
                        {
                            List <TempAct> editedBans = new List <TempAct>(actions.tempBans);
                            foreach (TempAct tempBan in actions.tempBans)
                            {
                                try {
                                    if (!guild.GetBansAsync().Result.Any(ban => ban.User.Id == tempBan.user))   //Need to add an embed for when this happens that's distinct
                                    {
                                        _ = client.GetUser(tempBan.user)?.TryNotify($"As you might know, you have been manually unbanned in {guild.Name} discord");
                                        //_ = new LogMessage(LogSeverity.Warning, "TempAction", "Tempbanned person isn't banned").Log();
                                        editedBans.Remove(tempBan);
                                    }
                                    else if (DateTime.Now >= tempBan.dateBanned.Add(tempBan.length))
                                    {
                                        RestUser rUser = guild.GetBansAsync().Result.First(ban => ban.User.Id == tempBan.user).User;
                                        await guild.RemoveBanAsync(tempBan.user);

                                        editedBans.Remove(tempBan);
                                        Logging.LogEndTempAct(guild, rUser, "bann", tempBan.reason, tempBan.length);
                                    }
                                } catch (Exception e) {
                                    _ = new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unbanning someone, continuing", e).Log();
                                }
                            }

                            if (editedBans != actions.tempBans)
                            {
                                if (debug)
                                {
                                    Console.Write($"{actions.tempBans.Count - editedBans.Count} tempbans are over, ");
                                }
                                needSave         = true;
                                actions.tempBans = editedBans;
                            }
                            else if (debug)
                            {
                                Console.Write($"tempbans checked, none over, ");
                            }
                        }
                        else if (debug)
                        {
                            Console.Write($"no tempbans, ");
                        }

                        ModerationSettings settings = guild.LoadFromFile <ModerationSettings>();
                        if (settings != null && guild.GetRole(settings.mutedRole) != null && !actions.tempMutes.IsNullOrEmpty())
                        {
                            List <TempAct> editedMutes  = new List <TempAct>(actions.tempMutes);
                            uint           checkedMutes = 0;
                            foreach (TempAct tempMute in actions.tempMutes)
                            {
                                checkedMutes++;
                                try {
                                    SocketUser user = guild.GetUser(tempMute.user);
                                    if (user != null && !(user as IGuildUser).RoleIds.Contains(settings.mutedRole))
                                    {
                                        _ = user.TryNotify($"As you might know, you have been manually unmuted in {guild.Name} discord");
                                        editedMutes.Remove(tempMute);
                                    }
                                    else if (DateTime.Now >= tempMute.dateBanned.Add(tempMute.length))
                                    {
                                        if (user != null)
                                        {
                                            await guild.GetUser(tempMute.user).RemoveRoleAsync(guild.GetRole(settings.mutedRole));
                                        }
                                        if (!(user as IGuildUser)?.RoleIds?.NotEmpty() ?? true || !(user as IGuildUser).RoleIds.Contains(settings.mutedRole))   //Doesn't remove tempmute if unmuting fails
                                        {
                                            user ??= client.GetUser(tempMute.user);
                                            if (user != null)
                                            {
                                                Logging.LogEndTempAct(guild, user, "mut", tempMute.reason, tempMute.length);
                                                _ = user.Notify($"untemp-muted", tempMute.reason, guild);
                                            }
                                            editedMutes.Remove(tempMute);
                                        }
                                    }
                                } catch (Exception e) {
                                    _ = new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unmuting someone, continuing", e).Log();
                                }
                            }

                            _ = (checkedMutes == actions.tempMutes.Count || checkedMutes == uint.MaxValue).AssertAsync("Didn't check all tempmutes");

                            if (editedMutes != actions.tempMutes)
                            {
                                if (debug)
                                {
                                    Console.Write($"{actions.tempMutes.Count - editedMutes.Count}/{actions.tempMutes.Count} tempmutes are over");
                                }
                                actions.tempMutes = editedMutes;
                                needSave          = true;
                            }
                            else if (debug)
                            {
                                Console.Write($"no tempmute changes");
                            }
                        }
                        else if (debug)
                        {
                            Console.Write("no tempmutes to check or no settings");
                        }
                        if (needSave)
                        {
                            actions.SaveToFile(guild);
                        }
                    }
                }
                if (debug)
                {
                    Console.Write("\n");
                }
                _ = (checkedGuilds > 0).AssertWarnAsync("Checked 0 guilds for tempbans?");
            } catch (Exception e) {
                _ = new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unbanning someone", e).Log();
            }
        }