コード例 #1
0
 public static async Task UserUpdated(SocketGuildUser beforeUser, SocketGuildUser afterUser)
 {
     if (beforeUser.Username != afterUser.Username || beforeUser.Nickname != afterUser.Nickname)
     {
         var guildDb = new DBGuild(afterUser.Guild.Id);
         if (guildDb.Users.Any(u => u.ID.Equals(afterUser.Id))) // if already exists
         {
             guildDb.Users.Find(u => u.ID.Equals(afterUser.Id)).AddUsername(beforeUser.Username);
             guildDb.Users.Find(u => u.ID.Equals(afterUser.Id)).AddNickname(beforeUser);
             guildDb.Users.Find(u => u.ID.Equals(afterUser.Id)).AddUsername(afterUser.Username);
             guildDb.Users.Find(u => u.ID.Equals(afterUser.Id)).AddNickname(afterUser);
         }
         else
         {
             guildDb.Users.Add(new DBUser(afterUser));
         }
         guildDb.Save();
     }
 }
コード例 #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
ファイル: PointsCommands.cs プロジェクト: HOGGARB/GenericBot
        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);
        }
コード例 #4
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);
        }
コード例 #5
0
ファイル: ModCommands.cs プロジェクト: AlishaSkye/GenericBot
        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
ファイル: RoleCommands.cs プロジェクト: AlishaSkye/GenericBot
        public List <Command> GetRoleCommands()
        {
            List <Command> RoleCommands = new List <Command>();

            Command mentionRole = new Command(nameof(mentionRole));

            mentionRole.RequiredPermission = Command.PermissionLevels.Moderator;
            mentionRole.Description        = "Mention a role that's not normally mentionable";
            mentionRole.ToExecute         += async(client, msg, parameters) =>
            {
                if (msg.GetGuild().Roles.HasElement(r => r.Name.ToLower().Contains(parameters[0].ToLower()), out SocketRole role))
                {
                    var state = role.IsMentionable;
                    if (!state)
                    {
                        await role.ModifyAsync(r => r.Mentionable = true);
                    }
                    parameters.RemoveAt(0);
                    await msg.ReplyAsync(role.Mention + " " + parameters.reJoin());

                    await msg.DeleteAsync();

                    if (!state)
                    {
                        await role.ModifyAsync(r => r.Mentionable = state);
                    }
                }
                else
                {
                    await msg.ReplyAsync("Couldn't find that role!");
                }
            };

            RoleCommands.Add(mentionRole);

            Command UserRoles = new Command("userroles");

            UserRoles.Description = $"Show all user roles on this server";
            UserRoles.Usage       = "userroles";
            UserRoles.ToExecute  += async(client, msg, paramList) =>
            {
                string prefix = (!String.IsNullOrEmpty(GenericBot.GuildConfigs[(msg.Channel as SocketGuildChannel).Guild.Id].Prefix))
                ? GenericBot.GuildConfigs[(msg.Channel as SocketGuildChannel).Guild.Id].Prefix : GenericBot.GlobalConfiguration.DefaultPrefix;
                string message = $"You can use `{prefix}iam` and `{prefix}iamnot` with any of these roles:\n";
                foreach (var role in msg.GetGuild().Roles
                         .Where(r => GenericBot.GuildConfigs[msg.GetGuild().Id].UserRoleIds.Contains(r.Id))
                         .OrderBy(r => r.Name))
                {
                    if ((msg.Author as SocketGuildUser).Roles.Contains(role))
                    {
                        message += "\\✔ ";
                    }
                    else
                    {
                        message += "✘";
                    }
                    message += $"`{role.Name}`, ";
                }
                message = message.Trim(' ', ',');

                foreach (var str in message.SplitSafe())
                {
                    await msg.ReplyAsync(str);
                }
            };

            RoleCommands.Add(UserRoles);

            Command iam = new Command("iam");

            iam.Description = "Join a User Role";
            iam.Usage       = "iam <role name>";
            iam.Aliases     = new List <string> {
                "join"
            };
            iam.ToExecute += async(client, msg, paramList) =>
            {
                IMessage rep;
                if (paramList.Empty())
                {
                    rep = msg.ReplyAsync($"Please select a role to join").Result;
                    await Task.Delay(15000);

                    await msg.DeleteAsync();

                    await rep.DeleteAsync();
                }
                string input = paramList.Aggregate((i, j) => i + " " + j);

                var roles = msg.GetGuild().Roles.Where(r => r.Name.ToLower().Contains(input.ToLower()))
                            .Where(r => GenericBot.GuildConfigs[msg.GetGuild().Id].UserRoleIds.Contains(r.Id));

                if (!roles.Any())
                {
                    rep = msg.ReplyAsync($"Could not find any user roles matching `{input}`").Result;
                    await Task.Delay(15000);

                    await msg.DeleteAsync();

                    await rep.DeleteAsync();
                }
                else if (roles.Count() == 1)
                {
                    try
                    {
                        RestUserMessage message;
                        if (msg.GetGuild().GetUser(msg.Author.Id).Roles.Any(r => r.Id == roles.First().Id))
                        {
                            message = await msg.ReplyAsync("You already have that role!");
                        }
                        else
                        {
                            await msg.GetGuild().GetUser(msg.Author.Id).AddRoleAsync(roles.First());

                            message = await msg.ReplyAsync("Done!");
                        }

                        await Task.Delay(15000);

                        try { await msg.DeleteAsync(); } catch { } // Catch the message being deleted
                        await message.DeleteAsync();
                    }
                    catch (Exception e)
                    {
                        await GenericBot.Logger.LogErrorMessage(e.Message);

                        await msg.ReplyAsync($"I may not have permissions to do that!");
                    }
                }
                else if (roles.Count() > 1)
                {
                    try
                    {
                        var role = roles.Any(r => r.Name.ToLower() == input.ToLower())
                            ? roles.First(r => r.Name.ToLower() == input.ToLower())
                            : roles.First();
                        RestUserMessage message;
                        if (msg.GetGuild().GetUser(msg.Author.Id).Roles.Any(r => r.Id == roles.First().Id))
                        {
                            message = await msg.ReplyAsync("You already have that role!");
                        }
                        else
                        {
                            await msg.GetGuild().GetUser(msg.Author.Id).AddRoleAsync(role);

                            message = await msg.ReplyAsync($"I've assigned you `{role.Name}`");
                        }

                        await Task.Delay(15000);

                        try { await msg.DeleteAsync(); } catch { } // Catch the message being deleted
                        await message.DeleteAsync();
                    }
                    catch (Exception e)
                    {
                        await GenericBot.Logger.LogErrorMessage(e.Message);

                        await msg.ReplyAsync($"I may not have permissions to do that!");
                    }
                }
            };

            RoleCommands.Add(iam);

            Command iamnot = new Command("iamnot");

            iamnot.Description = "Leave a User Role";
            iamnot.Usage       = "iamnot <role name>";
            iamnot.Aliases     = new List <string> {
                "leave"
            };
            iamnot.ToExecute += async(client, msg, paramList) =>
            {
                IMessage rep;
                if (paramList.Empty())
                {
                    rep = msg.ReplyAsync($"Please select a role to leave").Result;
                    await Task.Delay(15000);

                    await msg.DeleteAsync();

                    await rep.DeleteAsync();
                }
                string input = paramList.Aggregate((i, j) => i + " " + j);

                var roles = msg.GetGuild().Roles.Where(r => r.Name.ToLower().Contains(input.ToLower()))
                            .Where(r => GenericBot.GuildConfigs[msg.GetGuild().Id].UserRoleIds.Contains(r.Id));

                if (!roles.Any())
                {
                    rep = msg.ReplyAsync($"Could not find any user roles matching `{input}`").Result;
                    await Task.Delay(15000);

                    await msg.DeleteAsync();

                    await rep.DeleteAsync();
                }
                else if (roles.Count() == 1)
                {
                    try
                    {
                        RestUserMessage message;
                        if (!msg.GetGuild().GetUser(msg.Author.Id).Roles.Any(r => r.Id == roles.First().Id))
                        {
                            message = await msg.ReplyAsync("You don't have that role!");
                        }
                        else
                        {
                            await msg.GetGuild().GetUser(msg.Author.Id).RemoveRoleAsync(roles.First());

                            message = await msg.ReplyAsync("Done!");
                        }

                        await Task.Delay(15000);

                        try { await msg.DeleteAsync(); } catch { } // Catch the message being deleted
                        await message.DeleteAsync();
                    }
                    catch (Exception e)
                    {
                        await GenericBot.Logger.LogErrorMessage(e.Message);

                        await msg.ReplyAsync($"I may not have permissions to do that!");
                    }
                }
                else if (roles.Count() > 1)
                {
                    try
                    {
                        RestUserMessage message;
                        if (!msg.GetGuild().GetUser(msg.Author.Id).Roles.Any(r => r.Id == roles.First().Id))
                        {
                            message = await msg.ReplyAsync("You don't have that role!");
                        }
                        else
                        {
                            await msg.GetGuild().GetUser(msg.Author.Id).RemoveRoleAsync(roles.First());

                            message = await msg.ReplyAsync($"Removed `{roles.First()}`");
                        }

                        await Task.Delay(15000);

                        try { await msg.DeleteAsync(); } catch { } // Catch the message being deleted
                        await message.DeleteAsync();
                    }
                    catch (Exception e)
                    {
                        await GenericBot.Logger.LogErrorMessage(e.Message);

                        await msg.ReplyAsync($"I may not have permissions to do that!");
                    }
                }
            };

            RoleCommands.Add(iamnot);

            Command getrole = new Command("getrole");

            getrole.Description        = "Get the ID of a role";
            getrole.Usage              = "getrole <role name>";
            getrole.RequiredPermission = Command.PermissionLevels.Moderator;
            getrole.ToExecute         += async(client, msg, paramList) =>
            {
                string message = $"Roles matching `{paramList.reJoin()}`:\n";
                foreach (var role in msg.GetGuild().Roles.Where(r => Regex.IsMatch(r.Name, paramList.reJoin(), RegexOptions.IgnoreCase)))
                {
                    message += $"{role.Name} (`{role.Id}`)\n";
                }

                foreach (var str in message.SplitSafe())
                {
                    msg.ReplyAsync(str);
                }
            };

            RoleCommands.Add(getrole);

            Command membersOf = new Command("membersof");

            membersOf.Description        = "List all members of a role";
            membersOf.Usage              = "membersof <rolename>";
            membersOf.RequiredPermission = Command.PermissionLevels.Moderator;
            membersOf.ToExecute         += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync($"You need to specify a role");

                    return;
                }
                string result = "";
                foreach (var role in msg.GetGuild().Roles.OrderByDescending(r => r.Position).Where(r => new Regex(parameters.reJoin(), RegexOptions.IgnoreCase).IsMatch(r.Name) && r.Name != "@everyone"))
                {
                    result += $"\n**`{role.Name}` ({role.Members.Count()} Members)**\n";
                    foreach (var user in role.Members.OrderBy(u => u.Username))
                    {
                        if (!string.IsNullOrEmpty(user.Nickname))
                        {
                            result += $"{user.Nickname.Replace('`', '\'').Replace("_", "\\_")} ";
                        }
                        else
                        {
                            result += $"{user.Username.Replace('`', '\'').Replace("_", "\\_")} ";
                        }
                        result += $"(`{user.ToString().Replace('`', '\'')}`)\n";
                    }
                }

                foreach (var str in result.SplitSafe('\n'))
                {
                    await msg.ReplyAsync(str);
                }
            };

            RoleCommands.Add(membersOf);

            Command createRole = new Command("createRole");

            createRole.Description        = "Create a new role with default permissions";
            createRole.Usage              = "createRole <name>";
            createRole.RequiredPermission = Command.PermissionLevels.Admin;
            createRole.ToExecute         += async(client, msg, parameters) =>
            {
                RestRole role;
                bool     makeMentionable = false;
                if (parameters[0].ToLower().Equals("+m"))
                {
                    parameters.RemoveAt(0);
                    makeMentionable = true;
                }

                role = msg.GetGuild().CreateRoleAsync(parameters.reJoin(), GuildPermissions.None).Result;
                if (makeMentionable)
                {
                    await role.ModifyAsync(r => r.Mentionable = true);
                }
                await msg.ReplyAsync($"Created new role `{role.Name}` with ID `{role.Id}`");
            };

            RoleCommands.Add(createRole);

            Command createUserRole = new Command("createUserRole");

            createUserRole.Description        = "Create a new role with default permissions and add it to the public role list";
            createUserRole.Usage              = "createUserRole <name>";
            createUserRole.RequiredPermission = Command.PermissionLevels.Admin;
            createUserRole.ToExecute         += async(client, msg, parameters) =>
            {
                RestRole role;
                bool     makeMentionable = false;
                if (parameters[0].ToLower().Equals("+m"))
                {
                    parameters.RemoveAt(0);
                    makeMentionable = true;
                }

                role = msg.GetGuild().CreateRoleAsync(parameters.reJoin(), GuildPermissions.None).Result;
                var gc = GenericBot.GuildConfigs[msg.GetGuild().Id];
                gc.UserRoleIds.Add(role.Id);
                gc.Save();
                if (makeMentionable)
                {
                    await role.ModifyAsync(r => r.Mentionable = true);
                }
                await msg.ReplyAsync($"Created new role `{role.Name}` with ID `{role.Id}` and added it to the user roles");
            };

            RoleCommands.Add(createUserRole);

            Command roleeveryone = new Command("roleeveryone");

            roleeveryone.Aliases = new List <string> {
                "roleveryone"
            };
            roleeveryone.Description        = "Give or remove a role from everyone";
            roleeveryone.Usage              = "roleveryone [+-] <roleID>";
            roleeveryone.RequiredPermission = Command.PermissionLevels.Admin;
            roleeveryone.ToExecute         += async(client, msg, parameters) =>
            {
                if (!(parameters[0].Contains("+") || parameters[0].Contains("-")))
                {
                    await msg.ReplyAsync($"Invalid option `{parameters[0]}`");
                }
                ulong id;
                if (ulong.TryParse(parameters[1], out id) && msg.GetGuild().Roles.Any(r => r.Id == id))
                {
                    int i = 0;
                    await msg.GetGuild().DownloadUsersAsync();

                    var role = msg.GetGuild().GetRole(id);
                    foreach (var u in msg.GetGuild().Users)
                    {
                        if (parameters[0].Contains("-") && u.Roles.Any(r => r.Id == id))
                        {
                            await u.RemoveRoleAsync(role);

                            i++;
                        }
                        if (parameters[0].Contains("+") && !u.Roles.Any(r => r.Id == id))
                        {
                            await u.AddRoleAsync(role);

                            i++;
                        }
                    }
                    string addrem = parameters[0].Contains("+") ? "Added" : "Removed";
                    string tofrom = parameters[0].Contains("+") ? "to" : "from";
                    await msg.ReplyAsync($"{addrem} `{role.Name}` {tofrom} `{i}` users.");
                }
                else
                {
                    await msg.ReplyAsync("Invalid Role Id");
                }
            };

            RoleCommands.Add(roleeveryone);

            Command roleStore = new Command("roleStore");

            roleStore.Description = "Store your roles so you can restore them later";
            roleStore.Usage       = "rolestore [save|restore]";
            roleStore.ToExecute  += async(client, msg, parameters) =>
            {
                if (parameters[0].ToLower().Equals("save"))
                {
                    var          guildDb = new DBGuild(msg.GetGuild().Id);
                    var          dbUser  = guildDb.Users.First(u => u.ID.Equals(msg.Author.Id));
                    List <ulong> roles   = new List <ulong>();
                    foreach (var role in (msg.Author as SocketGuildUser).Roles)
                    {
                        roles.Add(role.Id);
                    }

                    dbUser.SavedRoles = roles;

                    await msg.ReplyAsync($"I've saved `{dbUser.SavedRoles.Count}` roles for you!");

                    guildDb.Save();
                }
                else if (parameters[0].ToLower().Equals("restore"))
                {
                    var guildDb = new DBGuild(msg.GetGuild().Id);
                    if (guildDb.Users.Any(u => u.ID.Equals(msg.Author.Id))) // if already exists
                    {
                        var dbUser = guildDb.Users.First(u => u.ID.Equals(msg.Author.Id));
                        if (dbUser.SavedRoles == null || !dbUser.SavedRoles.Any())
                        {
                            await msg.ReplyAsync("No roles saved. Try using `rolestore save` first!");

                            return;
                        }

                        int success = 0;
                        int fails   = 0;
                        foreach (var id in dbUser.SavedRoles.Where(id =>
                                                                   !(msg.Author as IGuildUser).RoleIds.Contains(id)))
                        {
                            try
                            {
                                await(msg.Author as SocketGuildUser).AddRoleAsync(
                                    msg.GetGuild().Roles.First(r => r.Id.Equals(id)));
                                success++;
                            }
                            catch (Exception e)
                            {
                                fails++;
                            }
                        }

                        await msg.ReplyAsync($"`{success}` roles restored, `{fails}` failed");
                    }
                    else
                    {
                        await msg.ReplyAsync("I don't have any saved roles for you");

                        return;
                    }
                }
                else
                {
                    await msg.ReplyAsync("Invalid option");
                }
            };

            RoleCommands.Add(roleStore);

            return(RoleCommands);
        }
コード例 #7
0
ファイル: FunCommands.cs プロジェクト: AlishaSkye/GenericBot
        public List <Command> GetFunCommands()
        {
            List <Command> FunCommands = new List <Command>();

            Command wat = new Command("wat");

            wat.Description = "The best command";
            wat.ToExecute  += async(client, msg, parameters) =>
            {
                await msg.ReplyAsync($"**-wat-**\nhttp://destroyallsoftware.com/talks/wat");
            };

            FunCommands.Add(wat);

            Command roll = new Command("roll");

            roll.Aliases.Add("dice");
            roll.Description = "Roll a specified number of dices. Defaults to 1d20 if no parameters";
            roll.Usage       = "roll [count]d[sides]";
            roll.ToExecute  += async(client, msg, parameters) =>
            {
                uint count = 1;
                uint sides = 20;
                int  add   = 0;
                if (!parameters.Empty())
                {
                    string param = parameters.reJoin("").ToLower();
                    if (!param.Contains("d"))
                    {
                        if (!uint.TryParse(param, out count))
                        {
                            await msg.ReplyAsync("Input improperly formatted");

                            return;
                        }
                    }
                    else
                    {
                        if (!(param.Contains("+") || param.Contains("-")))
                        {
                            var list = param.Split('d');
                            if (!(uint.TryParse(list[0], out count) && uint.TryParse(list[1], out sides)))
                            {
                                await msg.ReplyAsync("Input improperly formatted");

                                return;
                            }
                        }
                        else
                        {
                            string c      = param.Split('d')[0];
                            string second = param.Split('d')[1];
                            string s      = "";
                            string a      = "";
                            if (param.Contains("+"))
                            {
                                s = second.Split('+')[0];
                                a = second.Split('+')[1];
                            }
                            else if (param.Contains("-"))
                            {
                                s = second.Split('-')[0];
                                a = second.Replace(s, "");
                            }

                            if (!(uint.TryParse(c, out count) && uint.TryParse(s, out sides) && int.TryParse(a, out add)))
                            {
                                await msg.ReplyAsync("Input improperly formatted");

                                return;
                            }
                        }
                    }
                }

                if (count > 100)
                {
                    await msg.ReplyAsync("I don't think you can hold that many!");

                    return;
                }
                if (sides < 2)
                {
                    await msg.ReplyAsync("You can't have a 1-sided dice!");

                    return;
                }
                if (sides > 100)
                {
                    await msg.ReplyAsync("That's an awefully large dice, I can't hold that");

                    return;
                }
                RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
                List <int> results = new List <int>();
                while (results.Count < count)
                {
                    byte[] bytes = new byte[4];
                    crypto.GetNonZeroBytes(bytes);
                    long rand = Math.Abs(BitConverter.ToInt32(bytes, 0)) % sides;
                    results.Add((int)rand + 1 + add);
                }

                string res = $"{msg.Author.Mention}, you rolled ";
                results.Sort();
                res += results.SumAnd();
                if (count > 1)
                {
                    res += $" with a total of {results.Sum()}";
                }
                await msg.ReplyAsync(res);
            };

            FunCommands.Add(roll);

            Command cat = new Command("cat");

            cat.Description = "Link a cat pic";
            cat.SendTyping  = false;
            cat.ToExecute  += async(client, msg, parameters) =>
            {
                try
                {
                    await msg.ReplyAsync(GenericBot.Animols.GetCat());
                }
                catch (Exception ex)
                {
                    await msg.ReplyAsync("Uh oh, something borked a bit. Wait a sec and try again.");
                }
                GenericBot.Animols.RenewCats();
            };
            FunCommands.Add(cat);

            Command dog = new Command("dog");

            dog.Description = "Link a dog pic";
            dog.SendTyping  = false;
            dog.ToExecute  += async(client, msg, parameters) =>
            {
                await msg.ReplyAsync(GenericBot.Animols.GetDog());

                GenericBot.Animols.RenewDogs();
            };
            FunCommands.Add(dog);


            Command addQuote = new Command("addQuote");

            addQuote.SendTyping  = false;
            addQuote.Description = "Add a quote to the server's list";
            addQuote.ToExecute  += async(client, msg, parameters) =>
            {
                var dbGuild = new DBGuild(msg.GetGuild().Id);
                var q       = dbGuild.AddQuote(parameters.reJoin());
                dbGuild.Save();
                await msg.ReplyAsync($"Added {q.ToString()}");
            };
            FunCommands.Add(addQuote);

            Command removeQuote = new Command("removeQuote");

            removeQuote.Description        = "Remove a quote from the server's list";
            removeQuote.SendTyping         = false;
            removeQuote.RequiredPermission = Command.PermissionLevels.Moderator;
            removeQuote.ToExecute         += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync("You must supply a number");

                    return;
                }

                var dbGuild = new DBGuild(msg.GetGuild().Id);
                if (int.TryParse(parameters[0], out int quid))
                {
                    if (dbGuild.RemoveQuote(quid))
                    {
                        await msg.ReplyAsync($"Succefully removed quote #{quid}");
                    }
                    else
                    {
                        await msg.ReplyAsync($"The number was greater than the number of quotes saved");

                        return;
                    }
                }
                else
                {
                    await msg.ReplyAsync("You must pass in a number");
                }
                dbGuild.Save();
            };
            FunCommands.Add(removeQuote);

            Command quote = new Command("quote");

            quote.SendTyping  = false;
            quote.Description = "Get a random quote from the server's list";
            quote.ToExecute  += async(client, msg, parameters) =>
            {
                if (!parameters.Empty() && parameters[0] == "all" && quote.GetPermissions(msg.Author, msg.GetGuild().Id) >=
                    Command.PermissionLevels.Admin)
                {
                    System.IO.File.WriteAllText("quotes.txt", new DBGuild(msg.GetGuild().Id).Quotes.Where(q => q.Active).Select(q => $"{q.Content} (#{q.Id})").Aggregate((i, j) => i + "\n" + j));
                    await msg.Channel.SendFileAsync("quotes.txt");

                    System.IO.File.Delete("quotes.txt");
                    return;
                }
                await msg.ReplyAsync(new DBGuild(msg.GetGuild().Id).GetQuote(parameters.reJoin()));
            };
            FunCommands.Add(quote);

            Command redact = new Command(nameof(redact));

            redact.ToExecute += async(client, msg, parameters) =>
            {
                msg.DeleteAsync();
                char          block = '█';
                int           rcont = 1;
                StringBuilder resp  = new StringBuilder();
                foreach (var str in parameters)
                {
                    int rand = new Random().Next(0, rcont) + 1;
                    if (rand == rcont)
                    {
                        resp.Append(' ');
                        resp.Append(str);
                        resp.Append(' ');
                        rcont = 1;
                    }
                    else
                    {
                        resp.Append(block.Multiply(str.Length));
                        if (rcont == 16)
                        {
                            rcont = 1;
                        }
                    }
                    rcont++;
                }

                await msg.ReplyAsync(resp.ToString().Replace("  ", " "));
            };

            FunCommands.Add(redact);

            Command clap = new Command("clap");

            clap.Usage      = "Put the clap emoji between each word";
            clap.ToExecute += async(client, msg, parameters) =>
            {
                await msg.ReplyAsync(parameters.reJoin(" :clap: "));
            };

            FunCommands.Add(clap);

            return(FunCommands);
        }
コード例 #8
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);
        }
コード例 #9
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}");
            }
        }
コード例 #10
0
        public List <Command> GetFunCommands()
        {
            List <Command> FunCommands = new List <Command>();

            Command markov = new Command("markov");

            markov.Description = "Create a markov chain from the last messages in the channel";
            markov.Delete      = true;
            markov.Usage       = "markov";
            markov.ToExecute  += async(client, msg, parameters) =>
            {
                var messages = msg.Channel.GetMessagesAsync().Flatten().Reverse().Select(m => m.Content).ToList().Result;
                messages.ToList().AddRange(messages.TakeLast(50));
                messages.ToList().AddRange(messages.TakeLast(25));
                messages.ToList().AddRange(messages.TakeLast(10));

                int averageLength = messages.Sum(m => m.Split(' ').Length) / 185;
                averageLength = averageLength > 10 ? averageLength : averageLength * 2;

                var markovGenerator = new SharperMark.LookbackMarkov();
                markovGenerator.Train(messages.ToArray());

                await msg.ReplyAsync(markovGenerator.GenerateWords(averageLength));
            };

            FunCommands.Add(markov);

            Command wat = new Command("wat");

            wat.Description = "The best command";
            wat.ToExecute  += async(client, msg, parameters) =>
            {
                await msg.ReplyAsync($"**-wat-**\nhttp://destroyallsoftware.com/talks/wat");
            };

            FunCommands.Add(wat);

            Command twobee = new Command("2b");

            twobee.Description = "toggle the command";
            twobee.ToExecute  += async(client, msg, parameters) =>
            {
                if (msg.Author.Id == 189378507724292096)
                {
                    await msg.ReplyAsync($"2b sleep");
                }
                else
                {
                    GenericBot.annoy2B = !GenericBot.annoy2B;
                    await msg.ReplyAsync($"toggled to " + GenericBot.annoy2B);
                }
            };
            FunCommands.Add(twobee);

            Command inspirobot = new Command("inspirobot");

            inspirobot.Description = "Generate a new image from Inspirobot";
            inspirobot.ToExecute  += async(client, msg, parameters) =>
            {
                await msg.ReplyAsync(new WebClient().DownloadString("http://inspirobot.me/api?generate=true"));
            };

            FunCommands.Add(inspirobot);

            Command ud = new Command("ud");

            ud.Aliases = new List <string> {
                "urbandictionary"
            };
            ud.Description = "Define a word or phrase with UrbanDictionary";
            ud.ToExecute  += async(client, msg, parameters) =>
            {
                string word          = parameters.reJoin();
                var    urbanclient   = new UrbanDictionary.UrbanClient();
                var    urbanResponse = urbanclient.GetClientResponse(word);

                var em = new EmbedBuilder();

                em.WithThumbnailUrl("http://marcmarut.com/wp-content/uploads/2013/12/Urban-Dictionary-Icon3.png");
                Regex rgx = new Regex(@"\[(\w|\s)*\]");
                if (urbanResponse.List.Count == 0)
                {
                    em.WithTitle(word);
                    em.WithDescription("No matches found");
                    em.WithColor(new Color(250, 0, 0));
                }
                else
                {
                    var pos       = new Random().Next(urbanResponse.List.Where(w => (w.ThumbsUp - w.ThumbsDown) > 0).ToList().Count);
                    var wordToUse = urbanResponse.List.Where(w => (w.ThumbsUp - w.ThumbsDown) > 0).ToList()[pos];

                    em.WithTitle(wordToUse.Word);
                    em.WithUrl(wordToUse.Permalink);
                    em.AddField("Definition", wordToUse.Definition.Replace("[", "").Replace("]", ""));
                    em.AddField("Example", wordToUse.Example.Replace("[", "").Replace("]", ""));
                    //em.AddField("Tags", wordToUse.Tags.Aggregate((i, j) => i + ", " + j));
                    em.AddField("Author", wordToUse.Author, inline: true);
                    em.AddField("Rating", wordToUse.ThumbsUp - wordToUse.ThumbsDown, inline: true);
                    em.WithFooter(new EmbedFooterBuilder().WithText($" Definition {pos + 1}/{urbanResponse.List.Count} ({urbanResponse.List.Where(w => (w.ThumbsUp - w.ThumbsDown) > 0).ToList().Count})"));
                    em.WithColor(new Color(19, 79, 230));
                }

                await msg.Channel.SendMessageAsync("", embed : em.Build());
            };
            FunCommands.Add(ud);
            Command roll = new Command("roll");

            roll.Aliases.Add("dice");
            roll.Description = "Roll a specified number of dices. Defaults to 1d20 if no parameters";
            roll.Usage       = "roll [count]d[sides]";
            roll.ToExecute  += async(client, msg, parameters) =>
            {
                uint count = 1;
                uint sides = 20;
                int  add   = 0;
                if (!parameters.Empty()) // If there are any parameters
                {
                    string param = parameters.reJoin("").ToLower();
                    if (!param.Contains("d")) // it's just a number
                    {
                        if (!uint.TryParse(param, out count))
                        {
                            await msg.ReplyAsync("Input improperly formatted");

                            return;
                        }
                    }
                    else
                    {
                        if (!(param.Contains("+") || param.Contains("-"))) // There's no modifier
                        {
                            var list = param.Split('d');
                            if (!uint.TryParse(list[1], out sides))
                            {
                                await msg.ReplyAsync("Input improperly formatted");

                                return;
                            }
                            uint.TryParse(list[0], out count);
                            count = (count <= 1 ? 1 : count);
                        }
                        else
                        {
                            string c      = param.Split('d')[0];
                            string second = param.Split('d')[1];
                            string s      = "";
                            string a      = "";
                            if (param.Contains("+"))
                            {
                                s = second.Split('+')[0];
                                a = second.Split('+')[1];
                            }
                            else if (param.Contains("-"))
                            {
                                s = second.Split('-')[0];
                                a = second.Replace(s, "");
                            }

                            if (!(uint.TryParse(c, out count) && uint.TryParse(s, out sides) && int.TryParse(a, out add)))
                            {
                                await msg.ReplyAsync("Input improperly formatted");

                                return;
                            }
                        }
                    }
                }

                if (count > 100)
                {
                    await msg.ReplyAsync("I don't think you can hold that many!");

                    return;
                }
                if (sides < 2)
                {
                    await msg.ReplyAsync("You can't have a 1-sided dice!");

                    return;
                }
                if (sides > 100)
                {
                    await msg.ReplyAsync("That's an awefully large dice, I can't hold that");

                    return;
                }
                RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
                List <int> results = new List <int>();
                while (results.Count < count)
                {
                    byte[] bytes = new byte[4];
                    crypto.GetNonZeroBytes(bytes);
                    long rand = Math.Abs(BitConverter.ToInt32(bytes, 0)) % sides;
                    results.Add((int)rand + 1 + add);
                }

                string res = $"{msg.Author.Mention}, you rolled ";
                results.Sort();
                res += results.SumAnd();
                if (count > 1)
                {
                    res += $" with a total of {results.Sum()}";
                }
                await msg.ReplyAsync(res);
            };

            FunCommands.Add(roll);

            Command cat = new Command("cat");

            cat.Description = "Link a cat pic";
            cat.SendTyping  = false;
            cat.ToExecute  += async(client, msg, parameters) =>
            {
                try
                {
                    await msg.ReplyAsync(GenericBot.Animols.GetCat());
                }
                catch
                {
                    await msg.ReplyAsync("Uh oh, something borked a bit. Wait a sec and try again.");
                }
                GenericBot.Animols.RenewCats();
            };
            FunCommands.Add(cat);

            Command dog = new Command("dog");

            dog.Description = "Link a dog pic";
            dog.SendTyping  = false;
            dog.ToExecute  += async(client, msg, parameters) =>
            {
                await msg.ReplyAsync(GenericBot.Animols.GetDog());

                GenericBot.Animols.RenewDogs();
            };
            FunCommands.Add(dog);

            Command floof = new Command("floof");                 // defines a new command for the bot called floof

            floof.Description = "link a pic of chefs dog";        //adds a description so the help command works
            floof.ToExecute  += async(client, msg, parameters) => //i dont actually know what this does tbh but it seems important (maybe is the section of code that is run when the command is called (probably that tbh))
            {
                string baseURL = "https://mastrchef.rocks/baloo/";
                string floofstring;
                using (var wc = new System.Net.WebClient())
                    floofstring = wc.DownloadString(baseURL + "list.php");
                var floofarray = floofstring.Split("<br>").ToList();
                floofstring = floofarray.GetRandomItem();
                if (floofstring.Contains("https"))
                {
                    await msg.ReplyAsync(floofstring);
                }
                else
                {
                    await msg.ReplyAsync(baseURL + floofstring);
                }
            };
            FunCommands.Add(floof);

            Command keysmash = new Command("keysmash");

            keysmash.Description = "Generates a keysmash";
            keysmash.SendTyping  = false;
            keysmash.ToExecute  += async(client, msg, parameters) =>
            {
                List <string> Letters1 = new List <string> {
                    "a", "s", "d", "f", "j", "k", "l", ";"
                };

                string ToSend = "ad";

                for (int i = 1; i < 16; i++)
                {
                    Letters1.Remove(ToSend[ToSend.Length - 1].ToString());
                    ToSend += Letters1.GetRandomItem();
                    Letters1.Add(ToSend[ToSend.Length - 2].ToString());
                }
                await msg.ReplyAsync(ToSend);
            };
            FunCommands.Add(keysmash);


            Command addQuote = new Command("addQuote");

            addQuote.SendTyping  = false;
            addQuote.Description = "Add a quote to the server's list";
            addQuote.ToExecute  += async(client, msg, parameters) =>
            {
                var dbGuild = new DBGuild(msg.GetGuild().Id);
                if (string.IsNullOrEmpty(parameters.reJoin()))
                {
                    await msg.ReplyAsync("You can't add an empty quote");

                    return;
                }
                var q = dbGuild.AddQuote(parameters.reJoin());
                dbGuild.Save();
                await msg.ReplyAsync($"Added {q.ToString()}");
            };
            FunCommands.Add(addQuote);

            Command removeQuote = new Command("removeQuote");

            removeQuote.Description        = "Remove a quote from the server's list";
            removeQuote.SendTyping         = false;
            removeQuote.RequiredPermission = Command.PermissionLevels.Moderator;
            removeQuote.ToExecute         += async(client, msg, parameters) =>
            {
                if (parameters.Empty())
                {
                    await msg.ReplyAsync("You must supply a number");

                    return;
                }

                var dbGuild = new DBGuild(msg.GetGuild().Id);
                if (int.TryParse(parameters[0], out int quid))
                {
                    if (dbGuild.RemoveQuote(quid))
                    {
                        await msg.ReplyAsync($"Succefully removed quote #{quid}");
                    }
                    else
                    {
                        await msg.ReplyAsync($"The number was greater than the number of quotes saved");

                        return;
                    }
                }
                else
                {
                    await msg.ReplyAsync("You must pass in a number");
                }
                dbGuild.Save();
            };
            FunCommands.Add(removeQuote);

            Command quote = new Command("quote");

            quote.SendTyping  = false;
            quote.Description = "Get a random quote from the server's list";
            quote.ToExecute  += async(client, msg, parameters) =>
            {
                if (!parameters.Empty() && parameters[0] == "all" && quote.GetPermissions(msg.Author, msg.GetGuild().Id) >=
                    Command.PermissionLevels.Admin)
                {
                    System.IO.File.WriteAllText("quotes.txt", new DBGuild(msg.GetGuild().Id).Quotes.Where(q => q.Active).Select(q => $"{q.Content} (#{q.Id})").Aggregate((i, j) => i + "\n" + j));
                    await msg.Channel.SendFileAsync("quotes.txt");

                    System.IO.File.Delete("quotes.txt");
                    return;
                }
                await msg.ReplyAsync(new DBGuild(msg.GetGuild().Id).GetQuote(parameters.reJoin()));
            };
            FunCommands.Add(quote);

            Command redact = new Command(nameof(redact));

            redact.ToExecute += async(client, msg, parameters) =>
            {
                await msg.DeleteAsync();

                char          block = '█';
                int           rcont = 1;
                StringBuilder resp  = new StringBuilder();
                foreach (var str in parameters)
                {
                    int rand = new Random().Next(0, rcont) + 1;
                    if (rand == rcont)
                    {
                        resp.Append(' ');
                        resp.Append(str);
                        resp.Append(' ');
                        rcont = 1;
                    }
                    else
                    {
                        resp.Append(new String(block, str.Length));
                        if (rcont == 16)
                        {
                            rcont = 1;
                        }
                    }
                    rcont++;
                }

                await msg.ReplyAsync(resp.ToString().Replace("  ", " "));
            };

            FunCommands.Add(redact);

            Command clap = new Command("clap");

            clap.Usage      = "Put the clap emoji between each word";
            clap.ToExecute += async(client, msg, parameters) =>
            {
                await msg.ReplyAsync(parameters.reJoin(" :clap: ") + " :clap:");
            };

            FunCommands.Add(clap);

            return(FunCommands);
        }
コード例 #11
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));
            }
            lock ("db")
            {
                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 (Exception ex)
                {
                }
            }
            if (guildConfig.ProbablyMutedUsers.Contains(user.Id))
            {
                try { 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
        }