예제 #1
0
        public List <Command> GetPointsCommands()
        {
            var pointCommands = new List <Command>();

            Command points = new Command("points");

            points.Description = "Show the number of points the user has";
            points.ToExecute  += async(client, msg, parameters) =>
            {
                if (!GenericBot.GuildConfigs[msg.GetGuild().Id].PointsEnabled)
                {
                    return;
                }

                var user = new DBGuild(msg.GetGuild().Id).GetUser(msg.Author.Id);
                await msg.ReplyAsync($"{msg.Author.Mention}, you have `{Math.Floor(user.PointsCount)}` {GenericBot.GuildConfigs[msg.GetGuild().Id].PointsName}s!");
            };
            pointCommands.Add(points);

            Command leaderboard = new Command(nameof(leaderboard));

            leaderboard.ToExecute += async(client, msg, parameters) =>
            {
                var    db       = new DBGuild(msg.GetGuild().Id);
                var    topUsers = db.Users.OrderByDescending(u => u.PointsCount).Take(10);
                string result   = $"Top 10 users in {msg.GetGuild().Name}\n";
                int    i        = 1;
                var    config   = GenericBot.GuildConfigs[msg.GetGuild().Id];
                foreach (var user in topUsers)
                {
                    if (msg.GetGuild().Users.HasElement(u => u.Id == user.ID, out SocketGuildUser sgu))
                    {
                        result += $"{i++}: {sgu.GetDisplayName().Escape()}: `{Math.Floor(user.PointsCount)}` {config.PointsName}s\n";
                    }
                    else
                    {
                        result += $"{i++}: Unknown User (ID: `{user.ID}`): `{Math.Floor(user.PointsCount)}` {config.PointsName}s\n";
                    }
                }
                await msg.ReplyAsync(result);
            };

            pointCommands.Add(leaderboard);

            Command award = new Command("award");

            award.Description = "Give a user one of your points";
            award.ToExecute  += async(client, msg, parameters) =>
            {
                var config = GenericBot.GuildConfigs[msg.GetGuild().Id];
                if (!config.PointsEnabled)
                {
                    return;
                }

                var dbGuild = new DBGuild(msg.GetGuild().Id);
                var user    = dbGuild.GetUser(msg.Author.Id);
                if (user.PointsCount < 1)
                {
                    await msg.ReplyAsync($"You don't have any {config.PointsName} to give!");
                }
                else
                {
                    if (msg.MentionedUsers.Any())
                    {
                        if (msg.MentionedUsers.Count > user.PointsCount)
                        {
                            await msg.ReplyAsync($"You don't have that many {GenericBot.GuildConfigs[msg.GetGuild().Id].PointsName}s to give!");
                        }
                        else
                        {
                            foreach (var u in msg.MentionedUsers)
                            {
                                if (u.Id == msg.Author.Id)
                                {
                                    continue;
                                }

                                user.PointsCount--;
                                dbGuild.GetUser(u.Id).PointsCount++;
                            }
                            dbGuild.Save();
                            await msg.ReplyAsync($"{msg.MentionedUsers.Select(us => us.Mention).ToList().SumAnd()} received a {GenericBot.GuildConfigs[msg.GetGuild().Id].PointsName} from {msg.Author.Mention}!");
                        }
                    }
                    else
                    {
                        await msg.ReplyAsync($"You have to select a user to give a {config.PointsName} to");
                    }
                }
            };
            pointCommands.Add(award);

            Command setPoints = new Command("setpoints");

            setPoints.RequiredPermission = Command.PermissionLevels.GlobalAdmin;
            setPoints.ToExecute         += async(client, msg, parameters) =>
            {
                var dbGuild = new DBGuild(msg.GetGuild().Id);
                var user    = dbGuild.GetUser(ulong.Parse(parameters[0]));
                user.PointsCount = decimal.Parse(parameters[1]);
                dbGuild.Save();
                await msg.ReplyAsync($"`{parameters[0]}` now has {(user.PointsCount)} points");
            };
            pointCommands.Add(setPoints);

            return(pointCommands);
        }
예제 #2
0
        public static async Task UserJoined(SocketGuildUser user)
        {
            #region Database

            var  guildDb       = new DBGuild(user.Guild.Id);
            bool alreadyJoined = false;
            if (guildDb.Users.Any(u => u.ID.Equals(user.Id))) // if already exists
            {
                guildDb.Users.Find(u => u.ID.Equals(user.Id)).AddUsername(user.Username);
                alreadyJoined = true;
            }
            else
            {
                guildDb.Users.Add(new DBUser(user));
            }
            guildDb.Save();

            #endregion Databasae

            #region Logging

            var guildConfig = GenericBot.GuildConfigs[user.Guild.Id];

            if (!(guildConfig.VerifiedRole == 0 || (string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !user.Guild.Roles.Any(r => r.Id == guildConfig.VerifiedRole))))
            {
                string vMessage = $"Hey {user.Username}! To get verified on **{user.Guild.Name}** reply to this message with the hidden code in the message below\n\n"
                                  + GenericBot.GuildConfigs[user.Guild.Id].VerifiedMessage;

                string verificationMessage =
                    VerificationEngine.InsertCodeInMessage(vMessage, VerificationEngine.GetVerificationCode(user.Id, user.Guild.Id));

                try
                {
                    await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(verificationMessage);
                }
                catch
                {
                    await GenericBot.Logger.LogErrorMessage($"Could not send verification DM to {user} ({user.Id}) on {user.Guild} ({user.Guild.Id})");
                }
            }
            if (guildConfig.ProbablyMutedUsers.Contains(user.Id))
            {
                try { await user.AddRoleAsync(user.Guild.GetRole(guildConfig.MutedRoleId)); }
                catch { }
            }
            if (guildConfig.AutoRoleIds != null && guildConfig.AutoRoleIds.Any())
            {
                foreach (var role in guildConfig.AutoRoleIds)
                {
                    try
                    {
                        await user.AddRoleAsync(user.Guild.GetRole(role));
                    }
                    catch
                    {
                        // Supress
                    }
                }
            }

            if (guildConfig.UserLogChannelId == 0)
            {
                return;
            }

            EmbedBuilder log = new EmbedBuilder()
                               .WithAuthor(new EmbedAuthorBuilder().WithName("User Joined")
                                           .WithIconUrl(user.GetAvatarUrl()).WithUrl(user.GetAvatarUrl()))
                               .WithColor(114, 137, 218)
                               .AddField(new EmbedFieldBuilder().WithName("Username").WithValue(user.ToString().Escape()).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("UserId").WithValue(user.Id).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("Mention").WithValue(user.Mention).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("User Number").WithValue(user.Guild.MemberCount + (!alreadyJoined ? " (New Member)" : "")).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("Database Number").WithValue(guildDb.Users.Count + (alreadyJoined ? " (Previous Member)" : "")).WithIsInline(true))
                               .WithFooter($"{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");

            if ((DateTimeOffset.Now - user.CreatedAt).TotalDays < 7)
            {
                log.AddField(new EmbedFieldBuilder().WithName("New User")
                             .WithValue($"Account made {(DateTimeOffset.Now - user.CreatedAt).Nice()} ago").WithIsInline(true));
            }

            try
            {
                DBUser usr = guildDb.Users.First(u => u.ID.Equals(user.Id));

                if (!usr.Warnings.Empty())
                {
                    string warns = "";
                    for (int i = 0; i < usr.Warnings.Count; i++)
                    {
                        warns += $"{i + 1}: {usr.Warnings.ElementAt(i)}\n";
                    }
                    log.AddField(new EmbedFieldBuilder().WithName($"{usr.Warnings.Count} Warnings")
                                 .WithValue(warns));
                }
            }
            catch
            {
            }

            await user.Guild.GetTextChannel(guildConfig.UserLogChannelId).SendMessageAsync("", embed: log.Build());

            #endregion Logging

            #region Antispam

            if (guildConfig.AntispamLevel >= GuildConfig.AntiSpamLevel.Advanced)
            {
                var inviteLink = new Regex(@"(?:https?:\/\/)?(?:www\.)?(discord\.gg|discord\.io|discord\.me|discordapp\.com\/invite|paypal\.me|twitter\.com|youtube\.com|bit\.ly|twitch\.tv)\/(\S+)");
                if (inviteLink.Matches(user.Username).Any())
                {
                    if (guildConfig.AntispamLevel == GuildConfig.AntiSpamLevel.Advanced)
                    {
                        await user.KickAsync("Username Contains Discord Spam Invite");

                        var builder = new EmbedBuilder()
                                      .WithTitle("User Kicked")
                                      .WithDescription("Discord Invite in Username (Antispam)")
                                      .WithColor(new Color(0xFFFF00))
                                      .WithFooter(footer => {
                            footer
                            .WithText($"By {GenericBot.DiscordClient.CurrentUser} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                        })
                                      .WithAuthor(author => {
                            author
                            .WithName(user.ToString())
                            .WithIconUrl(user.GetAvatarUrl());
                        });

                        var guilddb     = new DBGuild(user.Guild.Id);
                        var guildconfig = GenericBot.GuildConfigs[user.Guild.Id];
                        guilddb.GetUser(user.Id)
                        .AddWarning(
                            $"Kicked for `Username Contains Discord Spam Invite` (By `{GenericBot.DiscordClient.CurrentUser}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)");
                        guilddb.Save();

                        if (guildconfig.UserLogChannelId != 0)
                        {
                            await(GenericBot.DiscordClient.GetChannel(guildconfig.UserLogChannelId) as SocketTextChannel)
                            .SendMessageAsync("", embed: builder.Build());
                        }
                    }
                    else if (guildConfig.AntispamLevel >= GuildConfig.AntiSpamLevel.Aggressive)
                    {
                        await user.BanAsync(0, "Username Contains Discord Spam Invite");

                        var builder = new EmbedBuilder()
                                      .WithTitle("User Banned")
                                      .WithDescription("Discord Invite in Username (Antispam)")
                                      .WithColor(new Color(0xFFFF00))
                                      .WithFooter(footer => {
                            footer
                            .WithText($"By {GenericBot.DiscordClient.CurrentUser} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                        })
                                      .WithAuthor(author => {
                            author
                            .WithName(user.ToString())
                            .WithIconUrl(user.GetAvatarUrl());
                        });

                        var guilddb     = new DBGuild(user.Guild.Id);
                        var guildconfig = GenericBot.GuildConfigs[user.Guild.Id];
                        guilddb.GetUser(user.Id)
                        .AddWarning(
                            $"Banned for `Username Contains Discord Spam Invite` (By `{GenericBot.DiscordClient.CurrentUser}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)");
                        guilddb.Save();

                        if (guildconfig.UserLogChannelId != 0)
                        {
                            await(GenericBot.DiscordClient.GetChannel(guildconfig.UserLogChannelId) as SocketTextChannel)
                            .SendMessageAsync("", embed: builder.Build());
                        }
                    }
                }
            }

            #endregion Antispam
        }
예제 #3
0
        public List <Command> GetTestCommands()
        {
            List <Command> TestCommands = new List <Command>();

            Command listEmotes = new Command("listemotes");

            listEmotes.RequiredPermission = Command.PermissionLevels.Admin;
            listEmotes.Delete             = true;
            listEmotes.ToExecute         += async(client, msg, parameters) =>
            {
                if (!msg.GetGuild().Emotes.Any())
                {
                    await msg.ReplyAsync($"`{msg.GetGuild().Name}` has no emotes");

                    return;
                }
                string emotes = $"`{msg.GetGuild().Name}` has `{msg.GetGuild().Emotes.Count}` emotes:";
                int    i      = 0;
                foreach (var emote in msg.GetGuild().Emotes)
                {
                    if (i % 3 == 0)
                    {
                        emotes += "\n";
                    }
                    if (emote.Url.Contains("gif"))
                    {
                        emotes += $"<a:{emote.Name}:{emote.Id}> `:{emote.Name}:`";
                    }
                    else
                    {
                        emotes += $"<:{emote.Name}:{emote.Id}> `:{emote.Name}:`";
                    }
                    for (int c = emote.Name.Length + 2; c < 16; c++)
                    {
                        emotes += " ";
                    }
                    i++;
                }
                await msg.ReplyAsync(emotes);
            };

            TestCommands.Add(listEmotes);

            Command updateDB = new Command("updateDB");

            updateDB.Delete             = false;
            updateDB.RequiredPermission = Command.PermissionLevels.GlobalAdmin;
            updateDB.ToExecute         += async(client, msg, paramList) =>
            {
                await msg.GetGuild().DownloadUsersAsync();

                int newUsers     = 0;
                int updatedUsers = 0;

                var db = new DBGuild(msg.GetGuild().Id);
                foreach (var user in msg.GetGuild().Users)
                {
                    if (!db.Users.Any(u => u.ID.Equals(user.Id)))
                    {
                        db.Users.Add(new DBUser(user));
                        newUsers++;
                    }
                    else
                    {
                        db.GetUser(user.Id).AddUsername(user.Username);
                        db.GetUser(user.Id).AddNickname(user);
                        updatedUsers++;
                    }
                }

                db.Save();
                await msg.ReplyAsync($"`{newUsers}` users added to database, `{updatedUsers}` updated");
            };

            TestCommands.Add(updateDB);

            Command IdInfo = new Command("idInfo");

            IdInfo.Aliases = new List <string> {
                "id"
            };
            IdInfo.Description = "Get information from a given ID";
            IdInfo.ToExecute  += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync("No ID given");

                    return;
                }
                ulong id;
                if (ulong.TryParse(parameters[0], out id))
                {
                    ulong          rawtime   = id >> 22;
                    long           epochtime = (long)rawtime + 1420070400000;
                    DateTimeOffset time      = DateTimeOffset.FromUnixTimeMilliseconds(epochtime);
                    await msg.ReplyAsync($"ID: `{id}`\nDateTime: `{time.ToString(@"yyyy-MM-dd HH:mm:ss.fff tt")} GMT`");
                }
                else
                {
                    await msg.ReplyAsync("That's not a valid ID");
                }
            };

            TestCommands.Add(IdInfo);

            Command DBStats = new Command("dbstats");

            DBStats.RequiredPermission = Command.PermissionLevels.GlobalAdmin;
            DBStats.ToExecute         += async(client, msg, parameters) =>
            {
                Stopwatch stw = new Stopwatch();
                stw.Start();
                string info = "";

                var guildDb = new DBGuild(msg.GetGuild().Id);

                info += $"Registered Users: `{guildDb.Users.Count}`\n";

                int unc = 0, nnc = 0, wnc = 0, nuc = 0;
                foreach (var user in guildDb.Users)
                {
                    if (user.Usernames != null && user.Usernames.Any())
                    {
                        unc += user.Usernames.Count;
                    }
                    if (user.Nicknames != null && user.Nicknames.Any())
                    {
                        nnc += user.Nicknames.Count;
                    }
                    if (user.Warnings != null && user.Warnings.Any())
                    {
                        wnc += user.Warnings.Count;
                        nuc++;
                    }
                }

                info += $"Stored Usernames: `{unc}`\n";
                info += $"Stored Nicknames: `{nnc}`\n";
                info += $"Stored Warnings:  `{wnc}`\n";
                info += $"Users with Warnings:  `{nuc}`\n";

                info += $"Access time: `{stw.ElapsedMilliseconds}`ms\n";
                await msg.ReplyAsync(info);
            };

            TestCommands.Add(DBStats);

            Command addwarning = new Command("oldwarning");

            addwarning.Description       += "Add a warning to the database without meta info";
            addwarning.Usage              = "oldwarning <user> <warning>";
            addwarning.RequiredPermission = Command.PermissionLevels.Admin;
            ulong uid;

            addwarning.ToExecute += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync("You must specify a user");

                    return;
                }

                if (ulong.TryParse(parameters[0].TrimStart('<', '@', '!').TrimEnd('>'), out uid))
                {
                    parameters.RemoveAt(0);
                    string warning = parameters.reJoin();
                    var    guildDb = new DBGuild(msg.GetGuild().Id);
                    if (guildDb.Users.Any(u => u.ID.Equals(uid))) // if already exists
                    {
                        guildDb.Users.Find(u => u.ID.Equals(uid)).AddWarning(warning);
                    }
                    else
                    {
                        guildDb.Users.Add(new DBUser {
                            ID = uid, Warnings = new List <string> {
                                warning
                            }
                        });
                    }
                    guildDb.Save();
                    await msg.ReplyAsync($"Added `{warning.Replace('`', '\'')}` to <@{uid}> (`{uid}`)");
                }
                else
                {
                    await msg.ReplyAsync("Could not find that user");
                }
            };

            TestCommands.Add(addwarning);

            Command archivePins = new Command("archivePins");

            archivePins.RequiredPermission = Command.PermissionLevels.GlobalAdmin;
            archivePins.ToExecute         += async(client, msg, parameters) =>
            {
                var msgs = msg.Channel.GetPinnedMessagesAsync().Result.ToList();
                if (msgs.Any())
                {
                    msgs.Reverse();
                    string header   = "<html><head><style>body {background-color: #36393e; color: #fff; font-family: \"Trebuchet MS\", Helvetica, sans-serif; font-size: small }server {font-size: 150%}channel {font-size: 130%}username {font-size: 100%}message {font-size: 80%}reqinf {font-size: 60%; color: grey;}</style></head>";
                    string server   = $"<body> <i><server>{msg.GetGuild().Name}</server> in <channel>#{msg.Channel.Name}</channel></i><hr>";
                    string messages = "";
                    foreach (var m in msgs)
                    {
                        string mess = m.Content;
                        foreach (var u in m.MentionedUsers)
                        {
                            mess = mess.Replace($"<@!{u.Id}>", $"@{u.Username}");
                            mess = mess.Replace($"<@{u.Id}>", $"@{u.Username}");
                            mess = mess.Replace(u.Mention, $"@{u.Username}");
                        }
                        foreach (var c in m.MentionedChannelIds)
                        {
                            mess = mess.Replace($"<#{c}>", $"#{(client.GetChannel(c) as IMessageChannel).Name}");
                        }
                        foreach (var u in m.MentionedRoleIds)
                        {
                            mess = mess.Replace($"<@&u>", $"@{msg.GetGuild().GetRole(u).Name}");
                        }
                        messages += $"<username>{m.Author}</username><br><message>{mess}</message><hr>";
                    }
                    string footer = $"<br><br> <i><reqinf>Requested by <b>{msg.Author}</b></reqinf></i></body></html>";

                    File.WriteAllText($"files/{msg.Channel.Name}_pins.html", header + server + messages + footer, Encoding.UTF8);
                    await msg.Channel.SendFileAsync($"files/{msg.Channel.Name}_pins.html");

                    File.Delete($"files/{msg.Channel.Name}_pins.html");
                }
                else
                {
                    await msg.ReplyAsync($"This channel has no pinned messages!");
                }
            };
            TestCommands.Add(archivePins);

            TestCommands.Add(DBStats);
            Command verify = new Command("verify");

            verify.RequiredPermission = Command.PermissionLevels.User;
            verify.ToExecute         += async(client, msg, parameter) =>
            {
                List <SocketUser> users = new List <SocketUser>();
                var guildConfig         = GenericBot.GuildConfigs[msg.GetGuild().Id];

                if (parameter.Empty())
                {
                    if ((msg.Author as SocketGuildUser).Roles.Any(r => r.Id == guildConfig.VerifiedRole))
                    {
                        await msg.ReplyAsync("You're already verified");

                        return;
                    }
                    users.Add(msg.Author);
                }
                else
                {
                    foreach (var user in msg.GetMentionedUsers())
                    {
                        if ((user as SocketGuildUser).Roles.Any(r => r.Id == guildConfig.VerifiedRole))
                        {
                            await msg.ReplyAsync($"{user.Username} is already verified");
                        }
                        else
                        {
                            users.Add(user);
                        }
                    }
                }


                if (guildConfig.VerifiedRole == 0)
                {
                    await msg.ReplyAsync($"Verification is disabled on this server");

                    return;
                }

                if ((string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !msg.GetGuild().Roles.Any(r => r.Id == guildConfig.VerifiedRole)))
                {
                    await msg.ReplyAsync(
                        $"It looks like verifiction is configured improperly (either the message is too short or the role does not exist.) Please contact your server administrator to resolve it.");

                    return;
                }

                List <SocketUser> failed  = new List <SocketUser>();
                List <SocketUser> success = new List <SocketUser>();
                foreach (var user in users)
                {
                    string message = $"Hey {user.Username}! To get verified on **{msg.GetGuild().Name}** reply to this message with the hidden code in the message below\n\n"
                                     + GenericBot.GuildConfigs[msg.GetGuild().Id].VerifiedMessage;

                    string verificationMessage =
                        VerificationEngine.InsertCodeInMessage(message, VerificationEngine.GetVerificationCode(user.Id, msg.GetGuild().Id));

                    try
                    {
                        await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(verificationMessage);

                        success.Add(user);
                    }
                    catch
                    {
                        failed.Add(user);
                    }
                }

                string reply = "";
                if (success.Any())
                {
                    reply += $"I've sent {success.Select(u => u.Username).ToList().SumAnd()} instructions!";
                }
                if (failed.Any())
                {
                    reply += $" {failed.Select(u => u.Username).ToList().SumAnd()} could not be messaged.";
                }
                await msg.ReplyAsync(reply);
            };
            TestCommands.Add(verify);

            Command cmdp = new Command("cmd");

            cmdp.RequiredPermission = Command.PermissionLevels.GlobalAdmin;
            cmdp.ToExecute         += async(client, msg, parameters) =>
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    Process cmd = new Process();
                    cmd.StartInfo.FileName = "cmd.exe";
                    cmd.StartInfo.RedirectStandardInput  = true;
                    cmd.StartInfo.RedirectStandardOutput = true;
                    cmd.StartInfo.CreateNoWindow         = true;
                    cmd.StartInfo.UseShellExecute        = false;
                    cmd.Start();

                    cmd.StandardInput.WriteLine(parameters.reJoin());
                    cmd.StandardInput.Flush();
                    cmd.StandardInput.Close();
                    cmd.WaitForExit();
                    foreach (var str in cmd.StandardOutput.ReadToEnd().SplitSafe('\n'))
                    {
                        await msg.ReplyAsync($"```\n{str}\n```");
                    }
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Process proc = new System.Diagnostics.Process();
                    proc.StartInfo.FileName  = "/bin/bash";
                    proc.StartInfo.Arguments = "-c \"" + parameters.reJoin() + " > results\"";
                    proc.StartInfo.RedirectStandardOutput = true;
                    proc.StartInfo.CreateNoWindow         = true;
                    proc.StartInfo.UseShellExecute        = false;

                    proc.Start();
                    proc.WaitForExit();

                    Console.WriteLine(proc.StandardOutput.ReadToEnd());
                    foreach (string str in File.ReadAllText("results").SplitSafe('\n'))
                    {
                        await msg.ReplyAsync($"```\n{str}\n```");
                    }
                }
                else
                {
                    await msg.ReplyAsync("Unrecognized platform");
                }
            };
            TestCommands.Add(cmdp);

            Command decryptDb = new Command("decryptDb");

            decryptDb.RequiredPermission = Command.PermissionLevels.GlobalAdmin;
            decryptDb.ToExecute         += async(client, msg, parameters) =>
            {
                File.WriteAllText($"files/guildDbs/{parameters[0]}_raw.json", AES.DecryptText(File.ReadAllText($"files/guildDbs/{parameters[0]}.json"), GenericBot.GlobalConfiguration.DatabasePassword));
                var res = msg.Channel.SendFileAsync($"files/guildDbs/{parameters[0]}_raw.json", "Self-destructing in 15 seconds!").Result;
                await Task.Delay(TimeSpan.FromSeconds(15));

                try { await res.DeleteAsync(); }
                catch { }
            };

            TestCommands.Add(decryptDb);

            Command repairDb = new Command("repairDb");

            repairDb.RequiredPermission = Command.PermissionLevels.GlobalAdmin;
            repairDb.ToExecute         += async(client, msg, paramList) =>
            {
                lock (msg.GetGuild().Id.ToString())
                {
                    var db = new DBGuild(msg.GetGuild().Id);


                    foreach (var user in db.Users)
                    {
                        if (!user.Nicknames.Empty())
                        {
                            user.Nicknames = user.Nicknames.Where(n => !string.IsNullOrEmpty(n)).ToList();
                        }

                        if (!user.Usernames.Empty())
                        {
                            user.Usernames = user.Usernames.Where(n => !string.IsNullOrEmpty(n)).ToList();
                        }
                    }
                    db.Save();
                }
                await msg.ReplyAsync($"Done!");
            };

            TestCommands.Add(repairDb);

            return(TestCommands);
        }
예제 #4
0
        public List <Command> GetConfigComamnds()
        {
            List <Command> ConfigCommands = new List <Command>();

            Command config = new Command("config");

            config.Usage              = "config <option> <value>`\nOptions are: `adminroles`, `moderatorroles`, `userroles`, `twitter`, `user`, `mutedroleid";
            config.Description        = "Configure the bot's option";
            config.RequiredPermission = Command.PermissionLevels.Admin;
            config.ToExecute         += async(client, msg, paramList) =>
            {
                if (paramList.Empty())
                {
                    await msg.Channel.SendMessageAsync($"Please enter a value to configure.");

                    return;
                }
                #region AdminRoles
                if (paramList[0].ToLower().Equals("adminroles"))
                {
                    if (config.GetPermissions(msg.Author, msg.GetGuild().Id) >= Command.PermissionLevels.GuildOwner)
                    {
                        if (paramList.Count == 1)
                        {
                            await msg.ReplyAsync($"Please enter a config option");

                            return;
                        }
                        if (paramList.Count == 2)
                        {
                            await msg.ReplyAsync($"Please enter a roleId");

                            return;
                        }
                        ulong id;
                        if (ulong.TryParse(paramList[2], out id) && msg.GetGuild().Roles.Select(r => r.Id).Any(u => u.Equals(id)))
                        {
                            if (paramList[1].ToLower().Equals("add"))
                            {
                                if (!GenericBot.GuildConfigs[msg.GetGuild().Id].AdminRoleIds.Contains(id))
                                {
                                    GenericBot.GuildConfigs[msg.GetGuild().Id].AdminRoleIds.Add(id);
                                    await msg.ReplyAsync($"Added {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} to Admin Roles");
                                }
                                else
                                {
                                    await msg.ReplyAsync($"Admin Roles already contains {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}");
                                }
                            }
                            else if (paramList[1].ToLower().Equals("remove"))
                            {
                                if (GenericBot.GuildConfigs[msg.GetGuild().Id].AdminRoleIds.Contains(id))
                                {
                                    GenericBot.GuildConfigs[msg.GetGuild().Id].AdminRoleIds.Remove(id);
                                    await msg.ReplyAsync($"Removed {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} from Admin Roles");
                                }
                                else
                                {
                                    await msg.ReplyAsync(
                                        $"Admin Roles doesn't contain {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}");
                                }
                            }
                            else
                            {
                                await msg.ReplyAsync($"Unknown property `{paramList[1]}`.");
                            }
                        }
                        else
                        {
                            await msg.ReplyAsync($"That is not a valid roleId");
                        }
                    }
                    else
                    {
                        await msg.ReplyAsync($"You don't have the permissions to do that");
                    }
                }
                #endregion AdminRoles

                #region ModRoles

                else if (paramList[0].ToLower().Equals("moderatorroles") || paramList[0].ToLower().Equals("modroles"))
                {
                    if (config.GetPermissions(msg.Author, msg.GetGuild().Id) >= Command.PermissionLevels.Admin)
                    {
                        if (paramList.Count == 1)
                        {
                            await msg.ReplyAsync($"Please enter a config option");

                            return;
                        }
                        if (paramList.Count == 2)
                        {
                            await msg.ReplyAsync($"Please enter a roleId");

                            return;
                        }
                        ulong id;
                        if (ulong.TryParse(paramList[2], out id) && msg.GetGuild().Roles.Select(r => r.Id).Any(u => u.Equals(id)))
                        {
                            if (paramList[1].ToLower().Equals("add"))
                            {
                                if (!GenericBot.GuildConfigs[msg.GetGuild().Id].ModRoleIds.Contains(id))
                                {
                                    GenericBot.GuildConfigs[msg.GetGuild().Id].ModRoleIds.Add(id);
                                    await msg.ReplyAsync($"Added {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} to Moderator Roles");
                                }
                                else
                                {
                                    await msg.ReplyAsync($"Moderator Roles already contains {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}");
                                }
                            }
                            else if (paramList[1].ToLower().Equals("remove"))
                            {
                                if (GenericBot.GuildConfigs[msg.GetGuild().Id].ModRoleIds.Contains(id))
                                {
                                    {
                                        GenericBot.GuildConfigs[msg.GetGuild().Id].ModRoleIds.Remove(id);
                                        await msg.ReplyAsync(
                                            $"Removed {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} from Moderator Roles");
                                    }
                                }
                                else
                                {
                                    await msg.ReplyAsync(
                                        $"Moderator Roles doesn't contain {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}");
                                }
                            }
                            else
                            {
                                await msg.ReplyAsync($"Unknown property `{paramList[1]}`.");
                            }
                        }
                        else
                        {
                            await msg.ReplyAsync($"That is not a valid roleId");
                        }
                    }
                    else
                    {
                        await msg.ReplyAsync($"You don't have the permissions to do that");
                    }
                }

                #endregion ModRoles

                #region UserRoles

                else if (paramList[0].ToLower().Equals("userroles"))
                {
                    if (config.GetPermissions(msg.Author, msg.GetGuild().Id) >= Command.PermissionLevels.Admin)
                    {
                        if (paramList.Count == 1)
                        {
                            await msg.ReplyAsync($"Please enter a config option");

                            return;
                        }
                        if (paramList.Count == 2)
                        {
                            await msg.ReplyAsync($"Please enter a roleId");

                            return;
                        }
                        ulong id;
                        if (ulong.TryParse(paramList[2], out id) && msg.GetGuild().Roles.Select(r => r.Id).Any(u => u.Equals(id)))
                        {
                            if (paramList[1].ToLower().Equals("add"))
                            {
                                if (!GenericBot.GuildConfigs[msg.GetGuild().Id].UserRoleIds.Contains(id))
                                {
                                    GenericBot.GuildConfigs[msg.GetGuild().Id].UserRoleIds.Add(id);
                                    await msg.ReplyAsync($"Added {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} to User Roles");
                                }
                                else
                                {
                                    await msg.ReplyAsync($"User Roles already contains {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}");
                                }
                            }
                            else if (paramList[1].ToLower().Equals("remove"))
                            {
                                if (GenericBot.GuildConfigs[msg.GetGuild().Id].UserRoleIds.Contains(id))
                                {
                                    {
                                        GenericBot.GuildConfigs[msg.GetGuild().Id].UserRoleIds.Remove(id);
                                        await msg.ReplyAsync(
                                            $"Removed {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} from User Roles");
                                    }
                                }
                                else
                                {
                                    await msg.ReplyAsync($"User Roles doesn't contain {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}");
                                }
                            }
                            else
                            {
                                await msg.ReplyAsync($"Unknown property `{paramList[1]}`.");
                            }
                        }
                        else
                        {
                            await msg.ReplyAsync($"That is not a valid roleId");
                        }
                    }
                    else
                    {
                        await msg.ReplyAsync($"You don't have the permissions to do that");
                    }
                }

                #endregion UserRoles

                #region Twitter

                else if (paramList[0].ToLower().Equals("twitter"))
                {
                    if (paramList[1].ToLower() == "true")
                    {
                        GenericBot.GuildConfigs[msg.GetGuild().Id].AllowTwitter = true;
                        await msg.ReplyAsync("Tweeting on this server has been enabled");
                    }
                    else if (paramList[1].ToLower() == "false")
                    {
                        GenericBot.GuildConfigs[msg.GetGuild().Id].AllowTwitter = false;
                        await msg.ReplyAsync("Tweeting on this server has been disabled");
                    }
                    else
                    {
                        await msg.ReplyAsync("That's not a valid option");
                    }
                }

                #endregion Twitter

                #region Prefix

                else if (paramList[0].ToLower().Equals("prefix"))
                {
                    try
                    {
                        paramList.RemoveAt(0);
                        GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix = paramList.reJoin();
                        if (msg.Content.EndsWith('"') && paramList[0].ToCharArray()[0].Equals('"'))
                        {
                            GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix = new Regex("\"(.*?)\"").Match(msg.Content).Value.Trim('"');
                        }
                        await msg.ReplyAsync($"The prefix has been set to `{GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix}`");
                    }
                    catch (Exception Ex)
                    {
                        GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix = "";
                        await msg.ReplyAsync($"The prefix has been reset to the default of `{GenericBot.GlobalConfiguration.DefaultPrefix}`");
                    }
                }

                #endregion Prefix

                #region Logging

                else if (paramList[0].ToLower().Equals("logging"))
                {
                    if (paramList[1].ToLower().Equals("channelid"))
                    {
                        if (paramList.Count() == 2)
                        {
                            await msg.ReplyAsync(
                                $"Current user event channel: <#{GenericBot.GuildConfigs[msg.GetGuild().Id].UserLogChannelId}>");
                        }
                        else
                        {
                            ulong cId;
                            if (ulong.TryParse(paramList[2], out cId) && (msg.GetGuild().Channels.Any(c => c.Id == cId) || cId == 0))
                            {
                                GenericBot.GuildConfigs[msg.GetGuild().Id].UserLogChannelId = cId;
                                await msg.ReplyAsync(
                                    $"User event channel set to <#{GenericBot.GuildConfigs[msg.GetGuild().Id].UserLogChannelId}>");
                            }
                            else
                            {
                                await msg.ReplyAsync("Invalid Channel Id");
                            }
                        }
                    }
                    else if (paramList[1].ToLower().Equals("ignorechannel"))
                    {
                        if (paramList.Count == 2)
                        {
                            string m = "Ignored channels:";
                            foreach (var id in GenericBot.GuildConfigs[msg.GetGuild().Id].MessageLoggingIgnoreChannels)
                            {
                                m += $"\n<#{id}>";
                            }

                            await msg.ReplyAsync(m);
                        }
                        else
                        {
                            if (ulong.TryParse(paramList[2], out ulong cId) &&
                                msg.GetGuild().TextChannels.Any(c => c.Id == cId))
                            {
                                if (!GenericBot.GuildConfigs[msg.GetGuild().Id].MessageLoggingIgnoreChannels.Contains(cId))
                                {
                                    GenericBot.GuildConfigs[msg.GetGuild().Id].MessageLoggingIgnoreChannels.Add(cId);
                                    await msg.ReplyAsync($"No longer logging <#{cId}>");
                                }
                                else
                                {
                                    GenericBot.GuildConfigs[msg.GetGuild().Id].MessageLoggingIgnoreChannels.Remove(cId);
                                    await msg.ReplyAsync($"Resuming logging <#{cId}>");
                                }
                            }
                            else
                            {
                                await msg.ReplyAsync("Invalid Channel Id");
                            }
                        }
                    }
                }

                #endregion Logging

                #region MutedRoleId

                else if (paramList[0].ToLower().Equals("mutedroleid"))
                {
                    paramList.RemoveAt(0);
                    if (paramList.Count != 1)
                    {
                        await msg.ReplyAsync(
                            "Incorrect number of arguments. Make sure the command is `voicerole [VoiceChannelId] [RoleId]`");

                        return;
                    }
                    else
                    {
                        ulong roleId;
                        if (ulong.TryParse(paramList[0], out roleId) && (msg.GetGuild().Roles.Any(r => r.Id == roleId) || roleId == 0))
                        {
                            GenericBot.GuildConfigs[msg.GetGuild().Id].MutedRoleId = roleId;
                            GenericBot.GuildConfigs[msg.GetGuild().Id].Save();
                            await msg.ReplyAsync($"MutedRoleId is now `{roleId}`");
                        }
                        else
                        {
                            await msg.ReplyAsync("Invalid Role Id");
                        }
                    }
                }

                #endregion MutedRoleId

                #region Verification

                else if (paramList[0].ToLower().Equals("verification"))
                {
                    if (paramList[1].ToLower().Equals("roleid"))
                    {
                        if (paramList.Count == 2)
                        {
                            var roleId = GenericBot.GuildConfigs[msg.GetGuild().Id].VerifiedRole;
                            if (roleId == 0)
                            {
                                await msg.ReplyAsync("Verification is disabled on this server");
                            }
                            else
                            {
                                await msg.ReplyAsync(
                                    $"Verification role is  `{msg.GetGuild().Roles.First(g => g.Id == roleId).Name}`");
                            }
                        }
                        else if (ulong.TryParse(paramList[2], out ulong roleId) && (msg.GetGuild().Roles.Any(g => g.Id == roleId) || roleId == 0))
                        {
                            GenericBot.GuildConfigs[msg.GetGuild().Id].VerifiedRole = roleId;
                            if (roleId != 0)
                            {
                                await msg.ReplyAsync(
                                    $"Verification role set to `{msg.GetGuild().Roles.First(g => g.Id == roleId).Name}`");
                            }
                            else
                            {
                                await msg.ReplyAsync("Verification role cleared. Verification is off for this server.");
                            }
                        }
                        else
                        {
                            await msg.ReplyAsync("Invalid RoleId");
                        }
                    }
                    else if (paramList[1].ToLower().Equals("message"))
                    {
                        string pref = GenericBot.GlobalConfiguration.DefaultPrefix;
                        if (!String.IsNullOrEmpty(GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix))
                        {
                            pref = GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix;
                        }

                        string message = msg.Content;
                        message = message.Remove(0, pref.Length).TrimStart(' ').Remove(0, "config".Length).TrimStart(' ').Remove(0, "verification".Length).TrimStart(' ').Remove(0, "message".Length).Trim(' ');

                        if (!string.IsNullOrEmpty(message))
                        {
                            GenericBot.GuildConfigs[msg.GetGuild().Id].VerifiedMessage = message;
                        }

                        await msg.ReplyAsync("Example verification message:");

                        string vm = $"Hey {msg.Author.Username}! To get verified on **{msg.GetGuild().Name}** reply to this message with the hidden code in the message below\n\n"
                                    + GenericBot.GuildConfigs[msg.GetGuild().Id].VerifiedMessage;

                        string verificationMessage =
                            VerificationEngine.InsertCodeInMessage(vm, VerificationEngine.GetVerificationCode(msg.Author.Id, msg.GetGuild().Id));

                        await msg.ReplyAsync(verificationMessage);
                    }
                    else
                    {
                        await msg.ReplyAsync("Invalid Option");
                    }
                }

                #endregion Verification

                #region Points

                else if (paramList[0].ToLower().Equals("points"))
                {
                    if (paramList[1].ToLower().Equals("enabled"))
                    {
                        GenericBot.GuildConfigs[msg.GetGuild().Id].PointsEnabled =
                            !GenericBot.GuildConfigs[msg.GetGuild().Id].PointsEnabled;
                        if (GenericBot.GuildConfigs[msg.GetGuild().Id].PointsEnabled)
                        {
                            await msg.ReplyAsync($"Enabled points for this server");
                        }
                        else
                        {
                            await msg.ReplyAsync($"Disabled points for this server");
                        }
                    }
                    else if (paramList[1].ToLower().Equals("noun"))
                    {
                        if (paramList.Count != 3)
                        {
                            await msg.ReplyAsync("Please use one word as the name for the points name");
                        }
                        else
                        {
                            GenericBot.GuildConfigs[msg.GetGuild().Id].PointsName = paramList[2];
                            await msg.ReplyAsync($"Set the name for points to `{paramList[2]}`");
                        }
                    }
                    else if (paramList[1].ToLower().Equals("verb"))
                    {
                        if (paramList.Count != 3)
                        {
                            await msg.ReplyAsync("Please use one word as the name for the points verb");

                            return;
                        }
                        else
                        {
                            GenericBot.GuildConfigs[msg.GetGuild().Id].PointsVerb = paramList[2];
                            await msg.ReplyAsync($"Set the verb for using points to `{paramList[2]}`");
                        }
                    }
                    else
                    {
                        await msg.ReplyAsync("Unknown option");
                    }
                }

                #endregion Points

                #region GlobalBanOptOut

                else if (paramList[0].ToLower().Equals("globalbanoptout"))
                {
                    if (paramList.Count > 1 && paramList[1].ToLower().Equals("true"))
                    {
                        GenericBot.GuildConfigs[msg.GetGuild().Id].GlobalBanOptOut = true;
                        await msg.ReplyAsync($"You have opted out of the global bans");
                    }
                    else if (paramList.Count > 1 && paramList[1].ToLower().Equals("false"))
                    {
                        GenericBot.GuildConfigs[msg.GetGuild().Id].GlobalBanOptOut = false;
                        await msg.ReplyAsync($"You have opted into the global bans");
                    }
                    else
                    {
                        GenericBot.GuildConfigs[msg.GetGuild().Id].GlobalBanOptOut = !GenericBot.GuildConfigs[msg.GetGuild().Id].GlobalBanOptOut;
                        if (GenericBot.GuildConfigs[msg.GetGuild().Id].GlobalBanOptOut)
                        {
                            await msg.ReplyAsync($"You have opted out of the global bans");
                        }
                        else
                        {
                            await msg.ReplyAsync($"You have opted into the global bans");
                        }
                    }
                }

                #endregion GlobalBanOptOut

                #region AutoRole

                else if (paramList[0].ToLower().Equals("autoroles") || paramList[0].ToLower().Equals("autorole"))
                {
                    if (paramList.Count == 2)
                    {
                        await msg.ReplyAsync($"Please enter a roleId");

                        return;
                    }
                    if (ulong.TryParse(paramList[2], out ulong id))
                    {
                        if (paramList[1].ToLower().Equals("add"))
                        {
                            if (msg.GetGuild().Roles.Select(r => r.Id).Any(u => u.Equals(id)))
                            {
                                if (!GenericBot.GuildConfigs[msg.GetGuild().Id].AutoRoleIds.Contains(id))
                                {
                                    GenericBot.GuildConfigs[msg.GetGuild().Id].AutoRoleIds.Add(id);
                                    await msg.ReplyAsync($"Added {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} to autoroles");
                                }
                                else
                                {
                                    await msg.ReplyAsync($"Autoroles already contains {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}");
                                }
                            }
                            else
                            {
                                await msg.ReplyAsync("Invalid RoleId (Not a role)");
                            }
                        }
                        else if (paramList[1].ToLower().Equals("remove"))
                        {
                            if (GenericBot.GuildConfigs[msg.GetGuild().Id].AutoRoleIds.Contains(id))
                            {
                                {
                                    GenericBot.GuildConfigs[msg.GetGuild().Id].AutoRoleIds.Remove(id);
                                    await msg.ReplyAsync(
                                        $"Removed `{id}` from autoroles");
                                }
                            }
                            else
                            {
                                await msg.ReplyAsync(
                                    $"The autoroles don't contain `{id}`");
                            }
                        }
                        else
                        {
                            await msg.ReplyAsync($"Unknown property `{paramList[1]}`.");
                        }
                    }
                    else
                    {
                        await msg.ReplyAsync($"That is not a valid roleId");
                    }
                }

                #endregion AutoRole

                else
                {
                    await msg.ReplyAsync($"Unknown property `{paramList[0]}`.");
                }

                GenericBot.GuildConfigs[msg.GetGuild().Id].Save();
            };

            ConfigCommands.Add(config);

            Command levels = new Command(nameof(levels));
            levels.RequiredPermission = Command.PermissionLevels.Admin;
            levels.Description        = "Set the number of points to get a role";
            levels.ToExecute         += async(client, msg, parameters) =>
            {
                var guildConfig = GenericBot.GuildConfigs[msg.GetGuild().Id];
                if (parameters.Empty())
                {
                    if (guildConfig.Levels.Any(kvp => msg.GetGuild().GetRole(kvp.Value) != null))
                    {
                        string res = "";
                        foreach (var level in guildConfig.Levels.OrderBy(kvp => kvp.Key).Where(kvp => msg.GetGuild().GetRole(kvp.Value) != null))
                        {
                            var role = msg.GetGuild().GetRole(level.Value);
                            res += $"Role `{role.Name.Escape()}` at `{level.Key}` Points\n";
                        }
                        await msg.ReplyAsync(res);
                    }
                    else
                    {
                        await msg.ReplyAsync("There are no levels for this server!");
                    }
                }
                else
                {
                    if (parameters[0].ToLower() == "add")
                    {
                        if (parameters.Count == 3)
                        {
                            if (decimal.TryParse(parameters[1], out decimal pointValue) && ulong.TryParse(parameters[2], out ulong roleId) &&
                                msg.GetGuild().Roles.Any(r => r.Id == roleId))
                            {
                                var db = new DBGuild(msg.GetGuild().Id);
                                guildConfig.Levels.Add(pointValue, roleId);
                                int addedUsers = 0;
                                foreach (var user in msg.GetGuild().Users)
                                {
                                    if (db.GetUser(user.Id).PointsCount >= pointValue)
                                    {
                                        try
                                        {
                                            await user.AddRoleAsync(msg.GetGuild().GetRole(roleId));

                                            addedUsers++;
                                        }
                                        catch
                                        { }
                                    }
                                }
                                await msg.ReplyAsync($"Users will get `{msg.GetGuild().GetRole(roleId).Name.Escape()}` at `{pointValue}` points. `{addedUsers}` had the more than the number of points and have had the role assigned");
                            }
                        }
                        else
                        {
                            await msg.ReplyAsync($"The command should be formatted as `levels add pointsValue roleId`");
                        }
                    }
                    else if (parameters[0].ToLower() == "remove")
                    {
                        if (parameters.Count == 2)
                        {
                            if (ulong.TryParse(parameters[1], out ulong roleId) && guildConfig.Levels.Any(kvp => kvp.Value.Equals(roleId)))
                            {
                                guildConfig.Levels.Remove(guildConfig.Levels.First(kvp => kvp.Value.Equals(roleId)).Key);
                                await msg.ReplyAsync("Done!");
                            }
                            else
                            {
                                await msg.ReplyAsync("That is not a valid RoleId!");
                            }
                        }
                        else
                        {
                            await msg.ReplyAsync($"The command should be formatted as `levels remove roleId`");
                        }
                    }
                    guildConfig.Save();
                }
            };

            ConfigCommands.Add(levels);

            return(ConfigCommands);
        }
예제 #5
0
        public List <Command> GetModCommands()
        {
            List <Command> ModCommands = new List <Command>();

            Command clear = new Command("clear");

            clear.Description        = "Clear a number of messages from a channel";
            clear.Usage              = "clear <number> <user>";
            clear.RequiredPermission = Command.PermissionLevels.Moderator;
            clear.ToExecute         += async(client, msg, paramList) =>
            {
                if (paramList.Empty())
                {
                    await msg.ReplyAsync("You gotta tell me how many messages to delete!");

                    return;
                }

                int count;
                if (int.TryParse(paramList[0], out count))
                {
                    List <IMessage> msgs = (msg.Channel as SocketTextChannel).GetManyMessages(count).Result;
                    if (msg.GetMentionedUsers().Any())
                    {
                        var users = msg.GetMentionedUsers();
                        msgs = msgs.Where(m => users.Select(u => u.Id).Contains(m.Author.Id)).ToList();
                        msgs.Add(msg);
                    }
                    if (paramList.Count > 1 && !msg.GetMentionedUsers().Any())
                    {
                        await msg.ReplyAsync($"It looks like you're trying to mention someone but failed.");

                        return;
                    }

                    await(msg.Channel as ITextChannel).DeleteMessagesAsync(msgs.Where(m => DateTime.Now - m.CreatedAt < TimeSpan.FromDays(14)));

                    var messagesSent = new List <IMessage>();

                    messagesSent.Add(msg.ReplyAsync($"{msg.Author.Mention}, done deleting those messages!").Result);
                    if (msgs.Any(m => DateTime.Now - m.CreatedAt > TimeSpan.FromDays(14)))
                    {
                        messagesSent.Add(msg.ReplyAsync($"I couldn't delete all of them, some were older than 2 weeks old :frowning:").Result);
                    }

                    await Task.Delay(2500);

                    await(msg.Channel as ITextChannel).DeleteMessagesAsync(messagesSent);
                }
                else
                {
                    await msg.ReplyAsync("That's not a valid number");
                }
            };

            ModCommands.Add(clear);

            Command whois = new Command("whois");

            whois.Description        = "Get information about a user currently on the server from a ID or Mention";
            whois.Usage              = "whois @user";
            whois.RequiredPermission = Command.PermissionLevels.Moderator;
            whois.ToExecute         += async(client, msg, parameters) =>
            {
                await msg.GetGuild().DownloadUsersAsync();

                if (!msg.GetMentionedUsers().Any())
                {
                    await msg.ReplyAsync("No user found");

                    return;
                }
                SocketGuildUser user;
                ulong           uid = msg.GetMentionedUsers().FirstOrDefault().Id;

                if (msg.GetGuild().Users.Any(u => u.Id == uid))
                {
                    user = msg.GetGuild().GetUser(uid);
                }
                else
                {
                    await msg.ReplyAsync("User not found");

                    return;
                }

                string nickname = msg.GetGuild().Users.All(u => u.Id != uid) || string.IsNullOrEmpty(user.Nickname) ? "None" : user.Nickname;
                string roles    = "";
                foreach (var role in user.Roles.Where(r => !r.Name.Equals("@everyone")).OrderByDescending(r => r.Position))
                {
                    roles += $"`{role.Name}`, ";
                }
                DBUser  dbUser;
                DBGuild guildDb = new DBGuild(msg.GetGuild().Id);
                if (guildDb.Users.Any(u => u.ID.Equals(user.Id))) // if already exists
                {
                    dbUser = guildDb.Users.First(u => u.ID.Equals(user.Id));
                }
                else
                {
                    dbUser = new DBUser(user);
                }

                string nicks = "", usernames = "";
                if (!dbUser.Usernames.Empty())
                {
                    foreach (var str in dbUser.Usernames.Distinct().ToList())
                    {
                        usernames += $"`{str.Replace('`', '\'')}`, ";
                    }
                }
                if (!dbUser.Nicknames.Empty())
                {
                    foreach (var str in dbUser.Nicknames.Distinct().ToList())
                    {
                        nicks += $"`{str.Replace('`', '\'')}`, ";
                    }
                }
                nicks     = nicks.Trim(',', ' ');
                usernames = usernames.Trim(',', ' ');

                string info = $"User Id:  `{user.Id}`\n";
                info += $"Username: `{user.ToString()}`\n";
                info += $"Past Usernames: {usernames}\n";
                info += $"Nickname: `{nickname}`\n";
                if (!dbUser.Nicknames.Empty())
                {
                    info += $"Past Nicknames: {nicks}\n";
                }
                info += $"Created At: `{string.Format("{0:yyyy-MM-dd HH\\:mm\\:ss zzzz}", user.CreatedAt.LocalDateTime)}GMT` " +
                        $"(about {(DateTime.UtcNow - user.CreatedAt).Days} days ago)\n";
                if (user.JoinedAt.HasValue)
                {
                    info +=
                        $"Joined At: `{string.Format("{0:yyyy-MM-dd HH\\:mm\\:ss zzzz}", user.JoinedAt.Value.LocalDateTime)}GMT`" +
                        $"(about {(DateTime.UtcNow - user.JoinedAt.Value).Days} days ago)\n";
                }
                info += $"Roles: {roles.Trim(' ', ',')}\n";
                if (!dbUser.Warnings.Empty())
                {
                    info += $"`{dbUser.Warnings.Count}` Warnings: {dbUser.Warnings.reJoin(" | ")}";
                }


                foreach (var str in info.SplitSafe(','))
                {
                    await msg.ReplyAsync(str.TrimStart(','));
                }
                guildDb.Save();
            };

            ModCommands.Add(whois);

            Command find = new Command("find");

            find.Description        = "Get information about a user currently on the server from a ID or Mention";
            find.Usage              = "whois @user";
            find.RequiredPermission = Command.PermissionLevels.Moderator;
            find.ToExecute         += async(client, msg, parameters) =>
            {
                string        input   = parameters.reJoin();
                List <DBUser> dbUsers = new List <DBUser>();
                var           guildDb = new DBGuild(msg.GetGuild().Id);

                if (msg.MentionedUsers.Any())
                {
                    dbUsers.Add(guildDb.GetUser(msg.MentionedUsers.First().Id));
                }
                else if ((input.Length > 16 && input.Length < 19) && ulong.TryParse(input, out ulong id))
                {
                    dbUsers.Add(guildDb.GetUser(id));
                }
                else if (input.Length < 3 && guildDb.Users.Count > 100)
                {
                    await msg.ReplyAsync($"I can't search for that, it's dangerously short and risks a crash.");

                    return;
                }
                else
                {
                    foreach (var user in guildDb.Users)
                    {
                        try
                        {
                            if (!user.Nicknames.Empty())
                            {
                                if (user.Nicknames.Any(n => n.ToLower().Contains(input.ToLower())))
                                {
                                    dbUsers.Add(user);
                                }
                            }

                            if (!user.Usernames.Empty())
                            {
                                if (user.Usernames.Any(n => n.ToLower().Contains(input.ToLower())))
                                {
                                    dbUsers.Add(user);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            foreach (var u in guildDb.Users)
                            {
                                if (!u.Nicknames.Empty())
                                {
                                    user.Nicknames = user.Nicknames.Where(n => !string.IsNullOrEmpty(n)).ToList();
                                }

                                if (!u.Usernames.Empty())
                                {
                                    user.Usernames = user.Usernames.Where(n => !string.IsNullOrEmpty(n)).ToList();
                                }
                            }
                            if (new Command("test").GetPermissions(msg.Author, msg.GetGuild().Id) >= Command.PermissionLevels.GlobalAdmin)
                            {
                                await msg.ReplyAsync($"```\n{ex.Message}\n{ex.StackTrace}\n{user.ID} : {user.Usernames.Count} | {user.Nicknames.Count}\n```");
                            }
                        }
                    }
                    dbUsers = dbUsers.Distinct().ToList();
                }

                if (dbUsers.Count > 5)
                {
                    string info =
                        $"Found `{dbUsers.Count}` users. Their first stored usernames are:\n{dbUsers.Select(u => $"`{u.Usernames.First()}`").ToList().SumAnd()}" +
                        $"\nTry using more precise search parameters";
                    foreach (var user in dbUsers)
                    {
                        if (user.Usernames.First().ToLower().Equals(input.ToLower()))
                        {
                            info = info.Replace($"`{user.Usernames.First()}`", $"`{user.Usernames.First()}` (`{user.ID}`)");
                        }
                    }
                    foreach (var str in info.SplitSafe(','))
                    {
                        await msg.ReplyAsync(str.TrimStart(','));
                    }

                    return;
                }
                else if (dbUsers.Count == 0)
                {
                    await msg.ReplyAsync($"No users found");
                }

                foreach (var dbUser in dbUsers)
                {
                    string nicks = "", usernames = "";
                    if (dbUser.Usernames != null && !dbUser.Usernames.Empty())
                    {
                        usernames = dbUser.Usernames.Distinct().Select(n => $"`{n.Replace("`", "'")}`").ToList().SumAnd();
                    }

                    if (dbUser.Nicknames != null && !dbUser.Nicknames.Empty())
                    {
                        nicks = dbUser.Nicknames.Distinct().Select(n => $"`{n.Replace("`", "'")}`").ToList().SumAnd();
                    }


                    string info = $"User: <@!{dbUser.ID}>\nUser Id:  `{dbUser.ID}`\n";
                    info += $"Past Usernames: {usernames}\n";
                    info += $"Past Nicknames: {nicks}\n";
                    SocketGuildUser user = msg.GetGuild().GetUser(dbUser.ID);
                    if (user != null && user.Id != msg.Author.Id)
                    {
                        info +=
                            $"Created At: `{string.Format("{0:yyyy-MM-dd HH\\:mm\\:ss zzzz}", user.CreatedAt.LocalDateTime)}GMT` " +
                            $"(about {(DateTime.UtcNow - user.CreatedAt).Days} days ago)\n";
                    }

                    if (user != null && user.Id != msg.Author.Id && user.JoinedAt.HasValue)
                    {
                        info +=
                            $"Joined At: `{string.Format("{0:yyyy-MM-dd HH\\:mm\\:ss zzzz}", user.JoinedAt.Value.LocalDateTime)}GMT`" +
                            $"(about {(DateTime.UtcNow - user.JoinedAt.Value).Days} days ago)\n";
                    }
                    if (dbUser.Warnings != null && !dbUser.Warnings.Empty())
                    {
                        info += $"`{dbUser.Warnings.Count}` Warnings: {dbUser.Warnings.SumAnd()}";
                    }

                    foreach (var str in info.SplitSafe(','))
                    {
                        await msg.ReplyAsync(str.TrimStart(','));
                    }
                }
            };

            ModCommands.Add(find);

            Command addwarning = new Command("addwarning");

            addwarning.Description       += "Add a warning to the database";
            addwarning.Usage              = "addwarning <user> <warning>";
            addwarning.RequiredPermission = Command.PermissionLevels.Moderator;
            addwarning.ToExecute         += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync("You must specify a user");

                    return;
                }
                ulong uid;
                if (ulong.TryParse(parameters[0].TrimStart('<', '@', '!').TrimEnd('>'), out uid))
                {
                    parameters.RemoveAt(0);
                    string warning = parameters.reJoin();
                    warning += $" (By `{msg.Author}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)";
                    DBGuild guildDb = new DBGuild(msg.GetGuild().Id);
                    if (guildDb.Users.Any(u => u.ID.Equals(uid))) // if already exists
                    {
                        guildDb.Users.Find(u => u.ID.Equals(uid)).AddWarning(warning);
                    }
                    else
                    {
                        guildDb.Users.Add(new DBUser {
                            ID = uid, Warnings = new List <string> {
                                warning
                            }
                        });
                    }
                    guildDb.Save();

                    var builder = new EmbedBuilder()
                                  .WithTitle("Warning Added")
                                  .WithDescription(warning)
                                  .WithColor(new Color(0xFFFF00))
                                  .WithFooter(footer =>
                    {
                        footer
                        .WithText($"By {msg.Author} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                    });

                    try
                    {
                        var user = client.GetUser(uid);
                        builder.Author = new EmbedAuthorBuilder().WithName(user.ToString()).WithIconUrl(user.GetAvatarUrl());
                    }
                    catch
                    {
                        builder.Author = new EmbedAuthorBuilder().WithName(uid.ToString());
                    }


                    await msg.Channel.SendMessageAsync("", embed : builder.Build());

                    if (GenericBot.GuildConfigs[msg.GetGuild().Id].UserLogChannelId != 0)
                    {
                        await((SocketTextChannel)client.GetChannel(GenericBot.GuildConfigs[msg.GetGuild().Id].UserLogChannelId))
                        .SendMessageAsync("", embed: builder.Build());
                    }
                }
                else
                {
                    await msg.ReplyAsync("Could not find that user");
                }
            };

            ModCommands.Add(addwarning);

            Command issuewarning = new Command("issuewarning");

            issuewarning.Description       += "Add a warning to the database and send it to the user";
            issuewarning.Usage              = "issuewarning <user> <warning>";
            issuewarning.RequiredPermission = Command.PermissionLevels.Moderator;
            issuewarning.ToExecute         += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync("You must specify a user");

                    return;
                }
                if (msg.GetMentionedUsers().Any())
                {
                    var user = msg.GetMentionedUsers().First();
                    if (!msg.GetGuild().Users.Any(u => u.Id.Equals(user.Id)))
                    {
                        await msg.ReplyAsync("Could not find that user");

                        return;
                    }
                    parameters.RemoveAt(0);
                    string warning = parameters.reJoin();
                    warning += $" (By `{msg.Author}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)";
                    DBGuild guildDb = new DBGuild(msg.GetGuild().Id);
                    if (guildDb.Users.Any(u => u.ID.Equals(user.Id))) // if already exists
                    {
                        guildDb.Users.Find(u => u.ID.Equals(user.Id)).AddWarning(warning);
                    }
                    else
                    {
                        guildDb.Users.Add(new DBUser {
                            ID = user.Id, Warnings = new List <string> {
                                warning
                            }
                        });
                    }
                    guildDb.Save();
                    try
                    {
                        await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(
                            $"The Moderator team of **{msg.GetGuild().Name}** has issued you the following warning:\n{parameters.reJoin()}");
                    }
                    catch (Exception ex)
                    {
                        warning += $"\nCould not message {user}";
                    }

                    var builder = new EmbedBuilder()
                                  .WithTitle("Warning Issued")
                                  .WithDescription(warning)
                                  .WithColor(new Color(0xFFFF00))
                                  .WithFooter(footer =>
                    {
                        footer
                        .WithText($"By {msg.Author} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                    });
                    builder.Author = new EmbedAuthorBuilder().WithName(user.ToString()).WithIconUrl(user.GetAvatarUrl());

                    await msg.Channel.SendMessageAsync("", embed : builder.Build());

                    if (GenericBot.GuildConfigs[msg.GetGuild().Id].UserLogChannelId != 0)
                    {
                        await((SocketTextChannel)client.GetChannel(GenericBot.GuildConfigs[msg.GetGuild().Id].UserLogChannelId))
                        .SendMessageAsync("", embed: builder.Build());
                    }
                }
                else
                {
                    await msg.ReplyAsync("Could not find that user");
                }
            };

            ModCommands.Add(issuewarning);

            Command removeWarning = new Command("removeWarning");

            removeWarning.RequiredPermission = Command.PermissionLevels.Moderator;
            removeWarning.Usage       = "removewarning <user>";
            removeWarning.Description = "Remove the last warning from a user";
            removeWarning.ToExecute  += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync($"You need to add some arguments. A user, perhaps?");

                    return;
                }

                bool removeAll = false;
                if (parameters[0].ToLower().Equals("all"))
                {
                    removeAll = true;
                    parameters.RemoveAt(0);
                }

                ulong uid;
                if (ulong.TryParse(parameters[0].TrimStart('<', '@', '!').TrimEnd('>'), out uid))
                {
                    var guilddb = new DBGuild(msg.GetGuild().Id);
                    if (guilddb.GetUser(uid).RemoveWarning(allWarnings: removeAll))
                    {
                        await msg.ReplyAsync($"Done!");
                    }
                    else
                    {
                        await msg.ReplyAsync("User had no warnings");
                    }
                    guilddb.Save();
                }
                else
                {
                    await msg.ReplyAsync($"No user found");
                }
            };

            ModCommands.Add(removeWarning);

            Command mute = new Command("mute");

            mute.RequiredPermission = Command.PermissionLevels.Moderator;
            mute.Usage       = "mute <user>";
            mute.Description = "Mute a user";
            mute.ToExecute  += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync($"You need to specify a user!");

                    return;
                }
                var gc = GenericBot.GuildConfigs[msg.GetGuild().Id];
                if (!msg.GetGuild().Roles.Any(r => r.Id == gc.MutedRoleId))
                {
                    await msg.ReplyAsync("The Muted Role Id is configured incorrectly. Please talk to your server admin");

                    return;
                }
                var          mutedRole  = msg.GetGuild().Roles.First(r => r.Id == gc.MutedRoleId);
                List <IUser> mutedUsers = new List <IUser>();
                foreach (var user in msg.GetMentionedUsers().Select(u => u.Id))
                {
                    try
                    {
                        (msg.GetGuild().GetUser(user)).AddRolesAsync(new List <IRole> {
                            mutedRole
                        });
                        gc.ProbablyMutedUsers.Add(user);
                        gc.Save();
                        mutedUsers.Add(msg.GetGuild().GetUser(user));
                    }
                    catch
                    {
                    }
                }

                string res = "Succesfully muted " + mutedUsers.Select(u => u.Mention).ToList().SumAnd();

                await msg.ReplyAsync(res);
            };

            ModCommands.Add(mute);

            Command unmute = new Command("unmute");

            unmute.RequiredPermission = Command.PermissionLevels.Moderator;
            unmute.Usage       = "unmute <user>";
            unmute.Description = "Unmute a user";
            unmute.ToExecute  += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync($"You need to specify a user!");

                    return;
                }
                var gc = GenericBot.GuildConfigs[msg.GetGuild().Id];
                if (!msg.GetGuild().Roles.Any(r => r.Id == gc.MutedRoleId))
                {
                    await msg.ReplyAsync("The Muted Role Id is configured incorrectly. Please talk to your server admin");

                    return;
                }
                var          mutedRole  = msg.GetGuild().Roles.First(r => r.Id == gc.MutedRoleId);
                List <IUser> mutedUsers = new List <IUser>();
                foreach (var user in msg.GetMentionedUsers().Select(u => u.Id))
                {
                    try
                    {
                        (msg.GetGuild().GetUser(user)).RemoveRoleAsync(mutedRole);
                        gc.ProbablyMutedUsers.Remove(user);
                        mutedUsers.Add(msg.GetGuild().GetUser(user));
                    }
                    catch
                    {
                    }
                }
                gc.Save();

                string res = "Succesfully unmuted ";
                for (int i = 0; i < mutedUsers.Count; i++)
                {
                    if (i == mutedUsers.Count - 1 && mutedUsers.Count > 1)
                    {
                        res += $"and {mutedUsers.ElementAt(i).Mention}";
                    }
                    else
                    {
                        res += $"{mutedUsers.ElementAt(i).Mention}, ";
                    }
                }

                await msg.ReplyAsync(res.TrimEnd(',', ' '));
            };

            ModCommands.Add(unmute);

            Command archive = new Command("archive");

            archive.RequiredPermission = Command.PermissionLevels.Admin;
            archive.Description        = "Save all the messages from a text channel";
            archive.ToExecute         += async(client, msg, parameters) =>
            {
                var msgs = (msg.Channel as SocketTextChannel).GetManyMessages(50000).Result;

                var    channel = msg.Channel;
                string str     = $"{((IGuildChannel)channel).Guild.Name} | {((IGuildChannel)channel).Guild.Id}\n";
                str += $"#{channel.Name} | {channel.Id}\n";
                str += $"{DateTime.Now}\n\n";

                IMessage lastMsg = null;
                msgs.Reverse();
                msgs.Remove(msg);
                foreach (var m in msgs)
                {
                    string msgstr = $"{m.Id}\n";
                    if (lastMsg != null && m.Author.Id != lastMsg.Author.Id)
                    {
                        msgstr += $"{m.Author} | {m.Author.Id}\n{m.Timestamp}\n";
                    }
                    msgstr += $"{m.Content}\n";
                    foreach (var a in m.Attachments)
                    {
                        msgstr += $"{a.Url}\n";
                    }
                    str    += msgstr + "\n";
                    lastMsg = m;
                }

                string filename = $"{channel.Name}.txt";
                File.WriteAllText("files/" + filename, str);
                await msg.Channel.SendFileAsync("files/" + filename, $"Here you go! I saved {msgs.Count()} messages");
            };

            ModCommands.Add(archive);

            return(ModCommands);
        }
예제 #6
0
        public List <Command> GetBanCommands()
        {
            List <Command> banCommands = new List <Command>();

            Command globalBan = new Command("globalBan");

            globalBan.RequiredPermission = Command.PermissionLevels.BotOwner;
            globalBan.Description        = "Ban someone from every server the bot is currently on";
            globalBan.ToExecute         += async(client, msg, parameters) =>
            {
                if (!ulong.TryParse(parameters[0], out ulong userId))
                {
                    await msg.ReplyAsync($"Invalid UserId");

                    return;
                }

                if (parameters.Count <= 1)
                {
                    await msg.ReplyAsync($"Need a reasono and/or userId");

                    return;
                }

                string reason = $"Globally banned for: {parameters.reJoin()}";

                int succ = 0, fail = 0, opt = 0;
                GenericBot.GlobalConfiguration.BlacklistedIds.Add(userId);
                foreach (var guild in client.Guilds)
                {
                    if (GenericBot.GuildConfigs[guild.Id].GlobalBanOptOut)
                    {
                        opt++;
                        continue;
                    }

                    try
                    {
                        await guild.AddBanAsync(userId, 0, reason);

                        succ++;
                    }
                    catch
                    {
                        fail++;
                    }
                }

                string repl =
                    $"Result: Banned `{msg.GetGuild().GetBansAsync().Result.First(b => b.User.Id == userId).User}` for `{reason}`\n";
                repl += $"\nSuccesses: `{succ}`\nFailures: `{fail}`\nOpt-Outs: `{opt}`";

                await msg.ReplyAsync(repl);
            };

            banCommands.Add(globalBan);

            Command unban = new Command("unban");

            unban.Description        = "Unban a user given their ID";
            unban.RequiredPermission = Command.PermissionLevels.Moderator;
            unban.Usage      = "unban <userId";
            unban.ToExecute += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync("Please specify a userid to unban");

                    return;
                }
                GuildConfig gc = GenericBot.GuildConfigs[msg.GetGuild().Id];
                if (ulong.TryParse(parameters[0], out ulong bannedUId) && gc.Bans.HasElement(b => b.Id == bannedUId, out GenericBan banToRemove))
                {
                    gc.Bans.Remove(banToRemove);
                    gc.Save();
                    try
                    {
                        var user = msg.GetGuild().GetBansAsync().Result.First(b => b.User.Id == bannedUId).User;
                        await msg.GetGuild().RemoveBanAsync(bannedUId);

                        await msg.ReplyAsync($"Succesfully unbanned `{user}` (`{user.Id}`)");

                        var builder = new EmbedBuilder()
                                      .WithTitle("User Unbanned")
                                      .WithDescription($"Banned for: {banToRemove.Reason}")
                                      .WithColor(new Color(0xFFFF00))
                                      .WithFooter(footer => {
                            footer
                            .WithText($"{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                        })
                                      .WithAuthor(author => {
                            author
                            .WithName(user.ToString())
                            .WithIconUrl(user.GetAvatarUrl());
                        })
                                      .AddField(new EmbedFieldBuilder().WithName("All Warnings").WithValue(
                                                    new DBGuild(msg.GetGuild().Id).GetUser(user.Id).Warnings.SumAnd()));

                        await((SocketTextChannel)GenericBot.DiscordClient.GetChannel(gc.UserLogChannelId))
                        .SendMessageAsync("", embed: builder.Build());
                    }
                    catch (Discord.Net.HttpException httpException)
                    {
                        await GenericBot.Logger.LogErrorMessage(httpException.Message + "\n" + httpException.StackTrace);

                        await msg.ReplyAsync("Could not unban that user. Either I don't have the permissions or they weren't banned");
                    }
                }
            };

            banCommands.Add(unban);

            Command ban = new Command("ban");

            ban.Description        = "Ban a user from the server, whether or not they're on it";
            ban.Delete             = false;
            ban.RequiredPermission = Command.PermissionLevels.Moderator;
            ban.Usage      = $"{ban.Name} <user> <time> <reason>";
            ban.ToExecute += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync($"You need to add some arguments. A user, perhaps?");

                    return;
                }

                ulong uid;
                if (ulong.TryParse(parameters[0].TrimStart('<', '@', '!').TrimEnd('>'), out uid))
                {
                    if (uid == client.GetApplicationInfoAsync().Result.Owner.Id)
                    {
                        await msg.ReplyAsync("Haha lol no");

                        return;
                    }

                    parameters.RemoveAt(0);
                    var time = new DateTimeOffset();

                    try
                    {
                        if (parameters[0] == "0" || parameters[0] == "0d")
                        {
                            time = DateTimeOffset.MaxValue;
                        }
                        else
                        {
                            time = parameters[0].ParseTimeString();
                        }
                        parameters.RemoveAt(0);
                    }
                    catch (System.FormatException ex)
                    { time = DateTimeOffset.MaxValue; }
                    var tmsg = time == DateTimeOffset.MaxValue ? "permanently" : $"for `{(time.AddSeconds(1) - DateTimeOffset.UtcNow).FormatTimeString()}`";

                    string reason = parameters.reJoin();
                    var    bans   = msg.GetGuild().GetBansAsync().Result;
                    if (bans.Any(b => b.User.Id == uid))
                    {
                        await msg.ReplyAsync(
                            $"`{bans.First(b => b.User.Id == uid).User}` is already banned for `{bans.First(b => b.User.Id == uid).Reason}`");
                    }
                    else
                    {
                        bool   dmSuccess = true;
                        string dmMessage = $"You have been banned from **{msg.GetGuild().Name}** ";
                        dmMessage += tmsg;
                        if (!string.IsNullOrEmpty(reason))
                        {
                            dmMessage += $" for the following reason: \n\n{reason}\n\n";
                        }
                        try
                        {
                            await msg.GetGuild().GetUser(uid).GetOrCreateDMChannelAsync().Result
                            .SendMessageAsync(dmMessage);
                        }
                        catch
                        {
                            dmSuccess = false;
                        }

                        try
                        {
                            string areason = reason.Replace("\"", "'");
                            if (areason.Length > 256)
                            {
                                areason = areason.Substring(0, 250) + "...";
                            }
                            await msg.GetGuild().AddBanAsync(uid, reason: areason);
                        }
                        catch
                        {
                            await msg.ReplyAsync($"Could not ban the given user. Try checking role hierarchy and permissions");

                            return;
                        }

                        bans = msg.GetGuild().GetBansAsync().Result;
                        var    user       = bans.First(u => u.User.Id == uid).User;
                        string banMessage = $"Banned `{user}` (`{user.Id}`)";
                        if (string.IsNullOrEmpty(reason))
                        {
                            banMessage += $" 👌";
                        }
                        else
                        {
                            banMessage += $" for `{reason}`";
                        }
                        banMessage += $"{tmsg} 👌";

                        if (!dmSuccess)
                        {
                            banMessage += "\nThe user could not be messaged";
                        }

                        var builder = new EmbedBuilder()
                                      .WithTitle("User Banned")
                                      .WithDescription(banMessage)
                                      .WithColor(new Color(0xFFFF00))
                                      .WithFooter(footer => {
                            footer
                            .WithText($"By {msg.Author} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                        })
                                      .WithAuthor(author => {
                            author
                            .WithName(user.ToString())
                            .WithIconUrl(user.GetAvatarUrl());
                        });

                        var guilddb     = new DBGuild(msg.GetGuild().Id);
                        var guildconfig = GenericBot.GuildConfigs[msg.GetGuild().Id];
                        guildconfig.Bans.Add(
                            new GenericBan(user.Id, msg.GetGuild().Id, reason, time));
                        guildconfig.ProbablyMutedUsers.Remove(user.Id);
                        string t = tmsg;

                        guildconfig.Save();
                        guilddb.GetUser(user.Id)
                        .AddWarning(
                            $"Banned {t} for `{reason}` (By `{msg.Author}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)");
                        guilddb.Save();

                        await msg.Channel.SendMessageAsync("", embed : builder.Build());

                        if (guildconfig.UserLogChannelId != 0)
                        {
                            await(client.GetChannel(guildconfig.UserLogChannelId) as SocketTextChannel)
                            .SendMessageAsync("", embed: builder.Build());
                        }
                    }
                }
                else
                {
                    await msg.ReplyAsync("Try specifying someone to ban first");
                }
            };

            banCommands.Add(ban);

            Command pban = new Command("purgeban");

            pban.Description        = "Ban a user from the server, whether or not they're in it, and delete the last day of their  messages";
            pban.Delete             = false;
            pban.RequiredPermission = Command.PermissionLevels.Moderator;
            pban.Usage      = $"{pban.Name} <user> <time in days> <reason>";
            pban.ToExecute += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync($"You need to add some arguments. A user, perhaps?");

                    return;
                }

                ulong uid;
                if (ulong.TryParse(parameters[0].TrimStart('<', '@', '!').TrimEnd('>'), out uid))
                {
                    if (uid == client.GetApplicationInfoAsync().Result.Owner.Id)
                    {
                        await msg.ReplyAsync("Haha lol no");

                        return;
                    }

                    parameters.RemoveAt(0);
                    var time = new DateTimeOffset();

                    try
                    {
                        if (parameters[0] == "0" || parameters[0] == "0d")
                        {
                            time = DateTimeOffset.MaxValue;
                        }
                        else
                        {
                            time = parameters[0].ParseTimeString();
                        }
                        parameters.RemoveAt(0);
                    }
                    catch (System.FormatException ex)
                    { time = DateTimeOffset.MaxValue; }

                    var tmsg = time == DateTimeOffset.MaxValue ? "permanently" : $"for `{(time.AddSeconds(1) - DateTimeOffset.UtcNow).FormatTimeString()}`";

                    string reason = parameters.reJoin();
                    var    bans   = msg.GetGuild().GetBansAsync().Result;
                    if (bans.Any(b => b.User.Id == uid))
                    {
                        await msg.ReplyAsync(
                            $"`{bans.First(b => b.User.Id == uid).User}` is already banned for `{bans.First(b => b.User.Id == uid).Reason}`");
                    }
                    else
                    {
                        bool   dmSuccess = true;
                        string dmMessage = $"You have been banned from **{msg.GetGuild().Name}** ";
                        dmMessage += tmsg;
                        if (!string.IsNullOrEmpty(reason))
                        {
                            dmMessage += $" for the following reason: \n\n{reason}\n\n";
                        }
                        try
                        {
                            await msg.GetGuild().GetUser(uid).GetOrCreateDMChannelAsync().Result
                            .SendMessageAsync(dmMessage);
                        }
                        catch
                        {
                            dmSuccess = false;
                        }

                        try
                        {
                            string areason = reason.Replace("\"", "'");
                            if (areason.Length > 256)
                            {
                                areason = areason.Substring(0, 250) + "...";
                            }
                            await msg.GetGuild().AddBanAsync(uid, reason: areason, pruneDays: 1);
                        }
                        catch
                        {
                            await msg.ReplyAsync($"Could not ban the given user. Try checking role hierarchy and permissions");

                            return;
                        }

                        bans = msg.GetGuild().GetBansAsync().Result;
                        var    user       = bans.First(u => u.User.Id == uid).User;
                        string banMessage = $"Banned `{user}` (`{user.Id}`)";
                        if (string.IsNullOrEmpty(reason))
                        {
                            banMessage += $" 👌";
                        }
                        else
                        {
                            banMessage += $" for `{reason}`";
                        }
                        banMessage += $"{tmsg} 👌";

                        if (!dmSuccess)
                        {
                            banMessage += "\nThe user could not be messaged";
                        }

                        var builder = new EmbedBuilder()
                                      .WithTitle("User Banned")
                                      .WithDescription(banMessage)
                                      .WithColor(new Color(0xFFFF00))
                                      .WithFooter(footer => {
                            footer
                            .WithText($"By {msg.Author} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                        })
                                      .WithAuthor(author => {
                            author
                            .WithName(user.ToString())
                            .WithIconUrl(user.GetAvatarUrl());
                        });

                        var guilddb     = new DBGuild(msg.GetGuild().Id);
                        var guildconfig = GenericBot.GuildConfigs[msg.GetGuild().Id];
                        guildconfig.Bans.Add(
                            new GenericBan(user.Id, msg.GetGuild().Id, reason, time));
                        guildconfig.ProbablyMutedUsers.Remove(user.Id);
                        string t = tmsg;

                        guildconfig.Save();
                        guilddb.GetUser(user.Id)
                        .AddWarning(
                            $"Banned {t} for `{reason}` (By `{msg.Author}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)");
                        guilddb.Save();

                        await msg.Channel.SendMessageAsync("", embed : builder.Build());

                        if (guildconfig.UserLogChannelId != 0)
                        {
                            await(client.GetChannel(guildconfig.UserLogChannelId) as SocketTextChannel)
                            .SendMessageAsync("", embed: builder.Build());
                        }
                    }
                }
                else
                {
                    await msg.ReplyAsync("Try specifying someone to ban first");
                }
            };

            banCommands.Add(pban);


            Command kick = new Command("kick");

            kick.Description        = "kick a user from the server, whether or not they're on it";
            kick.Delete             = false;
            kick.RequiredPermission = Command.PermissionLevels.Moderator;
            kick.Usage      = $"{kick.Name} <user> <reason>";
            kick.ToExecute += async(client, msg, parameters) =>
            {
                if (!msg.GetMentionedUsers().Any())
                {
                    await msg.ReplyAsync($"You need to specify a user to kick");

                    return;
                }

                var user = msg.GetMentionedUsers().First();
                parameters.RemoveAt(0);
                if (user.Id == client.GetApplicationInfoAsync().Result.Owner.Id)
                {
                    await msg.ReplyAsync("Haha lol no");

                    return;
                }

                string reason = parameters.reJoin();

                bool   dmSuccess = true;
                string dmMessage = $"You have been kicked from **{msg.GetGuild().Name}**";
                if (!string.IsNullOrEmpty(reason))
                {
                    dmMessage += $" for the following reason: \n\n{reason}\n\n";
                }
                try
                {
                    await msg.GetGuild().GetUser(user.Id).GetOrCreateDMChannelAsync().Result
                    .SendMessageAsync(dmMessage);
                }
                catch
                {
                    dmSuccess = false;
                }

                try
                {
                    await msg.GetGuild().GetUser(user.Id).KickAsync();
                }
                catch
                {
                    await msg.ReplyAsync($"Could not ban the given user. Try checking role hierarchy and permissions");

                    return;
                }

                string kickMessage = $"Kicked `{user}` (`{user.Id}`)";
                if (!string.IsNullOrEmpty(reason))
                {
                    kickMessage += $" for `{reason}`";
                }

                if (!dmSuccess)
                {
                    kickMessage += "\nThe user could not be messaged";
                }

                var builder = new EmbedBuilder()
                              .WithTitle("User Kicked")
                              .WithDescription(kickMessage)
                              .WithColor(new Color(0xFFFF00))
                              .WithFooter(footer => {
                    footer
                    .WithText($"By {msg.Author} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                })
                              .WithAuthor(author => {
                    author
                    .WithName(user.ToString())
                    .WithIconUrl(user.GetAvatarUrl());
                });

                var guilddb     = new DBGuild(msg.GetGuild().Id);
                var guildconfig = GenericBot.GuildConfigs[msg.GetGuild().Id];
                guildconfig.ProbablyMutedUsers.Remove(user.Id);
                guildconfig.Save();
                guilddb.GetUser(user.Id)
                .AddWarning(
                    $"Kicked for `{reason}` (By `{msg.Author}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)");
                guilddb.Save();

                await msg.Channel.SendMessageAsync("", embed : builder.Build());

                if (guildconfig.UserLogChannelId != 0)
                {
                    await(client.GetChannel(guildconfig.UserLogChannelId) as SocketTextChannel)
                    .SendMessageAsync("", embed: builder.Build());
                }
            };

            banCommands.Add(kick);


            return(banCommands);
        }
예제 #7
0
        public static async Task MessageRecieved(SocketMessage parameterMessage, bool edited = false)
        {
            // Don't handle the command if it is a system message
            var message = parameterMessage;

            if (GenericBot.GlobalConfiguration.BlacklistedIds.Contains(message.Author.Id))
            {
                return;
            }

            if (parameterMessage.Author.Id == GenericBot.DiscordClient.CurrentUser.Id)
            {
                return;
            }

            if (parameterMessage.Channel.GetType().FullName.ToLower().Contains("dmchannel"))
            {
                var msg = GenericBot.DiscordClient.GetApplicationInfoAsync().Result.Owner.GetOrCreateDMChannelAsync().Result
                          .SendMessageAsync($"```\nDM from: {message.Author}({message.Author.Id})\nContent: {message.Content}\n```").Result;
                if (parameterMessage.Content.Trim().Split().Length == 1)
                {
                    var guild = VerificationEngine.GetGuildFromCode(parameterMessage.Content, message.Author.Id);
                    if (guild == null)
                    {
                        await message.ReplyAsync("Invalid verification code");
                    }
                    else
                    {
                        await guild.GetUser(message.Author.Id)
                        .AddRoleAsync(guild.GetRole(GenericBot.GuildConfigs[guild.Id].VerifiedRole));

                        if (guild.TextChannels.HasElement(c => c.Id == (GenericBot.GuildConfigs[guild.Id].UserLogChannelId), out SocketTextChannel logChannel))
                        {
                            logChannel.SendMessageAsync($"`{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")}`:  `{message.Author}` (`{message.Author.Id}`) just verified");
                        }
                        await message.ReplyAsync($"You've been verified on **{guild.Name}**!");

                        await msg.ModifyAsync(m =>
                                              m.Content = $"```\nDM from: {message.Author}({message.Author.Id})\nContent: {message.Content.SafeSubstring(1900)}\nVerified on {guild.Name}\n```");
                    }
                }
            }

            new DBGuild(message.GetGuild().Id).Users.Find(u => u.ID.Equals(message.Author.Id)).AddUsername(message.Author.Username);
            new DBGuild(message.GetGuild().Id).Users.Find(u => u.ID.Equals(message.Author.Id)).AddNickname(message.Author as SocketGuildUser);

            if (!edited)
            {
                //new GuildMessageStats(parameterMessage.GetGuild().Id).AddMessage(parameterMessage.Author.Id).Save();
            }

            if (parameterMessage.Author.Id != GenericBot.DiscordClient.CurrentUser.Id &&
                GenericBot.GuildConfigs[parameterMessage.GetGuild().Id].FourChannelId == parameterMessage.Channel.Id)
            {
                await parameterMessage.DeleteAsync();

                await parameterMessage.ReplyAsync(
                    $"**[Anonymous]** {string.Format("{0:yyyy-MM-dd HH\\:mm\\:ss}", DateTimeOffset.UtcNow)}\n{parameterMessage.Content}");
            }

            System.Threading.Thread pointThread = new System.Threading.Thread(() =>
            {
                try
                {
                    lock (message.GetGuild().Id.ToString())
                    {
                        DBGuild db = new DBGuild(message.GetGuild().Id);
                        if (db.Users == null)
                        {
                            return;
                        }
                        if (!edited)
                        {
                            db.GetUser(message.Author.Id).PointsCount += (decimal)(.01);
                            if (GenericBot.GuildConfigs[message.GetGuild().Id].Levels.Any(kvp => kvp.Key <= db.GetUser(message.Author.Id).PointsCount))
                            {
                                foreach (var level in GenericBot.GuildConfigs[message.GetGuild().Id].Levels
                                         .Where(kvp => kvp.Key <= db.GetUser(message.Author.Id).PointsCount)
                                         .Where(kvp => !(message.Author as SocketGuildUser).Roles.Any(r => r.Id.Equals(kvp.Value))))
                                {
                                    (message.Author as SocketGuildUser).AddRoleAsync(message.GetGuild().GetRole(level.Value));
                                }
                            }
                        }
                        var thanksRegex = new Regex(@"(\b)((thanks?)|(thx)|(ty))(\b)", RegexOptions.IgnoreCase);
                        if (thanksRegex.IsMatch(message.Content) && GenericBot.GuildConfigs[message.GetGuild().Id].PointsEnabled && message.MentionedUsers.Any())
                        {
                            if (new DBGuild(message.GetGuild().Id).GetUser(message.Author.Id).LastThanks.AddMinutes(1) < DateTimeOffset.UtcNow)
                            {
                                List <IUser> givenUsers = new List <IUser>();
                                foreach (var user in message.MentionedUsers)
                                {
                                    if (user.Id == message.Author.Id)
                                    {
                                        continue;
                                    }

                                    db.GetUser(user.Id).PointsCount++;
                                    givenUsers.Add(user);
                                }
                                if (givenUsers.Any())
                                {
                                    message.ReplyAsync($"{givenUsers.Select(us => $"**{(us as SocketGuildUser).GetDisplayName()}**").ToList().SumAnd()} recieved a {GenericBot.GuildConfigs[message.GetGuild().Id].PointsName} of thanks from **{(message.Author as SocketGuildUser).GetDisplayName()}**");
                                    db.GetUser(message.Author.Id).LastThanks = DateTimeOffset.UtcNow;
                                }
                                else
                                {
                                    message.ReplyAsync("You can't give yourself a point!");
                                }
                            }
                        }
                        db.Save();
                    }
                }
                catch (Exception ex)
                {
                    //GenericBot.Logger.LogErrorMessage($"{ex.Message}\nGuild:{message.GetGuild().Name} | {message.GetGuild().Id}\nChannel:{message.Channel.Name} | {message.Channel.Id}\nUser:{message.Author} | {message.Author.Id}\n{message.Content}");
                }
            });
            pointThread.IsBackground = true;
            pointThread.Start();


            GenericBot.QuickWatch.Restart();
            try
            {
                var commandInfo = CommandHandler.ParseMessage(parameterMessage);

                CustomCommand custom = new CustomCommand();

                if (parameterMessage.Channel is IDMChannel)
                {
                    goto DMChannel;
                }

                if (GenericBot.GuildConfigs[parameterMessage.GetGuild().Id].CustomCommands
                    .HasElement(c => c.Name == commandInfo.Name, out custom) ||
                    GenericBot.GuildConfigs[parameterMessage.GetGuild().Id].CustomCommands
                    .HasElement(c => c.Aliases.Any(a => a.Equals(commandInfo.Name)), out custom))
                {
                    if (custom.Delete)
                    {
                        await parameterMessage.DeleteAsync();
                    }
                    await parameterMessage.ReplyAsync(custom.Response);

                    //new GuildMessageStats(parameterMessage.GetGuild().Id).AddCommand(parameterMessage.Author.Id, custom.Name).Save();
                }

DMChannel:
                GenericBot.LastCommand = commandInfo;
                commandInfo.Command.ExecuteCommand(GenericBot.DiscordClient, message, commandInfo.Parameters).FireAndForget();
                GenericBot.Logger.LogGenericMessage($"Guild: {parameterMessage.GetGuild().Name} ({parameterMessage.GetGuild().Id}) Channel: {parameterMessage.Channel.Name} ({parameterMessage.Channel.Id}) User: {parameterMessage.Author} ({parameterMessage.Author.Id}) Command: {commandInfo.Command.Name} Parameters {JsonConvert.SerializeObject(commandInfo.Parameters)}");
                //new GuildMessageStats(parameterMessage.GetGuild().Id).AddCommand(parameterMessage.Author.Id, commandInfo.Command.Name).Save();
            }
            catch (NullReferenceException nullRefEx)
            {
            }
            catch (Exception ex)
            {
                if (parameterMessage.Author.Id == GenericBot.GlobalConfiguration.OwnerId)
                {
                    await parameterMessage.ReplyAsync("```\n" + $"{ex.Message}\n{ex.StackTrace}".SafeSubstring(1000) +
                                                      "\n```");
                }
                await GenericBot.Logger.LogErrorMessage(ex.Message);

                //else Console.WriteLine($"{ex.Message}\n{ex.StackTrace}");
            }
        }