Ejemplo n.º 1
0
        private async void OnJoin(JoinEventArgs e)
        {
            if (e.Handled)
            {
                return;
            }

            TSPlayer player = TShock.Players[e.Who];

            if (player == null)
            {
                return;
            }

            DateTime muteExpiration = await Mutes.GetExpirationAsync(player);

            if (DateTime.UtcNow < muteExpiration)
            {
                player.mute = true;
                try
                {
                    await Task.Delay(muteExpiration - DateTime.UtcNow, player.GetPlayerInfo().MuteToken);

                    player.mute = false;
                    player.SendInfoMessage("You have been unmuted.");
                }
                catch (TaskCanceledException)
                {
                }
            }
        }
Ejemplo n.º 2
0
            private void RemoveMute(MuteInfo info)
            {
                if (info == null)
                {
                    return;
                }

                Mutes.Remove(info.PlayerId);
            }
Ejemplo n.º 3
0
        public async Task StartAsync()
        {
            _running = true;
            while (_running)
            {
                await Task.Delay(3000);

                var mutesToRemove = new List <Mute>();
                foreach (var m in Mutes.Where(x => DateTime.Compare(DateTime.UtcNow, x.UnmuteAt) > 0 && x.Active))
                {
                    var guild = _client.GetGuild(m.GuildId);
                    var user  = guild.GetUser(m.SubjectId);

                    var role = guild.GetRole(_config.MuteRoleId);
                    if (user == null || role == null)
                    {
                        return;
                    }
                    await user.RemoveRolesAsync(new SocketRole[] { role });

                    var name = user.Nickname == null
                        ? user.Username
                        : $"{user.Username} (nickname: {user.Nickname})";
                    await _log.LogModMessageAsync($":alarm_clock: **{name}#{user.Discriminator} ({m.SubjectId})**'s mute from {m.Timestamp} has expired.");

                    await _records.DeactivateMuteAsync(m.Key);

                    var dmChannel = await user.GetOrCreateDMChannelAsync();

                    await dmChannel.SendMessageAsync($"Your mute in {user.Guild.Name} has expired.");

                    mutesToRemove.Add(m);
                }
                foreach (var m in mutesToRemove)
                {
                    Mutes.Remove(m);
                }

                var bansToRemove = new List <TempBan>();
                foreach (var b in Bans.Where(x => DateTime.Compare(DateTime.UtcNow, x.UnbanAt) > 0 && x.Active))
                {
                    var guild = _client.GetGuild(b.GuildId);
                    await guild.RemoveBanAsync(b.SubjectId);

                    await _log.LogModMessageAsync($":alarm_clock: **{b.SubjectName}#{b.SubjectId} ({b.SubjectId})**'s ban from {b.Timestamp} has expired.");

                    await _records.DeactivateBanAsync(b.Key);

                    bansToRemove.Add(b);
                }
                foreach (var b in bansToRemove)
                {
                    Bans.Remove(b);
                }
            }
        }
Ejemplo n.º 4
0
            MuteInfo GetMute(string steamid)
            {
                MuteInfo info;

                if (Mutes.TryGetValue(steamid, out info))
                {
                    return(info);
                }
                else
                {
                    return(null);
                }
            }
Ejemplo n.º 5
0
        private void ListMutes(IPlayer player, string command, string[] args)
        {
            var CommandInfo = $"{command} {args[0].ToLower()}";

            // /voice list

            if (!CanList(player) && !player.IsServer)
            {
                SendChatMessage(player, Lang("No Permission", player.Id, CommandInfo));
                return;
            }

            if (Mutes.Count == 0)
            {
                SendChatMessage(player, Lang("No Mutes", player.Id));
                return;
            }

            var mutes = string.Join(Environment.NewLine, Mutes.Select(kvp => $"- [#add8e6]{Mutes[kvp.Key].PlayerName}[/#]: {FormatTime(kvp.Value.ExpireDate - DateTime.UtcNow)}").ToArray());

            SendInfoMessage(player, Lang("Prefix List", player.Id), mutes);
        }
Ejemplo n.º 6
0
            public MuteInfo AddMute(IPlayer target, string adminName, DateTime expireDate, string reason = null, bool addReason = false)
            {
                MuteInfo info;

                if (Mutes.ContainsKey(target.Id))
                {
                    MuteInfo m = GetMute(target);

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

                    m.ExpireDate = expireDate;
                    m.Reason     = (addReason ? $"{m.Reason} | {reason}" : reason);

                    return(null);
                }

                info = new MuteInfo(target, adminName, expireDate, reason);
                Mutes.Add(target.Id, info);

                return(info);
            }
Ejemplo n.º 7
0
        public override Task DivideLine(string line)
        {
            if (line.Contains(" CITC "))
            {
                CitC.Add(line);
            }

            else if (line.Contains(" LOGIN: "******" LOGIN MISC: "))
            {
                LoginMisc.Add(line);
            }
            else if (line.Contains(" QUIT MISC: "))
            {
                QuitMisc.Add(line);
            }

            else if (line.Contains(" (AA)(BAN) "))
            {
                Bans.Add(line);
            }
            else if (line.Contains(" (AA)(MUTE) "))
            {
                Mutes.Add(line);
            }
            else if (line.Contains(" (AA)(JAIL) "))
            {
                Jails.Add(line);
            }
            else if (line.Contains(" (AA)(CONTACTADMIN) "))
            {
                Cad.Add(line);
            }
            else if (line.Contains(" (AA)(SUPPORT) "))
            {
                Support.Add(line);
            }

            else if (line.Contains(" opened '") && line.Contains(" ms"))
            {
                LogsFetched.Add(line);
            }
            else if (line.Contains(" [CM] ") && line.Contains(" set "))
            {
                Reports.Add(line);
            }
            else if (line.Contains("[Complaint ID") && line.Contains(" replied with "))
            {
                Reports.Add(line);
            }
            else if (line.Contains(" warped to ") || line.Contains(" WL: "))
            {
                if (line.Contains("WL: 0") || line.Contains("with 0 stars Dim: 0"))
                {
                    PossibleAbuse.Add(line);
                }
                else
                {
                    RegisteredAbuse.Add(line);
                }
            }

            /*else if (line.Contains(" warped to ") && !line.Contains(" WL: 0") && !line.Contains(" (EM) "))
             *  RegisteredAbuse.Add(line);
             * else if (line.Contains(" warped to ") && line.Contains(" WL: 0") && !line.Contains(" (EM) "))
             *  PossibleAbuse.Add(line);
             * else if (line.Contains(" ST ") && (!line.Contains("from 0") && line.Contains("wanted points.")))
             *  RegisteredAbuse.Add(line);*/
            else if (line.Contains(" ST ") && line.Contains("from 0 wanted points."))
            {
                PossibleAbuse.Add(line);
            }
            else if (line.Contains("abuse") ||
                     line.Contains("recommendation") ||
                     line.Contains("leak") ||
                     line.Contains("bias") ||
                     line.Contains("accept") ||
                     line.Contains("jcm") ||
                     line.Contains("rcm") ||
                     line.Contains("scm")
                     )
            {
                PossibleAbuse.Add(line);
            }

            else if (line.Contains("object. ID:"))
            {
                DutyRelated.Add(line);
            }
            else if (line.Contains("changed account:"))
            {
                DutyRelated.Add(line);
            }
            else if (line.Contains("changed the password of account"))
            {
                DutyRelated.Add(line);
            }
            else if (line.Contains("checked the PIN code of account"))
            {
                DutyRelated.Add(line);
            }
            else if (line.Contains("zone 0 p"))
            {
                DutyRelated.Add(line);
            }

            else if (line.Contains(" (PP) "))
            {
                PendingPunishments.Add(line);
            }
            else
            {
                Other.Add(line);
            }
            return(Task.CompletedTask);
        }
Ejemplo n.º 8
0
 public Mutes.Users_List.Result[] Users_List(Mutes.Users_List.Command command)
 {
     return _ApiEndpoints._Client.GetResult<Mutes.Users_List.Command, Mutes.Users_List.Result[]>(command);
 }
Ejemplo n.º 9
0
 public Mutes.Users_Destroy.Result[] Users_Destroy(Mutes.Users_Destroy.Command command)
 {
     return _ApiEndpoints._Client.GetResult<Mutes.Users_Destroy.Command, Mutes.Users_Destroy.Result[]>(command);
 }
Ejemplo n.º 10
0
        static async Task MainAsync(string[] _)
        {
            var json = "";

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync();

            cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);

            var keys = cfgjson.WordListList.Keys;

            foreach (string key in keys)
            {
                var listOutput = File.ReadAllLines($"Lists/{key}");
                cfgjson.WordListList[key].Words = listOutput;
            }

            string redisHost;

            if (Environment.GetEnvironmentVariable("REDIS_DOCKER_OVERRIDE") != null)
            {
                redisHost = "redis";
            }
            else
            {
                redisHost = cfgjson.Redis.Host;
            }
            redis = ConnectionMultiplexer.Connect($"{redisHost}:{cfgjson.Redis.Port}");
            db    = redis.GetDatabase();
            db.KeyDelete("messages");

            discord = new DiscordClient(new DiscordConfiguration
            {
                Token           = cfgjson.Core.Token,
                TokenType       = TokenType.Bot,
                MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Debug,
                Intents         = DiscordIntents.All
            });

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            async Task OnReady(DiscordClient client, ReadyEventArgs e)
            {
                Console.WriteLine($"Logged in as {client.CurrentUser.Username}#{client.CurrentUser.Discriminator}");
                logChannel = await discord.GetChannelAsync(cfgjson.LogChannel);

                Mutes.CheckMutesAsync();
                ModCmds.CheckBansAsync();
            }

            async Task MessageCreated(DiscordClient client, MessageCreateEventArgs e)
            {
                if (e.Channel.IsPrivate || e.Guild.Id != cfgjson.ServerID || e.Author.IsBot)
                {
                    return;
                }

                if (processedMessages.Contains(e.Message.Id))
                {
                    return;
                }
                else
                {
                    processedMessages.Add(e.Message.Id);
                }

                DiscordMember member = await e.Guild.GetMemberAsync(e.Author.Id);

                if (Warnings.GetPermLevel(member) >= ServerPermLevel.TrialMod)
                {
                    return;
                }


                bool match = false;

                // Matching word list
                var wordListKeys = cfgjson.WordListList.Keys;

                foreach (string key in wordListKeys)
                {
                    if (CheckForNaughtyWords(e.Message.Content, cfgjson.WordListList[key]))
                    {
                        try
                        {
                            e.Message.DeleteAsync();
                            DiscordChannel logChannel = await discord.GetChannelAsync(Program.cfgjson.LogChannel);

                            var embed = new DiscordEmbedBuilder()
                                        .WithDescription(e.Message.Content)
                                        .WithColor(new DiscordColor(0xf03916))
                                        .WithTimestamp(e.Message.Timestamp)
                                        .WithFooter(
                                $"User ID: {e.Author.Id}",
                                null
                                )
                                        .WithAuthor(
                                $"{e.Author.Username}#{e.Author.Discriminator} in #{e.Channel.Name}",
                                null,
                                e.Author.AvatarUrl
                                );
                            logChannel.SendMessageAsync($"{cfgjson.Emoji.Denied} Deleted infringing message by {e.Author.Mention} in {e.Channel.Mention}:", false, embed);
                        }
                        catch
                        {
                            // still warn anyway
                        }

                        match = true;
                        string         reason = cfgjson.WordListList[key].Reason;
                        DiscordMessage msg    = await e.Channel.SendMessageAsync($"{cfgjson.Emoji.Denied} {e.Message.Author.Mention} was warned: **{reason.Replace("`", "\\`").Replace("*", "\\*")}**");

                        Warnings.GiveWarningAsync(e.Message.Author, discord.CurrentUser, reason, contextLink: Warnings.MessageLink(msg), e.Channel);
                        return;
                    }
                    if (match)
                    {
                        return;
                    }
                }

                if (match)
                {
                    return;
                }

                // Mass emoji
                if (e.Message.MentionedUsers.Count >= cfgjson.MassMentionThreshold)
                {
                    DiscordChannel logChannel = await discord.GetChannelAsync(Program.cfgjson.LogChannel);

                    try
                    {
                        e.Message.DeleteAsync();
                        var embed = new DiscordEmbedBuilder()
                                    .WithDescription(e.Message.Content)
                                    .WithColor(new DiscordColor(0xf03916))
                                    .WithTimestamp(e.Message.Timestamp)
                                    .WithFooter(
                            $"User ID: {e.Author.Id}",
                            null
                            )
                                    .WithAuthor(
                            $"{e.Author.Username}#{e.Author.Discriminator} in #{e.Channel.Name}",
                            null,
                            e.Author.AvatarUrl
                            );
                        logChannel.SendMessageAsync($"{cfgjson.Emoji.Denied} Deleted infringing message by {e.Author.Mention} in {e.Channel.Mention}:", false, embed);
                    }
                    catch
                    {
                        // still warn anyway
                    }

                    string         reason = "Mass mentions";
                    DiscordMessage msg    = await e.Channel.SendMessageAsync($"{cfgjson.Emoji.Denied} {e.Message.Author.Mention} was warned: **{reason.Replace("`", "\\`").Replace("*", "\\*")}**");

                    await Warnings.GiveWarningAsync(e.Message.Author, discord.CurrentUser, reason, contextLink : Warnings.MessageLink(msg), e.Channel);

                    return;
                }

                // Unapproved invites
                if (Warnings.GetPermLevel(member) < (ServerPermLevel)cfgjson.InviteTierRequirement)
                {
                    string inviteExclusion = "microsoft";
                    if (cfgjson.InviteExclusion != null)
                    {
                        inviteExclusion = cfgjson.InviteExclusion;
                    }

                    string checkedMessage = e.Message.Content.Replace($"discord.gg/{inviteExclusion}", "").Replace($"discord.com/invite/{inviteExclusion}", "");

                    if (checkedMessage.Contains("discord.gg/") || checkedMessage.Contains("discord.com/invite/"))
                    {
                        try
                        {
                            e.Message.DeleteAsync();
                            var embed = new DiscordEmbedBuilder()
                                        .WithDescription(e.Message.Content)
                                        .WithColor(new DiscordColor(0xf03916))
                                        .WithTimestamp(e.Message.Timestamp)
                                        .WithFooter(
                                $"User ID: {e.Author.Id}",
                                null
                                )
                                        .WithAuthor(
                                $"{e.Author.Username}#{e.Author.Discriminator} in #{e.Channel.Name}",
                                null,
                                e.Author.AvatarUrl
                                );
                            logChannel.SendMessageAsync($"{cfgjson.Emoji.Denied} Deleted infringing message by {e.Author.Mention} in {e.Channel.Mention}:", false, embed);
                        }
                        catch
                        {
                            // still warn anyway
                        }
                        string         reason = "Sent an invite";
                        DiscordMessage msg    = await e.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Denied} {e.Message.Author.Mention} was warned: **{reason.Replace("`", "\\`").Replace("*", "\\*")}**");

                        await Warnings.GiveWarningAsync(e.Message.Author, discord.CurrentUser, reason, contextLink : Warnings.MessageLink(msg), e.Channel);

                        return;
                    }
                }

                // Mass emoji
                if (!cfgjson.UnrestrictedEmojiChannels.Contains(e.Message.ChannelId) && e.Message.Content.Length >= cfgjson.MassEmojiThreshold)
                {
                    char[] tempArray = e.Message.Content.Replace("🏻", "").Replace("🏼", "").Replace("🏽", "").Replace("🏾", "").Replace("🏿", "").ToCharArray();
                    int    pos       = 0;
                    foreach (char c in tempArray)
                    {
                        if (c == '™' || c == '®' || c == '©')
                        {
                            tempArray[pos] = ' ';
                        }
                        if (c == '\u200d')
                        {
                            tempArray[pos]     = ' ';
                            tempArray[pos + 1] = ' ';
                        }
                        ++pos;
                    }
                    string input = new string(tempArray);

                    var matches = emoji_rx.Matches(input);
                    if (matches.Count > cfgjson.MassEmojiThreshold)
                    {
                        e.Message.DeleteAsync();
                        string         reason = "Mass emoji";
                        DiscordMessage msg    = await e.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Denied} {e.Message.Author.Mention} was warned: **{reason.Replace("`", "\\`").Replace("*", "\\*")}**");

                        await Warnings.GiveWarningAsync(e.Message.Author, discord.CurrentUser, reason, contextLink : Warnings.MessageLink(msg), e.Channel);

                        return;
                    }
                }
            }

            async Task GuildMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
            {
                if (e.Guild.Id != cfgjson.ServerID)
                {
                    return;
                }

                if (await db.HashExistsAsync("mutes", e.Member.Id))
                {
                    // todo: store per-guild
                    DiscordRole mutedRole = e.Guild.GetRole(cfgjson.MutedRole);
                    await e.Member.GrantRoleAsync(mutedRole);
                }
            }

            discord.Ready            += OnReady;
            discord.MessageCreated   += MessageCreated;
            discord.GuildMemberAdded += GuildMemberAdded;


            commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefixes = cfgjson.Core.Prefixes
            });;

            commands.RegisterCommands <Warnings>();
            commands.RegisterCommands <MuteCmds>();
            commands.RegisterCommands <UserRoleCmds>();
            commands.RegisterCommands <ModCmds>();

            await discord.ConnectAsync();

            while (true)
            {
                await Task.Delay(60000);

                Mutes.CheckMutesAsync();
                ModCmds.CheckBansAsync();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
        }
Ejemplo n.º 11
0
 public void Add(Mute item) => Mutes.Add(item);
Ejemplo n.º 12
0
        static async Task MainAsync(string[] _)
        {
            string token;
            var    json = "";

            string configFile = "config.json";

#if DEBUG
            configFile = "config.dev.json";
#endif

            using (var fs = File.OpenRead(configFile))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync();

            cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);

            var keys = cfgjson.WordListList.Keys;
            foreach (string key in keys)
            {
                var listOutput = File.ReadAllLines($"Lists/{key}");
                cfgjson.WordListList[key].Words = listOutput;
            }

            if (Environment.GetEnvironmentVariable("FORTEBASS_TOKEN") != null)
            {
                token = Environment.GetEnvironmentVariable("FORTEBASS_TOKEN");
            }
            else
            {
                token = cfgjson.Core.Token;
            }

            string redisHost;
            if (Environment.GetEnvironmentVariable("REDIS_DOCKER_OVERRIDE") != null)
            {
                redisHost = "redis";
            }
            else
            {
                redisHost = cfgjson.Redis.Host;
            }
            redis = ConnectionMultiplexer.Connect($"{redisHost}:{cfgjson.Redis.Port}");
            db    = redis.GetDatabase();
            db.KeyDelete("messages");

            discord = new DiscordClient(new DiscordConfiguration
            {
                Token           = token,
                TokenType       = TokenType.Bot,
                MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Debug,
                Intents         = DiscordIntents.All
            });


#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            async Task OnReady(DiscordClient client, ReadyEventArgs e)
            {
                Console.WriteLine($"Logged in as {client.CurrentUser.Username}#{client.CurrentUser.Discriminator}");
                logChannel = await discord.GetChannelAsync(cfgjson.LogChannel);

                Mutes.CheckMutesAsync();
                ModCmds.CheckBansAsync();
                ModCmds.CheckRemindersAsync();

                string commitHash    = "aaaaaaa";
                string commitMessage = "N/A";
                string commitTime    = "0000-00-00 00:00:00 +0000";

                if (File.Exists("CommitHash.txt"))
                {
                    using var sr = new StreamReader("CommitHash.txt");
                    commitHash   = sr.ReadToEnd();
                }

                if (File.Exists("CommitMessage.txt"))
                {
                    using var sr  = new StreamReader("CommitMessage.txt");
                    commitMessage = sr.ReadToEnd();
                }

                if (File.Exists("CommitTime.txt"))
                {
                    using var sr = new StreamReader("CommitTime.txt");
                    commitTime   = sr.ReadToEnd();
                }

                var FortebassChannel = await client.GetChannelAsync(cfgjson.HomeChannel);

                FortebassChannel.SendMessageAsync($"{cfgjson.Emoji.Connected} Fortebass connected successfully!\n\n" +
                                                  $"**Version**: `{commitHash}`\n" +
                                                  $"**Version timestamp**: `{commitTime}`\n**Framework**: `{RuntimeInformation.FrameworkDescription}`\n**Platform**: `{RuntimeInformation.OSDescription}`\n\n" +
                                                  $"Most recent commit message:\n" +
                                                  $"```\n" +
                                                  $"{commitMessage}\n" +
                                                  $"```");
            }

            async Task MessageCreated(DiscordClient client, MessageCreateEventArgs e)
            {
                if (e.Channel.IsPrivate || e.Guild.Id != cfgjson.ServerID || e.Author.IsBot)
                {
                    return;
                }

                if (processedMessages.Contains(e.Message.Id))
                {
                    return;
                }
                else
                {
                    processedMessages.Add(e.Message.Id);
                }

                DiscordMember member = await e.Guild.GetMemberAsync(e.Author.Id);

                if (Warnings.GetPermLevel(member) >= ServerPermLevel.CommunityManager)
                {
                    return;
                }


                bool match = false;

                // Matching word list
                var wordListKeys = cfgjson.WordListList.Keys;

                foreach (string key in wordListKeys)
                {
                    if (CheckForNaughtyWords(e.Message.Content.ToLower(), cfgjson.WordListList[key]))
                    {
                        try
                        {
                            e.Message.DeleteAsync();
                            DiscordChannel logChannel = await discord.GetChannelAsync(Program.cfgjson.LogChannel);

                            var embed = new DiscordEmbedBuilder()
                                        .WithDescription(e.Message.Content)
                                        .WithColor(new DiscordColor(0xf03916))
                                        .WithTimestamp(e.Message.Timestamp)
                                        .WithFooter(
                                $"User ID: {e.Author.Id}",
                                null
                                )
                                        .WithAuthor(
                                $"{e.Author.Username}#{e.Author.Discriminator} in #{e.Channel.Name}",
                                null,
                                e.Author.AvatarUrl
                                );
                            logChannel.SendMessageAsync($"{cfgjson.Emoji.Denied} Deleted infringing message by {e.Author.Mention} in {e.Channel.Mention}:", embed);
                        }
                        catch
                        {
                            // still warn anyway
                        }

                        match = true;
                        string         reason = cfgjson.WordListList[key].Reason;
                        DiscordMessage msg    = await e.Channel.SendMessageAsync($"{cfgjson.Emoji.Denied} {e.Message.Author.Mention} was automatically warned: **{reason.Replace("`", "\\`").Replace("*", "\\*")}**");

                        Warnings.GiveWarningAsync(e.Message.Author, discord.CurrentUser, reason, contextLink: Warnings.MessageLink(msg), e.Channel);
                        return;
                    }
                    if (match)
                    {
                        return;
                    }
                }

                if (match)
                {
                    return;
                }

                // Mass mentions
                if (e.Message.MentionedUsers.Count >= cfgjson.MassMentionThreshold && Warnings.GetPermLevel(member) < ServerPermLevel.Mod)
                {
                    DiscordChannel logChannel = await discord.GetChannelAsync(cfgjson.LogChannel);

                    try
                    {
                        e.Message.DeleteAsync();
                        var embed = new DiscordEmbedBuilder()
                                    .WithDescription(e.Message.Content)
                                    .WithColor(new DiscordColor(0xf03916))
                                    .WithTimestamp(e.Message.Timestamp)
                                    .WithFooter(
                            $"User ID: {e.Author.Id}",
                            null
                            )
                                    .WithAuthor(
                            $"{e.Author.Username}#{e.Author.Discriminator} in #{e.Channel.Name}",
                            null,
                            e.Author.AvatarUrl
                            );
                        logChannel.SendMessageAsync($"{cfgjson.Emoji.Denied} Deleted infringing message by {e.Author.Mention} in {e.Channel.Mention}:", embed);
                    }
                    catch
                    {
                        // still warn anyway
                    }

                    string         reason = "Mass mentions";
                    DiscordMessage msg    = await e.Channel.SendMessageAsync($"{cfgjson.Emoji.Denied} {e.Message.Author.Mention} was automatically warned: **{reason.Replace("`", "\\`").Replace("*", "\\*")}**");

                    await Warnings.GiveWarningAsync(e.Message.Author, discord.CurrentUser, reason, contextLink : Warnings.MessageLink(msg), e.Channel);

                    return;
                }

                // Unapproved invites
                if (Warnings.GetPermLevel(member) < (ServerPermLevel)cfgjson.InviteTierRequirement)
                {
                    string inviteExclusion = cfgjson.InviteExclusion;
                    if (cfgjson.InviteExclusion != null)
                    {
                        inviteExclusion = cfgjson.InviteExclusion;
                    }

                    string checkedMessage = e.Message.Content.Replace($"discord.gg/{inviteExclusion}", "").Replace($"discord.com/invite/{inviteExclusion}", "").Replace('\\', '/');

                    if (checkedMessage.Contains("discord.gg/") || checkedMessage.Contains("discord.com/invite/"))
                    {
                        try
                        {
                            e.Message.DeleteAsync();
                            var embed = new DiscordEmbedBuilder()
                                        .WithDescription(e.Message.Content)
                                        .WithColor(new DiscordColor(0xf03916))
                                        .WithTimestamp(e.Message.Timestamp)
                                        .WithFooter(
                                $"User ID: {e.Author.Id}",
                                null
                                )
                                        .WithAuthor(
                                $"{e.Author.Username}#{e.Author.Discriminator} in #{e.Channel.Name}",
                                null,
                                e.Author.AvatarUrl
                                );
                            logChannel.SendMessageAsync($"{cfgjson.Emoji.Denied} Deleted infringing message by {e.Author.Mention} in {e.Channel.Mention}:", embed);
                        }
                        catch
                        {
                            // still warn anyway
                        }
                        string         reason = "Sent an invite";
                        DiscordMessage msg    = await e.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Denied} {e.Message.Author.Mention} was automatically warned: **{reason.Replace("`", "\\`").Replace("*", "\\*")}**");

                        await Warnings.GiveWarningAsync(e.Message.Author, discord.CurrentUser, reason, contextLink : Warnings.MessageLink(msg), e.Channel);

                        return;
                    }
                }

                // Mass emoji
                if (!cfgjson.UnrestrictedEmojiChannels.Contains(e.Message.ChannelId) && e.Message.Content.Length >= cfgjson.MassEmojiThreshold)
                {
                    char[] tempArray = e.Message.Content.Replace("🏻", "").Replace("🏼", "").Replace("🏽", "").Replace("🏾", "").Replace("🏿", "").ToCharArray();
                    int    pos       = 0;
                    foreach (char c in tempArray)
                    {
                        if (c == '™' || c == '®' || c == '©')
                        {
                            tempArray[pos] = ' ';
                        }
                        if (c == '\u200d')
                        {
                            tempArray[pos]     = ' ';
                            tempArray[pos + 1] = ' ';
                        }
                        ++pos;
                    }
                    string input = new string(tempArray);

                    var matches = emoji_rx.Matches(input);
                    if (matches.Count > cfgjson.MassEmojiThreshold)
                    {
                        e.Message.DeleteAsync();

                        if (Warnings.GetPermLevel(member) == ServerPermLevel.nothing && !db.HashExists("emojiPardoned", e.Message.Author.Id.ToString()))
                        {
                            await db.HashSetAsync("emojiPardoned", member.Id.ToString(), false);

                            await e.Channel.SendMessageAsync($"{cfgjson.Emoji.Information} {e.Author.Mention}, if you want to play around with lots of emoji, please use <#{cfgjson.UnrestrictedEmojiChannels[0]}> to avoid punishment.");

                            return;
                        }

                        string reason = "Mass emoji";
                        string output = $"{Program.cfgjson.Emoji.Denied} {e.Message.Author.Mention} was automatically warned: **{reason.Replace("`", "\\`").Replace("*", "\\*")}**";
                        if (!db.HashExists("emojiPardoned", e.Author.Id.ToString()) || db.HashGet("emojiPardoned", e.Message.Author.Id.ToString()) == false)
                        {
                            output += $"\nIf you want to play around with lots of emoji, please use <#{cfgjson.UnrestrictedEmojiChannels[0]}> to avoid punishment.";
                            await db.HashSetAsync("emojiPardoned", member.Id.ToString(), true);
                        }

                        DiscordMessage msg = await e.Channel.SendMessageAsync(output);

                        await Warnings.GiveWarningAsync(e.Message.Author, discord.CurrentUser, reason, contextLink : Warnings.MessageLink(msg), e.Channel);

                        return;
                    }
                }
            }

            async Task GuildMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
            {
                if (e.Guild.Id != cfgjson.ServerID)
                {
                    return;
                }

                if (await db.HashExistsAsync("mutes", e.Member.Id))
                {
                    // todo: store per-guild
                    DiscordRole mutedRole = e.Guild.GetRole(cfgjson.MutedRole);
                    await e.Member.GrantRoleAsync(mutedRole, "Reapplying mute: possible mute evasion.");
                }
            }

            discord.Ready                += OnReady;
            discord.MessageCreated       += MessageCreated;
            discord.GuildMemberAdded     += GuildMemberAdded;
            discord.MessageReactionAdded += OnReaction;

            commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefixes = cfgjson.Core.Prefixes
            });;

            commands.RegisterCommands <Warnings>();
            commands.RegisterCommands <MuteCmds>();
            commands.RegisterCommands <UserRoleCmds>();
            commands.RegisterCommands <ModCmds>();

            await discord.ConnectAsync();

            while (true)
            {
                await Task.Delay(10000);

                Mutes.CheckMutesAsync();
                ModCmds.CheckBansAsync();
                ModCmds.CheckRemindersAsync();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
        }
Ejemplo n.º 13
0
        static async Task MainAsync(string[] _)
        {
            var json = "";

            using (var fs = File.OpenRead("config.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = await sr.ReadToEndAsync();

            cfgjson = JsonConvert.DeserializeObject <ConfigJson>(json);

            string redisHost;

            if (Environment.GetEnvironmentVariable("REDIS_DOCKER_OVERRIDE") != null)
            {
                redisHost = "redis";
            }
            else
            {
                redisHost = cfgjson.Redis.Host;
            }
            redis = ConnectionMultiplexer.Connect($"{redisHost}:{cfgjson.Redis.Port}");
            db    = redis.GetDatabase();
            db.KeyDelete("messages");

            discord = new DiscordClient(new DiscordConfiguration
            {
                Token                 = cfgjson.Core.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                LogLevel              = LogLevel.Debug
            });

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            discord.Ready += async e =>
            {
                Console.WriteLine($"Logged in as {e.Client.CurrentUser.Username}#{e.Client.CurrentUser.Discriminator}");
                logChannel = await discord.GetChannelAsync(cfgjson.LogChannel);

                await Task.Delay(4000);

                Mutes.CheckMutesAsync();
            };

            discord.GuildMemberAdded += async e =>
            {
                if (e.Guild.Id != cfgjson.ServerID)
                {
                    return;
                }

                if (await db.HashExistsAsync("mutes", e.Member.Id))
                {
                    // todo: store per-guild
                    DiscordRole mutedRole = e.Guild.GetRole(cfgjson.MutedRole);
                    await e.Member.GrantRoleAsync(mutedRole);
                }
            };

            commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefixes = cfgjson.Core.Prefixes
            });;

            commands.RegisterCommands <Warnings>();
            commands.RegisterCommands <MuteCmds>();

            await discord.ConnectAsync();

            while (true)
            {
                await Task.Delay(60000);

                Mutes.CheckMutesAsync();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
        }
Ejemplo n.º 14
0
 public Mutes.Users_Ids.Result Users_Ids(Mutes.Users_Ids.Command command)
 {
     return _ApiEndpoints._Client.GetResult<Mutes.Users_Ids.Command, Mutes.Users_Ids.Result>(command);
 }