Example #1
0
 public Giveaway(ParsedCommand context, string description)
 {
     this.OwnerId      = context.Author.Id;
     this.Description  = description;
     this.Id           = VerificationEngine.GetVerificationCode(context.Message.Id, context.Author.Id);
     this.EnteredUsers = new List <ulong>();
     this.IsActive     = true;
 }
Example #2
0
        public List <Command> Load()
        {
            List <Command> commands = new List <Command>();

            Command config = new Command("config");

            config.RequiredPermission = Command.PermissionLevels.Admin;
            config.Description        = "Configure the bot or see current config";
            config.Usage      = "config <option> <value>";
            config.ToExecute += async(context) =>
            {
                var _guildConfig = Core.GetGuildConfig(context.Guild.Id);
                if (context.Parameters.IsEmpty())
                {
                    string currentConfig =
                        $"Prefix: `{Core.GetPrefix(context)}`\n" +
                        $"Admin Roles: `{JsonConvert.SerializeObject(_guildConfig.AdminRoleIds)}`\n" +
                        $"Mod Roles: `{JsonConvert.SerializeObject(_guildConfig.ModRoleIds)}`\n" +
                        $"User Roles: `{JsonConvert.SerializeObject(_guildConfig.UserRoles)}`\n" +
                        $"Logging\n" +
                        $"    Channel Id: `{_guildConfig.LoggingChannelId}`\n" +
                        $"    Ignored Channels: `{JsonConvert.SerializeObject(_guildConfig.MessageLoggingIgnoreChannels)}`\n" +
                        $"Muted Role Id: `{_guildConfig.MutedRoleId}`\n" +
                        $"Verification:\n" +
                        $"    Role Id: `{_guildConfig.VerifiedRole}`\n" +
                        $"    Message: Do `{Core.GetPrefix(context)}config verification message` to see the message\n" +
                        $"Points: {_guildConfig.PointsEnabled}\n" +
                        $"Auto Roles: `{JsonConvert.SerializeObject(_guildConfig.AutoRoleIds)}`" +
                        $"Trusted Role Id: `{_guildConfig.TrustedRoleId}`" +
                        $"Trusted Role Point Threshold: `{_guildConfig.TrustedRolePointThreshold}`";

                    await context.Message.ReplyAsync(currentConfig);
                }

                #region AdminRoles
                else if (context.Parameters[0].ToLower().Equals("adminroles"))
                {
                    if (context.Parameters.Count == 1)
                    {
                        await context.Message.ReplyAsync($"Please enter a config option");

                        return;
                    }
                    if (context.Parameters.Count == 2)
                    {
                        await context.Message.ReplyAsync($"Please enter a roleId");

                        return;
                    }
                    ulong id;
                    if (ulong.TryParse(context.Parameters[2], out id) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(id)))
                    {
                        if (context.Parameters[1].ToLower().Equals("add"))
                        {
                            if (!Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Contains(id))
                            {
                                Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Add(id);
                                await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to Admin Roles");
                            }
                            else
                            {
                                await context.Message.ReplyAsync($"Admin Roles already contains {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                            }
                        }
                        else if (context.Parameters[1].ToLower().Equals("remove"))
                        {
                            if (Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Contains(id))
                            {
                                Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Remove(id);
                                await context.Message.ReplyAsync($"Removed {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} from Admin Roles");
                            }
                            else
                            {
                                await context.Message.ReplyAsync(
                                    $"Admin Roles doesn't contain {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                            }
                        }
                        else
                        {
                            await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`.");
                        }
                    }
                    else
                    {
                        await context.Message.ReplyAsync($"That is not a valid roleId");
                    }
                }
                #endregion AdminRoles

                #region ModRoles
                else if (context.Parameters[0].ToLower().Equals("moderatorroles") || context.Parameters[0].ToLower().Equals("modroles"))
                {
                    if (context.Parameters.Count == 1)
                    {
                        await context.Message.ReplyAsync($"Please enter a config option");

                        return;
                    }
                    if (context.Parameters.Count == 2)
                    {
                        await context.Message.ReplyAsync($"Please enter a roleId");

                        return;
                    }
                    ulong id;
                    if (ulong.TryParse(context.Parameters[2], out id) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(id)))
                    {
                        if (context.Parameters[1].ToLower().Equals("add"))
                        {
                            if (!_guildConfig.ModRoleIds.Contains(id))
                            {
                                _guildConfig.ModRoleIds.Add(id);
                                await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to Moderator Roles");
                            }
                            else
                            {
                                await context.Message.ReplyAsync($"Moderator Roles already contains {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                            }
                        }
                        else if (context.Parameters[1].ToLower().Equals("remove"))
                        {
                            if (_guildConfig.ModRoleIds.Contains(id))
                            {
                                {
                                    _guildConfig.ModRoleIds.Remove(id);
                                    await context.Message.ReplyAsync(
                                        $"Removed {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} from Moderator Roles");
                                }
                            }
                            else
                            {
                                await context.Message.ReplyAsync(
                                    $"Moderator Roles doesn't contain {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                            }
                        }
                        else
                        {
                            await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`.");
                        }
                    }
                    else
                    {
                        await context.Message.ReplyAsync($"That is not a valid roleId");
                    }
                }
                #endregion ModRoles

                #region UserRoles

                else if (context.Parameters[0].ToLower().Equals("userroles"))
                {
                    if (config.GetPermissions(context) >= Command.PermissionLevels.Admin)
                    {
                        if (context.Parameters.Count == 1)
                        {
                            await context.Message.ReplyAsync($"Please enter a config option");

                            return;
                        }
                        if (context.Parameters.Count == 2)
                        {
                            await context.Message.ReplyAsync($"Please enter a roleId");

                            return;
                        }
                        ulong id;
                        if (ulong.TryParse(context.Parameters[2], out id) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(id)))
                        {
                            if (context.Parameters[1].ToLower().Equals("add"))
                            {
                                if (!_guildConfig.UserRoles.Any(rg => rg.Value.Contains(id)))
                                {
                                    context.Parameters.RemoveRange(0, 3);
                                    if (context.Parameters.Count != 0)
                                    {
                                        if (_guildConfig.UserRoles.Any(rg => rg.Key.ToLower() == context.Parameters.Rejoin().ToLower()))
                                        {
                                            string groupName = _guildConfig.UserRoles.First(rg => rg.Key.ToLower() == context.Parameters.Rejoin().ToLower()).Key;
                                            _guildConfig.UserRoles[groupName].Add(id);
                                            await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to User Roles in group {_guildConfig.UserRoles.First(rg => rg.Key.ToLower() == context.Parameters.Rejoin().ToLower()).Key}");
                                        }
                                        else
                                        {
                                            _guildConfig.UserRoles.Add(context.Parameters.Rejoin(), new List <ulong>());
                                            _guildConfig.UserRoles[context.Parameters.Rejoin()].Add(id);
                                            await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to User Roles in new group {_guildConfig.UserRoles.First(rg => rg.Key.ToLower() == context.Parameters.Rejoin().ToLower()).Key}");
                                        }
                                    }
                                    else
                                    {
                                        try
                                        {
                                            _guildConfig.UserRoles.Add("", new List <ulong>());
                                        }
                                        catch (ArgumentException ex)
                                        {
                                            await Core.Logger.LogErrorMessage(ex, context);
                                        }

                                        _guildConfig.UserRoles[""].Add(id);
                                        await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to User Roles");
                                    }
                                }
                                else
                                {
                                    await context.Message.ReplyAsync($"User Roles already contains {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                                }
                            }
                            else if (context.Parameters[1].ToLower().Equals("remove"))
                            {
                                if (_guildConfig.UserRoles.Any(rg => rg.Value.Contains(id)))
                                {
                                    {
                                        _guildConfig.UserRoles.First(rg => rg.Value.Contains(id)).Value.Remove(id);
                                        await context.Message.ReplyAsync(
                                            $"Removed {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} from User Roles");
                                    }
                                }
                                else
                                {
                                    await context.Message.ReplyAsync($"User Roles doesn't contain {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                                }
                            }
                            else
                            {
                                await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`.");
                            }
                        }
                        else
                        {
                            await context.Message.ReplyAsync($"That is not a valid roleId");
                        }
                    }
                    else
                    {
                        await context.Message.ReplyAsync($"You don't have the permissions to do that");
                    }
                }

                #endregion UserRoles

                #region RequiresRoles

                else if (context.Parameters[0].ToLower().Equals("requiresroles"))
                {
                    if (context.Parameters.Count == 1)
                    {
                        await context.Message.ReplyAsync($"Please enter a config option");

                        return;
                    }
                    var checkRegex = new Regex(@"requiresroles (add|remove) \d{17,19} requires \d{17,19}", RegexOptions.IgnoreCase);
                    if (!checkRegex.IsMatch(context.ParameterString.ToLower().Replace("  ", " ")))
                    {
                        await context.Message.ReplyAsync($"Syntax incorrect. Please use the syntax {_guildConfig.Prefix}config requiresRoles <add|remove> [roleid] requires [requiredRoleId]");

                        return;
                    }
                    if (ulong.TryParse(context.Parameters[2], out ulong roleId) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(roleId)) &&
                        ulong.TryParse(context.Parameters[4], out ulong requiredRoleId) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(requiredRoleId)))
                    {
                        if (_guildConfig.RequiresRoles == null)
                        {
                            _guildConfig.RequiresRoles = new Dictionary <ulong, List <ulong> >();
                        }
                        if (context.Parameters[1].ToLower().Equals("add"))
                        {
                            if (_guildConfig.RequiresRoles.ContainsKey(roleId))
                            {
                                if (_guildConfig.RequiresRoles[roleId] == null || !_guildConfig.RequiresRoles[roleId].Contains(requiredRoleId))
                                {
                                    if (_guildConfig.RequiresRoles[roleId] == null)
                                    {
                                        _guildConfig.RequiresRoles[roleId] = new List <ulong>();
                                    }
                                    _guildConfig.RequiresRoles[roleId].Add(requiredRoleId);
                                    await context.Message.ReplyAsync($"{context.Guild.Roles.First(r => r.Id == roleId).Name} now requires {context.Guild.Roles.First(r => r.Id == requiredRoleId).Name}");
                                }
                                else
                                {
                                    await context.Message.ReplyAsync($"{context.Guild.Roles.First(r => r.Id == roleId).Name} already requires {context.Guild.Roles.First(r => r.Id == requiredRoleId).Name}");
                                }
                            }
                            else
                            {
                                _guildConfig.RequiresRoles[roleId] = new List <ulong> {
                                    requiredRoleId
                                };
                                await context.Message.ReplyAsync($"{context.Guild.Roles.First(r => r.Id == roleId).Name} now requires {context.Guild.Roles.First(r => r.Id == requiredRoleId).Name}");
                            }
                        }
                        else if (context.Parameters[1].ToLower().Equals("remove"))
                        {
                            if (_guildConfig.RequiresRoles.ContainsKey(roleId))
                            {
                                if (_guildConfig.RequiresRoles[roleId] == null || !_guildConfig.RequiresRoles[roleId].Contains(requiredRoleId))
                                {
                                    await context.Message.ReplyAsync($"That requirement does not exist");
                                }
                                else
                                {
                                    _guildConfig.RequiresRoles[roleId].RemoveAll(r => r == requiredRoleId);
                                    if (!_guildConfig.RequiresRoles[roleId].Any())
                                    {
                                        _guildConfig.RequiresRoles.Remove(roleId);
                                    }
                                    await context.Message.ReplyAsync($"{context.Guild.Roles.First(r => r.Id == roleId).Name} no longer requires {context.Guild.Roles.First(r => r.Id == requiredRoleId).Name}");
                                }
                            }
                            else
                            {
                                await context.Message.ReplyAsync($"That requirement does not exist");
                            }
                        }
                    }
                    else
                    {
                        await context.Message.ReplyAsync($"One of those is not a valid roleId");
                    }
                }

                #endregion RequiresRoles

                #region Prefix

                else if (context.Parameters[0].ToLower().Equals("prefix"))
                {
                    try
                    {
                        context.Parameters.RemoveAt(0);
                        _guildConfig.Prefix = context.Parameters.Rejoin();
                        if (context.Message.Content.EndsWith('"') && context.Parameters[0].ToCharArray()[0].Equals('"'))
                        {
                            _guildConfig.Prefix = new Regex("\"(.*?)\"").Match(context.Message.Content).Value.Trim('"');
                        }
                        await context.Message.ReplyAsync($"The prefix has been set to `{_guildConfig.Prefix}`");
                    }
                    catch (Exception ex)
                    {
                        await Core.Logger.LogErrorMessage(ex, context);

                        _guildConfig.Prefix = "";
                        await context.Message.ReplyAsync($"The prefix has been reset to the default of `{Core.GetGlobalPrefix()}`");
                    }
                }

                #endregion Prefix

                #region Logging

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

                            await context.Message.ReplyAsync(m);
                        }
                        else
                        {
                            if (ulong.TryParse(context.Parameters[2], out ulong cId) &&
                                context.Guild.TextChannels.Any(c => c.Id == cId))
                            {
                                if (!_guildConfig.MessageLoggingIgnoreChannels.Contains(cId))
                                {
                                    _guildConfig.MessageLoggingIgnoreChannels.Add(cId);
                                    await context.Message.ReplyAsync($"No longer logging <#{cId}>");
                                }
                                else
                                {
                                    _guildConfig.MessageLoggingIgnoreChannels.Remove(cId);
                                    await context.Message.ReplyAsync($"Resuming logging <#{cId}>");
                                }
                            }
                            else
                            {
                                await context.Message.ReplyAsync("Invalid Channel Id");
                            }
                        }
                    }
                }
                #endregion Logging

                #region MutedRoleId

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

                        return;
                    }
                    else
                    {
                        ulong roleId;
                        if (ulong.TryParse(context.Parameters[0], out roleId) && (context.Guild.Roles.Any(r => r.Id == roleId) || roleId == 0))
                        {
                            _guildConfig.MutedRoleId = roleId;
                            Core.SaveGuildConfig(_guildConfig);
                            await context.Message.ReplyAsync($"MutedRoleId is now `{roleId}`");
                        }
                        else
                        {
                            await context.Message.ReplyAsync("Invalid Role Id");
                        }
                    }
                }

                #endregion MutedRoleId

                #region Verification

                else if (context.Parameters[0].ToLower().Equals("verification"))
                {
                    if (context.Parameters[1].ToLower().Equals("roleid"))
                    {
                        if (context.Parameters.Count == 2)
                        {
                            var roleId = _guildConfig.VerifiedRole;
                            if (roleId == 0)
                            {
                                await context.Message.ReplyAsync("Verification is disabled on this server");
                            }
                            else
                            {
                                await context.Message.ReplyAsync(
                                    $"Verification role is  `{context.Guild.Roles.First(g => g.Id == roleId).Name}`");
                            }
                        }
                        else if (ulong.TryParse(context.Parameters[2], out ulong roleId) && (context.Guild.Roles.Any(g => g.Id == roleId) || roleId == 0))
                        {
                            _guildConfig.VerifiedRole = roleId;
                            if (roleId != 0)
                            {
                                await context.Message.ReplyAsync(
                                    $"Verification role set to `{context.Guild.Roles.First(g => g.Id == roleId).Name}`");
                            }
                            else
                            {
                                await context.Message.ReplyAsync("Verification role cleared. Verification is off for this server.");
                            }
                        }
                        else
                        {
                            await context.Message.ReplyAsync("Invalid RoleId");
                        }
                    }
                    else if (context.Parameters[1].ToLower().Equals("message"))
                    {
                        string pref = Core.GetPrefix(context);

                        string message = context.ParameterString.Replace("  ", " ").Remove(0, "verification message".Length);

                        if (string.IsNullOrEmpty(message) && string.IsNullOrEmpty(_guildConfig.VerifiedMessage))
                        {
                            await context.Message.ReplyAsync("Verification is disabled on this server. Please make sure you have a roleid and message set.");

                            return;
                        }
                        else if (!string.IsNullOrEmpty(message))
                        {
                            _guildConfig.VerifiedMessage = message;
                        }
                        await context.Message.ReplyAsync("Example verification message:");

                        string vm = $"Hey {context.Author.Username}! To get verified on **{context.Guild.Name}** reply to this message with the hidden code in the message below\n\n"
                                    + _guildConfig.VerifiedMessage;

                        string verificationMessage =
                            VerificationEngine.InsertCodeInMessage(vm, VerificationEngine.GetVerificationCode(context.Author.Id, context.Guild.Id));

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

                #endregion Verification

                #region JoinMessage

                else if (context.Parameters[0].ToLower().Equals("joinmessage"))
                {
                    if (context.Parameters.Count >= 2 && context.Parameters[1].ToLower().Equals("channelid"))
                    {
                        if (context.Parameters.Count == 2)
                        {
                            var channelId = _guildConfig.JoinMessageChannelId;
                            if (channelId == 0)
                            {
                                await context.Message.ReplyAsync("Join messages are disabled on this server");
                            }
                            else
                            {
                                await context.Message.ReplyAsync($"Join message channel is <#{channelId}>");
                            }
                        }
                        else if (ulong.TryParse(context.Parameters[2], out ulong channelId) && (context.Guild.Channels.Any(g => g.Id == channelId) || channelId == 0))
                        {
                            _guildConfig.JoinMessageChannelId = channelId;
                            if (channelId != 0)
                            {
                                await context.Message.ReplyAsync(
                                    $"Join message channel set to <#{channelId}>");
                            }
                            else
                            {
                                await context.Message.ReplyAsync("Join message channel cleared. Join messages are off for this server.");
                            }
                        }
                        else
                        {
                            await context.Message.ReplyAsync("Invalid Channel Id");
                        }
                    }
                    else if (context.Parameters.Count >= 2 && context.Parameters[1].ToLower().Equals("message"))
                    {
                        string message = context.ParameterString.Replace("  ", " ").Remove(0, "joinmessage message".Length);

                        if (string.IsNullOrEmpty(message) && string.IsNullOrEmpty(_guildConfig.VerifiedMessage))
                        {
                            await context.Message.ReplyAsync("Join messages are disabled on this server. Please make sure you have a channelid and message set.");

                            return;
                        }
                        else if (!string.IsNullOrEmpty(message))
                        {
                            _guildConfig.JoinMessage = message;
                        }

                        await context.Message.ReplyAsync("Example join message:");

                        await context.Message.ReplyAsync(VerificationEngine.ConstructWelcomeMessage(_guildConfig.JoinMessage, context.Author));
                    }
                    else
                    {
                        await context.Message.ReplyAsync("Invalid Option");
                    }
                }

                #endregion JoinMessage

                #region AutoRole

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

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

                #endregion AutoRole

                #region Antispam

                else if (context.Parameters[0].ToLower().Equals("antispam"))
                {
                    if (context.Parameters.Count != 2)
                    {
                        await context.Message.ReplyAsync("Please a single-word option");
                    }
                    else
                    {
                        switch (context.Parameters[1].ToLower())
                        {
                        case "none":
                            _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.None;
                            await context.Message.ReplyAsync("Antispam Level **None** has been selected! The following options are enabled: None");

                            break;

                        case "basic":
                            _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.Basic;
                            await context.Message.ReplyAsync("Antispam Level **Basic** has been selected! The following options are enabled: None (yet)");

                            break;

                        case "advanced":
                            _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.Advanced;
                            await context.Message.ReplyAsync("Antispam Level **Advanced** has been selected! The following options are enabled: Username Link Kicking");

                            break;

                        case "aggressive":
                            _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.Aggressive;
                            await context.Message.ReplyAsync("Antispam Level **Aggressive** has been selected! The following options are enabled: Username Link Banning");

                            break;

                        case "activeraid":
                            _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.ActiveRaid;
                            await context.Message.ReplyAsync("Antispam Level **ActiveRaid** has been selected! The following options are enabled: Username Link Banning");

                            break;

                        default:
                            await context.Message.ReplyAsync("That is not an available option. You can select: `None`, `Basic`, `Advanced`, `Aggressive`, and `ActiveRaid`");

                            break;
                        }
                    }
                }

                #endregion Antispam

                #region Points

                else if (context.Parameters[0].ToLower().Equals("points"))
                {
                    if (context.Parameters[1].ToLower().Equals("true") || context.Parameters[1].ToLower().Contains("enable"))
                    {
                        _guildConfig.PointsEnabled = true;
                    }
                    else if (context.Parameters[1].ToLower().Equals("false") || context.Parameters[1].ToLower().Contains("disable"))
                    {
                        _guildConfig.PointsEnabled = false;
                    }
                    else
                    {
                        await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`.");
                    }
                    await context.Message.ReplyAsync($"Points Enabled: {_guildConfig.PointsEnabled}");
                }

                #endregion Points

                #region Trusted Role

                else if (context.Parameters.FirstOrDefault().Equals("trustedrole"))
                {
                    context.Parameters.RemoveAt(0);
                    if (context.Parameters.Count() < 2)
                    {
                        await context.Message.ReplyAsync("Please provide an action and a numeric value.");
                    }

                    var command  = context.Parameters[0];
                    var argument = context.Parameters[1];
                    if (ulong.TryParse(argument, out ulong argumentAsLong))
                    {
                        switch (command)
                        {
                        case "setrole":
                            _guildConfig.TrustedRoleId = argumentAsLong;
                            break;

                        case "threshold":
                            _guildConfig.TrustedRolePointThreshold = argumentAsLong;
                            break;

                        default:
                            await context.Message.ReplyAsync($"Unknown property `{command}`.");

                            break;
                        }
                    }
                    else
                    {
                        context.Message.ReplyAsync($"Invalid argument `{argument}`.");
                    }
                }
                #endregion

                else
                {
                    await context.Message.ReplyAsync($"Unknown property `{context.Parameters[0]}`.");
                }

                Core.SaveGuildConfig(_guildConfig);
            };
            commands.Add(config);

            Command audit = new Command("audit");
            audit.Description        = "Get the audit log of mod commands for the server";
            audit.RequiredPermission = Command.PermissionLevels.Admin;
            audit.ToExecute         += async(context) =>
            {
                var   log         = Core.GetAuditLog(context.Guild.Id);
                ulong uIdToSearch = 0;
                if (!context.Parameters.IsEmpty())
                {
                    if (ulong.TryParse(context.Parameters[0], out uIdToSearch))
                    {
                        log = log.Where(l => l.UserId == uIdToSearch).ToList();
                    }
                }
                log = log.OrderByDescending(l => l.MessageId).ToList();

                string message = string.Empty;
                int    i       = 0;
                while (i < log.Count)
                {
                    var cmd = log.ElementAt(i++);
                    if (message.Length + $"{cmd.Message} - <@{cmd.UserId}>\n".Length > 2000)
                    {
                        break;
                    }
                    message = $"{cmd.Message} - <@{cmd.UserId}>\n" + message;
                }
                var builder = new EmbedBuilder()
                              .WithDescription(message)
                              .WithColor(new Color(0xFFFF00));
                await context.Channel.SendMessageAsync("", embed : builder.Build());
            };
            commands.Add(audit);

            Command runas = new Command("runas");
            runas.RequiredPermission = Command.PermissionLevels.BotOwner;
            runas.ToExecute         += async(context) =>
            {
                if (context.Parameters.Count < 2 || context.Message.GetMentionedUsers().Count != 1)
                {
                    await context.Message.ReplyAsync("Please make sure to provide a userid and a command to run");

                    return;
                }
                try
                {
                    // >runas [UserId] [Command] [Params]
                    ParsedCommand runContext = new ParsedCommand();
                    runContext = context;
                    string message   = context.ParameterString.Trim();
                    var    runAsUser = context.Guild.GetUser(ulong.Parse(context.Parameters[0].Trim("<@! >".ToCharArray())));

                    if (Core.Commands.HasElement(c => context.Parameters[1].Equals(c.Name) || c.Aliases.Any(a => context.Parameters[1].Equals(a)), out Command cmd))
                    {
                        runContext.RawCommand = cmd;
                        // remove first two params (uid and command)
                        message = new Regex(Regex.Escape(context.Parameters[0])).Replace(message, "", 1).TrimStart();
                        message = new Regex(Regex.Escape(context.Parameters[1])).Replace(message, "", 1).Trim();

                        // set new parameters
                        runContext.ParameterString = message;
                        runContext.Parameters      = message.Split().Where(p => !string.IsNullOrEmpty(p.Trim())).ToList();
                        runContext.Author          = runAsUser;

                        await runContext.Execute();
                    }
                    else
                    {
                        await context.Message.ReplyAsync("Invalid command");
                    }
                }
                catch (Exception ex)
                {
                    await context.Message.ReplyAsync($"```{ex.Message}```");

                    await context.Message.ReplyAsync($"```{ex.StackTrace}```");

                    throw ex;
                }
            };
            commands.Add(runas);

            Command dumpdb = new Command("dumpdb");
            dumpdb.RequiredPermission = Command.PermissionLevels.BotOwner;
            dumpdb.ToExecute         += async(context) =>
            {
                File.WriteAllText("dump/guilds.json", JsonConvert.SerializeObject((Core.DatabaseEngine as MongoEngine).GetGuildIdsFromDb(), Formatting.Indented));
                foreach (var guildid in (Core.DatabaseEngine as MongoEngine).GetGuildIdsFromDb())
                {
                    // CustomCommands
                    try
                    {
                        File.WriteAllText($"dump/{guildid}-customCommands.json", JsonConvert.SerializeObject(Core.GetCustomCommands(ulong.Parse(guildid)), Formatting.Indented));
                        //Console.WriteLine(JsonConvert.SerializeObject(Core.GetCustomCommands(ulong.Parse(guildid)), Formatting.Indented));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Exception {ex.Message} occured dumping customCommands for {guildid}\n{ex.StackTrace}");
                        System.Threading.Thread.Sleep(1);
                    }
                    Console.WriteLine("Dumped CustomCommands");
                    // Config
                    try
                    {
                        File.WriteAllText($"dump/{guildid}-config.json", JsonConvert.SerializeObject(Core.GetGuildConfig(ulong.Parse(guildid)), Formatting.Indented));
                        //Console.WriteLine(JsonConvert.SerializeObject(Core.GetGuildConfig(ulong.Parse(guildid)), Formatting.Indented));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Exception {ex.Message} occured dumping config for {guildid}\n{ex.StackTrace}");
                        System.Threading.Thread.Sleep(1);
                    }
                    Console.WriteLine("Dumped config");
                    // Bans
                    try
                    {
                        File.WriteAllText($"dump/ {guildid}-bans.json", JsonConvert.SerializeObject(Core.GetBansFromGuild(ulong.Parse(guildid)), Formatting.Indented));
                        //Console.WriteLine(JsonConvert.SerializeObject(Core.GetBansFromGuild(ulong.Parse(guildid)), Formatting.Indented));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Exception {ex.Message} occured dumping bans for {guildid}\n{ex.StackTrace}");
                        System.Threading.Thread.Sleep(1);
                    }
                    Console.WriteLine("Dumped bans");
                    // Users
                    try
                    {
                        File.WriteAllText($"dump/{guildid}-users.json", JsonConvert.SerializeObject(Core.GetAllUsers(ulong.Parse(guildid)), Formatting.Indented));
                        //Console.WriteLine(JsonConvert.SerializeObject(Core.GetAllUsers(ulong.Parse(guildid)), Formatting.Indented));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Exception {ex.Message} occured dumping users for {guildid}\n{ex.StackTrace}");
                        System.Threading.Thread.Sleep(1);
                    }
                    Console.WriteLine("Dumped users");
                    // Quotes
                    try
                    {
                        File.WriteAllText($"dunp/{guildid}-quotes.json", JsonConvert.SerializeObject(Core.GetAllQuotes(ulong.Parse(guildid)), Formatting.Indented));
                        //Console.WriteLine(JsonConvert.SerializeObject(Core.GetAllQuotes(ulong.Parse(guildid)), Formatting.Indented));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Exception {ex.Message} occured dumping quotes for {guildid}\n{ex.StackTrace}");
                        System.Threading.Thread.Sleep(1);
                    }
                    Console.WriteLine("Dumped quotes");
                    // Giveaways
                    try
                    {
                        File.WriteAllText($"dump/{guildid}-giveaways.json", JsonConvert.SerializeObject(Core.GetGiveaways(ulong.Parse(guildid)), Formatting.Indented));
                        //Console.WriteLine(JsonConvert.SerializeObject(Core.GetGiveaways(ulong.Parse(guildid)), Formatting.Indented));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Exception {ex.Message} occured dumping giveaways for {guildid}\n{ex.StackTrace}");
                        System.Threading.Thread.Sleep(1);
                    }
                    Console.WriteLine("Dumped quotes");
                }
                await context.Message.ReplyAsync("Done!");
            };
            commands.Add(dumpdb);

            return(commands);
        }
Example #3
0
        public List <Command> GetTestCommands()
        {
            List <Command> TestCommands = new List <Command>();

            Command listEmotes = new Command("listemotes");

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

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

            TestCommands.Add(listEmotes);

            Command updateDB = new Command("updateDB");

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

                int newUsers     = 0;
                int updatedUsers = 0;

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

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

            TestCommands.Add(updateDB);

            Command IdInfo = new Command("idInfo");

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

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

            TestCommands.Add(IdInfo);

            Command DBStats = new Command("dbstats");

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

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

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

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

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

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

            TestCommands.Add(DBStats);

            Command addwarning = new Command("oldwarning");

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

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

                    return;
                }

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

            TestCommands.Add(addwarning);

            Command archivePins = new Command("archivePins");

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

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

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

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

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

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

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


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

                    return;
                }

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

                    return;
                }

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

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

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

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

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

            Command cmdp = new Command("cmd");

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

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

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

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

            Command decryptDb = new Command("decryptDb");

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

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

            TestCommands.Add(decryptDb);

            Command repairDb = new Command("repairDb");

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


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

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

            TestCommands.Add(repairDb);

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

            Command config = new Command("config");

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

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

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

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

                #region ModRoles

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

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

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

                #endregion ModRoles

                #region UserRoles

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

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

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

                #endregion UserRoles

                #region Twitter

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

                #endregion Twitter

                #region Prefix

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

                #endregion Prefix

                #region Logging

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

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

                #endregion Logging

                #region MutedRoleId

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

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

                #endregion MutedRoleId

                #region Verification

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

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

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

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

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

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

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

                #endregion Verification

                #region Points

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

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

                #endregion Points

                #region GlobalBanOptOut

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

                #endregion GlobalBanOptOut

                #region AutoRole

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

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

                #endregion AutoRole

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

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

            ConfigCommands.Add(config);

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

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

            ConfigCommands.Add(levels);

            return(ConfigCommands);
        }
Example #5
0
        public List <Command> Load()
        {
            List <Command> commands = new List <Command>();

            Command UserRoles = new Command("userroles");

            UserRoles.Description = $"Show all user roles on this server";
            UserRoles.Usage       = "userroles";
            UserRoles.ToExecute  += async(context) =>
            {
                string prefix  = Core.GetPrefix(context);
                string message = $"You can use `{prefix}iam` and `{prefix}iamnot` with any of these roles:\n _\\*(Pro tip: You can add/remove more than one role at a time by seperating each role with a comma like `{prefix}iam role0, role1, role2, etc`)*_\n";
                var    config  = Core.GetGuildConfig(context.Guild.Id);
                foreach (var group in config.UserRoles.Where(g => !string.IsNullOrEmpty(g.Key) && g.Value.Count > 0).OrderBy(g => g.Key))
                {
                    message += $"**{group.Key}:** ";
                    foreach (var role in context.Guild.Roles
                             .Where(r => group.Value.Contains(r.Id))
                             .OrderBy(r => r.Name))
                    {
                        if ((context.Author as SocketGuildUser).Roles.Contains(role))
                        {
                            message += "\\✔ ";
                        }
                        else
                        {
                            message += "✘";
                        }
                        message += $"`{role.Name}`, ";
                    }
                    message += "\n";
                }

                if (config.UserRoles[""].Count > 0)
                {
                    message += $"**Ungrouped:** ";
                    foreach (var role in context.Guild.Roles
                             .Where(r => config.UserRoles[""].Contains(r.Id))
                             .OrderBy(r => r.Name))
                    {
                        if ((context.Author as SocketGuildUser).Roles.Contains(role))
                        {
                            message += "\\✔ ";
                        }
                        else
                        {
                            message += "✘";
                        }
                        message += $"`{role.Name}`, ";
                    }
                    message += "\n";
                }

                message = message.Trim(' ', ',', '\n');
                //message += $"\n You can also use `{prefix}rolestore save` to backup your assigned roles";

                foreach (var str in message.MessageSplit())
                {
                    await context.Message.ReplyAsync(str);
                }
            };
            commands.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(context) =>
            {
                List <IMessage> messagesToDelete = new List <IMessage>();

                if (context.Parameters.IsEmpty())
                {
                    messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription("Please select a role to join").WithColor(new Color(0xFFFF00)).Build()).Result);
                }

                foreach (var roleName in context.ParameterString.Trim(',', ' ').Split(','))
                {
                    if (string.IsNullOrWhiteSpace(roleName))
                    {
                        continue;
                    }
                    var roles = context.Guild.Roles.Where(r => r.Name.ToLower().Contains(roleName.ToLower().Trim()))
                                .Where(r => Core.GetGuildConfig(context.Guild.Id).UserRoles.Any(rg => rg.Value.Contains(r.Id)));
                    if (!roles.Any())
                    {
                        messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"Could not find any user roles matching `{roleName}`").WithColor(new Color(0xFFFF00)).Build()).Result);
                    }
                    else
                    {
                        try
                        {
                            var role = roles.Any(r => r.Name.ToLower() == roleName.ToLower())
                                ? roles.First(r => r.Name.ToLower() == roleName.ToLower())
                                : roles.First();
                            if (context.Guild.GetUser(context.Author.Id).Roles.Any(r => r.Id == role.Id))
                            {
                                messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"You already have that role!").WithColor(new Color(0xFFFF00)).Build()).Result);
                            }
                            else
                            {
                                await context.Guild.GetUser(context.Author.Id).AddRoleAsync(role);

                                messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"Assigned you `{role.Name}`").WithColor(new Color(0x9B00)).Build()).Result);
                            }
                        }
                        catch (Exception e)
                        {
                            await Core.Logger.LogErrorMessage(e, context);

                            messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"I may not have permissions to do that").WithColor(new Color(0xFFFF00)).Build()).Result);
                        }
                    }
                }

                await Task.Delay(15 * 1000);

                try
                {
                    messagesToDelete.ForEach(m => GenericBot.ClearedMessageIds.Add(m.Id));
                    messagesToDelete.Add(context.Message);
                    await(context.Channel as ITextChannel).DeleteMessagesAsync(messagesToDelete);
                }
                catch (Exception ex)
                {
                    await Core.Logger.LogErrorMessage(ex, context);

                    try
                    {
                        foreach (var m in messagesToDelete)
                        {
                            await m.DeleteAsync();
                        }
                    }
                    catch (Exception e)
                    {
                        await Core.Logger.LogErrorMessage(e, context);
                    }
                }
            };
            commands.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(context) =>
            {
                List <IMessage> messagesToDelete = new List <IMessage>();

                if (context.Parameters.IsEmpty())
                {
                    messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription("Please select a role to remove").WithColor(new Color(0xFFFF00)).Build()).Result);
                }

                foreach (var roleName in context.ParameterString.Trim(',', ' ').Split(','))
                {
                    if (string.IsNullOrWhiteSpace(roleName))
                    {
                        continue;
                    }
                    var roles = context.Guild.Roles.Where(r => r.Name.ToLower().Contains(roleName.ToLower().Trim()))
                                .Where(r => Core.GetGuildConfig(context.Guild.Id).UserRoles.Any(rg => rg.Value.Contains(r.Id)));
                    if (!roles.Any())
                    {
                        messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"Could not find any user roles matching `{roleName}`").WithColor(new Color(0xFFFF00)).Build()).Result);
                    }
                    else
                    {
                        try
                        {
                            var role = roles.Any(r => r.Name.ToLower() == roleName.ToLower())
                                ? roles.First(r => r.Name.ToLower() == roleName.ToLower())
                                : roles.First();
                            if (!context.Guild.GetUser(context.Author.Id).Roles.Any(r => r.Id == role.Id))
                            {
                                messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"You don't have that role!").WithColor(new Color(0xFFFF00)).Build()).Result);
                            }
                            else
                            {
                                await context.Guild.GetUser(context.Author.Id).RemoveRoleAsync(role);

                                messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"Removed `{role.Name}`").WithColor(new Color(0x9B00)).Build()).Result);
                            }
                        }
                        catch (Exception e)
                        {
                            await Core.Logger.LogErrorMessage(e, context);

                            messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"I may not have permissions to do that").WithColor(new Color(0xFFFF00)).Build()).Result);
                        }
                    }
                }

                await Task.Delay(15 * 1000);

                try
                {
                    messagesToDelete.ForEach(m => GenericBot.ClearedMessageIds.Add(m.Id));
                    messagesToDelete.Add(context.Message);
                    await(context.Channel as ITextChannel).DeleteMessagesAsync(messagesToDelete);
                }
                catch (Exception ex)
                {
                    await Core.Logger.LogErrorMessage(ex, context);

                    try
                    {
                        foreach (var m in messagesToDelete)
                        {
                            await m.DeleteAsync();
                        }
                    }
                    catch (Exception e)
                    {
                        await Core.Logger.LogErrorMessage(e, context);
                    }
                }
            };
            commands.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(context) =>
            {
                string message = $"Roles matching `{context.ParameterString}`:\n";
                foreach (var role in context.Guild.Roles.Where(r => Regex.IsMatch(r.Name, context.ParameterString, RegexOptions.IgnoreCase)).OrderBy(r => r.Name))
                {
                    message += $"{role.Name} (`{role.Id}`)\n";
                }

                foreach (var str in message.MessageSplit())
                {
                    await context.Message.ReplyAsync(str);
                }
            };
            commands.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(context) =>
            {
                if (context.Parameters.IsEmpty())
                {
                    await context.Message.ReplyAsync($"You need to specify a role");

                    return;
                }
                string result = "";
                foreach (var role in context.Guild.Roles.OrderByDescending(r => r.Position).Where(r => new Regex(context.ParameterString, 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.MessageSplit('\n'))
                {
                    await context.Message.ReplyAsync(str);
                }
            };
            commands.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(context) =>
            {
                RestRole role;

                role = context.Guild.CreateRoleAsync(context.ParameterString, GuildPermissions.None).Result;
                await context.Message.ReplyAsync($"Created new role `{role.Name}` with ID `{role.Id}`");
            };
            commands.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(context) =>
            {
                RestRole role;

                role = context.Guild.CreateRoleAsync(context.ParameterString, GuildPermissions.None).Result;
                var gc = Core.GetGuildConfig(context.Guild.Id);
                if (gc.UserRoles.ContainsKey(""))
                {
                    gc.UserRoles[""].Add(role.Id);
                }
                else
                {
                    gc.UserRoles.Add("", new List <ulong> {
                        role.Id
                    });
                }
                Core.SaveGuildConfig(gc);
                await context.Message.ReplyAsync($"Created new role `{role.Name}` with ID `{role.Id}` and added it to the user roles");
            };
            commands.Add(createUserRole);


            Command verify = new Command("verify");

            verify.RequiredPermission = Command.PermissionLevels.User;
            verify.ToExecute         += async(context) =>
            {
                List <SocketUser> users = new List <SocketUser>();
                var guildConfig         = Core.GetGuildConfig(context.Guild.Id);

                if (context.Parameters.IsEmpty())
                {
                    if ((context.Author as SocketGuildUser).Roles.Any(r => r.Id == guildConfig.VerifiedRole))
                    {
                        await context.Message.ReplyAsync("You're already verified");

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


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

                    return;
                }

                if ((string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !context.Guild.Roles.Any(r => r.Id == guildConfig.VerifiedRole)))
                {
                    await context.Message.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 **{context.Guild.Name}** reply to this message with the hidden code in the message below\n\n"
                                     + Core.GetGuildConfig(context.Guild.Id).VerifiedMessage;

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

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

                        success.Add(user);
                    }
                    catch (Exception ex)
                    {
                        await Core.Logger.LogErrorMessage(ex, context);

                        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 context.Message.ReplyAsync(reply);
            };
            commands.Add(verify);

            Command verifyall = new Command("verifyall");

            verifyall.RequiredPermission = Command.PermissionLevels.User;
            verifyall.ToExecute         += async(context) =>
            {
                var guildConfig = Core.GetGuildConfig(context.Guild.Id);

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

                    return;
                }
                if (string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !context.Guild.Roles.Any(r => r.Id == guildConfig.VerifiedRole))
                {
                    await context.Message.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 <SocketGuildUser> users = context.Guild.Users.Where(u => !u.Roles.Any(r => r.Id == guildConfig.VerifiedRole)).ToList();

                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 **{context.Guild.Name}** reply to this message with the hidden code in the message below\n\n"
                                     + Core.GetGuildConfig(context.Guild.Id).VerifiedMessage;

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

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

                        success.Add(user);
                    }
                    catch (Exception ex)
                    {
                        await Core.Logger.LogErrorMessage(ex, context);

                        failed.Add(user);
                    }
                }

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

                foreach (var message in reply.MessageSplit())
                {
                    await context.Message.ReplyAsync(reply);
                }
            };
            commands.Add(verifyall);

            return(commands);
        }
Example #6
0
        public List <Command> Load()
        {
            List <Command> commands = new List <Command>();

            Command UserRoles = new Command("userroles");

            UserRoles.Description = $"Show all user roles on this server";
            UserRoles.Usage       = "userroles";
            UserRoles.ToExecute  += async(context) =>
            {
                string prefix  = Core.GetPrefix(context);
                string message = $"You can use `{prefix}iam` and `{prefix}iamnot` with any of these roles:\n _\\*(Pro tip: You can add/remove more than one role at a time by seperating each role with a comma like `{prefix}iam role0, role1, role2, etc`)*_\n";
                var    config  = Core.GetGuildConfig(context.Guild.Id);
                if (config.UserRoles.Count < 1 ||
                    config.UserRoles
                    .Sum(kvp => kvp.Value
                         .Count(r => context.Guild.Roles.Any(gr => gr.Id == r))) < 1)
                {
                    await context.Message.ReplyAsync("It looks like there are no available user roles on this server. If you believe this is in error, please talk to your server administrators!");

                    return;
                }
                foreach (var group in config.UserRoles.Where(g => !string.IsNullOrEmpty(g.Key) && g.Value.Count > 0).OrderBy(g => g.Key))
                {
                    message += $"**{group.Key}:** ";
                    foreach (var role in context.Guild.Roles
                             .Where(r => group.Value.Contains(r.Id))
                             .OrderBy(r => r.Name))
                    {
                        if ((context.Author as SocketGuildUser).Roles.Contains(role))
                        {
                            message += "\\✔ ";
                        }
                        else
                        {
                            message += "✘";
                        }
                        message += $"`{role.Name}`, ";
                    }
                    message += "\n";
                }

                if (config.UserRoles.Keys.Contains("") && config.UserRoles[""].Count > 0)
                {
                    message += $"**Ungrouped:** ";
                    foreach (var role in context.Guild.Roles
                             .Where(r => config.UserRoles[""].Contains(r.Id))
                             .OrderBy(r => r.Name))
                    {
                        if ((context.Author as SocketGuildUser).Roles.Contains(role))
                        {
                            message += "\\✔ ";
                        }
                        else
                        {
                            message += "✘";
                        }
                        message += $"`{role.Name}`, ";
                    }
                    message += "\n";
                }

                message  = message.Trim(' ', ',', '\n');
                message += $"\n You can also use `{prefix}rolestore save` to backup your assigned roles";

                foreach (var str in message.MessageSplit())
                {
                    await context.Message.ReplyAsync(str);
                }
            };
            commands.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(context) =>
            {
                List <IMessage> messagesToDelete = new List <IMessage>();
                DatabaseUser    dbUser           = Core.GetUserFromGuild(context.Author.Id, context.Guild.Id);

                if (context.Parameters.IsEmpty())
                {
                    messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription("Please select a role to join").WithColor(new Color(0xFFFF00)).Build()).Result);
                }

                foreach (var roleName in context.ParameterString.Trim(',', ' ').Split(','))
                {
                    if (string.IsNullOrWhiteSpace(roleName))
                    {
                        continue;
                    }
                    var roles = context.Guild.Roles.Where(r => r.Name.ToLower().Contains(roleName.ToLower().Trim()))
                                .Where(r => Core.GetGuildConfig(context.Guild.Id).UserRoles.Any(rg => rg.Value.Contains(r.Id)));
                    if (!roles.Any())
                    {
                        messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"Could not find any user roles matching `{roleName}`").WithColor(new Color(0xFFFF00)).Build()).Result);
                    }
                    else
                    {
                        try
                        {
                            var role = roles.Any(r => r.Name.ToLower() == roleName.ToLower())
                                ? roles.First(r => r.Name.ToLower() == roleName.ToLower())
                                : roles.First();
                            dbUser.AddStoredRole(role.Id);
                            if (context.Guild.GetUser(context.Author.Id).Roles.Any(r => r.Id == role.Id))
                            {
                                messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"You already have that role!").WithColor(new Color(0xFFFF00)).Build()).Result);
                            }
                            else
                            {
                                await context.Guild.GetUser(context.Author.Id).AddRoleAsync(role);

                                messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"Assigned you `{role.Name}`").WithColor(new Color(0x9B00)).Build()).Result);
                            }
                        }
                        catch (Exception e)
                        {
                            await Core.Logger.LogErrorMessage(e, context);

                            messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"I may not have permissions to do that").WithColor(new Color(0xFFFF00)).Build()).Result);
                        }
                    }
                }
                Core.SaveUserToGuild(dbUser, context.Guild.Id);

                await Task.Delay(15 * 1000);

                try
                {
                    messagesToDelete.ForEach(m => Program.ClearedMessageIds.Add(m.Id));
                    messagesToDelete.Add(context.Message);
                    await(context.Channel as ITextChannel).DeleteMessagesAsync(messagesToDelete);
                }
                catch (Exception ex)
                {
                    await Core.Logger.LogErrorMessage(ex, context);

                    try
                    {
                        foreach (var m in messagesToDelete)
                        {
                            await m.DeleteAsync();
                        }
                    }
                    catch (Exception e)
                    {
                        await Core.Logger.LogErrorMessage(e, context);
                    }
                }
            };
            commands.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(context) =>
            {
                List <IMessage> messagesToDelete = new List <IMessage>();
                DatabaseUser    dbUser           = Core.GetUserFromGuild(context.Author.Id, context.Guild.Id);

                if (context.Parameters.IsEmpty())
                {
                    messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription("Please select a role to remove").WithColor(new Color(0xFFFF00)).Build()).Result);
                }

                foreach (var roleName in context.ParameterString.Trim(',', ' ').Split(','))
                {
                    if (string.IsNullOrWhiteSpace(roleName))
                    {
                        continue;
                    }
                    var roles = context.Guild.Roles.Where(r => r.Name.ToLower().Contains(roleName.ToLower().Trim()))
                                .Where(r => Core.GetGuildConfig(context.Guild.Id).UserRoles.Any(rg => rg.Value.Contains(r.Id)));
                    if (!roles.Any())
                    {
                        messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"Could not find any user roles matching `{roleName}`").WithColor(new Color(0xFFFF00)).Build()).Result);
                    }
                    else
                    {
                        try
                        {
                            var role = roles.Any(r => r.Name.ToLower() == roleName.ToLower())
                                ? roles.First(r => r.Name.ToLower() == roleName.ToLower())
                                : roles.First();
                            dbUser.RemoveStoredRole(role.Id);
                            if (!context.Guild.GetUser(context.Author.Id).Roles.Any(r => r.Id == role.Id))
                            {
                                messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"You don't have that role!").WithColor(new Color(0xFFFF00)).Build()).Result);
                            }
                            else
                            {
                                await context.Guild.GetUser(context.Author.Id).RemoveRoleAsync(role);

                                messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"Removed `{role.Name}`").WithColor(new Color(0x9B00)).Build()).Result);
                            }
                        }
                        catch (Exception e)
                        {
                            await Core.Logger.LogErrorMessage(e, context);

                            messagesToDelete.Add(context.Channel.SendMessageAsync("", embed: new EmbedBuilder().WithDescription($"I may not have permissions to do that").WithColor(new Color(0xFFFF00)).Build()).Result);
                        }
                    }
                }
                Core.SaveUserToGuild(dbUser, context.Guild.Id);

                await Task.Delay(15 * 1000);

                try
                {
                    messagesToDelete.ForEach(m => Program.ClearedMessageIds.Add(m.Id));
                    messagesToDelete.Add(context.Message);
                    await(context.Channel as ITextChannel).DeleteMessagesAsync(messagesToDelete);
                }
                catch (Exception ex)
                {
                    await Core.Logger.LogErrorMessage(ex, context);

                    try
                    {
                        foreach (var m in messagesToDelete)
                        {
                            await m.DeleteAsync();
                        }
                    }
                    catch (Exception e)
                    {
                        await Core.Logger.LogErrorMessage(e, context);
                    }
                }
            };
            commands.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(context) =>
            {
                string message = $"Roles matching `{context.ParameterString}`:\n";
                foreach (var role in context.Guild.Roles.Where(r => Regex.IsMatch(r.Name, context.ParameterString, RegexOptions.IgnoreCase)).OrderBy(r => r.Name))
                {
                    message += $"{role.Name} (`{role.Id}`)\n";
                }

                foreach (var str in message.MessageSplit())
                {
                    await context.Message.ReplyAsync(str);
                }
            };
            commands.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(context) =>
            {
                if (context.Parameters.IsEmpty())
                {
                    await context.Message.ReplyAsync($"You need to specify a role");

                    return;
                }
                string result = "";
                foreach (var role in context.Guild.Roles.OrderByDescending(r => r.Position).Where(r => new Regex(context.ParameterString, 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.MessageSplit('\n'))
                {
                    await context.Message.ReplyAsync(str);
                }
            };
            commands.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(context) =>
            {
                RestRole role;

                role = context.Guild.CreateRoleAsync(name: context.ParameterString, permissions: GuildPermissions.None, null, false, null).Result;
                await context.Message.ReplyAsync($"Created new role `{role.Name}` with ID `{role.Id}`");
            };
            commands.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(context) =>
            {
                RestRole role;

                role = context.Guild.CreateRoleAsync(context.ParameterString, GuildPermissions.None, null, false, null).Result;
                var gc = Core.GetGuildConfig(context.Guild.Id);
                if (gc.UserRoles.ContainsKey(""))
                {
                    gc.UserRoles[""].Add(role.Id);
                }
                else
                {
                    gc.UserRoles.Add("", new List <ulong> {
                        role.Id
                    });
                }
                Core.SaveGuildConfig(gc);
                await context.Message.ReplyAsync($"Created new role `{role.Name}` with ID `{role.Id}` and added it to the user roles");
            };
            commands.Add(createUserRole);


            Command verify = new Command("verify");

            verify.RequiredPermission = Command.PermissionLevels.User;
            verify.ToExecute         += async(context) =>
            {
                List <SocketUser> users = new List <SocketUser>();
                var guildConfig         = Core.GetGuildConfig(context.Guild.Id);

                if (context.Parameters.IsEmpty())
                {
                    if ((context.Author as SocketGuildUser).Roles.Any(r => r.Id == guildConfig.VerifiedRole))
                    {
                        await context.Message.ReplyAsync("You're already verified");

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


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

                    return;
                }

                if ((string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !context.Guild.Roles.Any(r => r.Id == guildConfig.VerifiedRole)))
                {
                    await context.Message.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 **{context.Guild.Name}** reply to this message with the hidden code in the message below\n\n"
                                     + Core.GetGuildConfig(context.Guild.Id).VerifiedMessage;

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

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

                        success.Add(user);
                    }
                    catch (Exception ex)
                    {
                        await Core.Logger.LogErrorMessage(ex, context);

                        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 context.Message.ReplyAsync(reply);
            };
            commands.Add(verify);

            Command verifyall = new Command("verifyall");

            verifyall.RequiredPermission = Command.PermissionLevels.Admin;
            verifyall.ToExecute         += async(context) =>
            {
                var guildConfig = Core.GetGuildConfig(context.Guild.Id);

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

                    return;
                }
                if (string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !context.Guild.Roles.Any(r => r.Id == guildConfig.VerifiedRole))
                {
                    await context.Message.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 <SocketGuildUser> users = context.Guild.Users.Where(u => !u.Roles.Any(r => r.Id == guildConfig.VerifiedRole)).ToList();

                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 **{context.Guild.Name}** reply to this message with the hidden code in the message below\n\n"
                                     + Core.GetGuildConfig(context.Guild.Id).VerifiedMessage;

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

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

                        success.Add(user);
                    }
                    catch (Exception ex)
                    {
                        await Core.Logger.LogErrorMessage(ex, context);

                        failed.Add(user);
                    }
                }

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

                foreach (var message in reply.MessageSplit())
                {
                    await context.Message.ReplyAsync(reply);
                }
            };
            commands.Add(verifyall);

            Command roleeveryone = new Command("roleeveryone");

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

                    var role = context.Guild.GetRole(id);
                    foreach (var u in context.Guild.Users)
                    {
                        if (context.Parameters[0].ToLower().Equals("remove") && u.Roles.Any(r => r.Id == id))
                        {
                            await u.RemoveRoleAsync(role);

                            i++;
                        }
                        if (context.Parameters[0].ToLower().Equals("add") && !u.Roles.Any(r => r.Id == id))
                        {
                            await u.AddRoleAsync(role);

                            i++;
                        }
                    }
                    string addrem = context.Parameters[0].ToLower().Equals("add") ? "Added" : "Removed";
                    string tofrom = context.Parameters[0].ToLower().Equals("add") ? "to" : "from";
                    await context.Message.ReplyAsync($"{addrem} `{role.Name}` {tofrom} `{i}` users.");
                }
                else
                {
                    await context.Message.ReplyAsync("Invalid Role Id");
                }
            };
            commands.Add(roleeveryone);

            Command rolestore = new Command("rolestore");

            rolestore.Description = "Save or restore all of your userroles";
            rolestore.Usage       = "roleveryone [save|restore]";
            rolestore.ToExecute  += async(context) =>
            {
                var dbUser = Core.GetUserFromGuild(context.Author.Id, context.Guild.Id);
                if (Core.GetGuildConfig(context.Guild.Id).UserRoles == null || Core.GetGuildConfig(context.Guild.Id).UserRoles.Count < 1 ||
                    Core.GetGuildConfig(context.Guild.Id).UserRoles.Values.Aggregate((a, b) => a.Concat(b).ToList()).Count < 1)
                {
                    await context.Message.ReplyAsync("This server has no user-assignable roles!");

                    return;
                }
                var userRoles = Core.GetGuildConfig(context.Guild.Id).UserRoles.Values.Aggregate((a, b) => a.Concat(b).ToList());

                if (context.Parameters.Count == 0)
                {
                    var storedRoles = dbUser.GetStoredRoles()
                                      .Intersect(context.Guild.Roles.Select(r => r.Id));
                    var restoreableRoles = storedRoles
                                           .Where(r => !(context.Author as SocketGuildUser).Roles.Any(u => u.Id == r))
                                           .Intersect(userRoles);
                    if (storedRoles.Any())
                    {
                        if (restoreableRoles.Any())
                        {
                            await context.Message
                            .ReplyAsync($"You have `{storedRoles.Count()}` saved roles, and `{restoreableRoles.Count()}` that can be restored! " +
                                        $"The restoreable roles are: {restoreableRoles.Select(r => $"`{context.Guild.GetRole(r).Name}`").ToList().SumAnd()}");
                        }
                        else
                        {
                            await context.Message
                            .ReplyAsync($"You have `{storedRoles.Count()}` saved roles, but you already have them all, so none of them can be restored!");
                        }
                    }
                    else
                    {
                        await context.Message.ReplyAsync("You have no saved roles!");
                    }
                }
                else if (context.Parameters.Count == 1)
                {
                    if (context.Parameters[0].ToLower().Equals("save"))
                    {
                        foreach (var role in (context.Author as SocketGuildUser).Roles.Select(r => r.Id))
                        {
                            dbUser.AddStoredRole(role);
                        }
                        var storedRoles = dbUser.GetStoredRoles()
                                          .Intersect(context.Guild.Roles.Select(r => r.Id))
                                          .Intersect(userRoles);
                        await context.Message.ReplyAsync($"You have `{storedRoles.Count()}` roles you will be able to restore now");

                        Core.SaveUserToGuild(dbUser, context.Guild.Id);
                    }
                    else if (context.Parameters[0].ToLower().Equals("restore"))
                    {
                        var storedRoles = dbUser.GetStoredRoles()
                                          .Intersect(context.Guild.Roles.Select(r => r.Id))
                                          .Where(r => !(context.Author as SocketGuildUser).Roles.Any(u => u.Id == r))
                                          .Intersect(userRoles);
                        if (storedRoles.Count() == 0)
                        {
                            await context.Message.ReplyAsync($"You are missing no saved roles");
                        }
                        else
                        {
                            try
                            {
                                await(context.Author as SocketGuildUser).AddRolesAsync(storedRoles.Select(r => context.Guild.GetRole(r)));
                                await context.Message.ReplyAsync($"Successfully restored `{storedRoles.Count()}` roles for you!");
                            }
                            catch
                            {
                                var missingRoles = dbUser.GetStoredRoles()
                                                   .Intersect(context.Guild.Roles.Select(r => r.Id))
                                                   .Where(r => !(context.Author as SocketGuildUser).Roles.Any(u => u.Id == r))
                                                   .Intersect(userRoles);
                                await context.Message.ReplyAsync($"Uh oh. You had `{storedRoles.Count()}` roles that could be restored, but `{missingRoles.Count()}` couldn't be restored.");
                            }
                        }
                    }
                    else
                    {
                        await context.Message.ReplyAsync("Invalid parameter. Use rolestore with no parameters to see available roles, or `save` or `restore`");
                    }
                }
                else
                {
                    await context.Message.ReplyAsync("Use rolestore with no parameters to see available roles, or `save` or `restore`");
                }
            };
            commands.Add(rolestore);

            return(commands);
        }
Example #7
0
        public List <Command> Load()
        {
            List <Command> commands = new List <Command>();

            Command config = new Command("config");

            config.RequiredPermission = Command.PermissionLevels.Admin;
            config.Description        = "Configure the bot or see current config";
            config.Usage      = "config <option> <value>";
            config.ToExecute += async(context) =>
            {
                var _guildConfig = Core.GetGuildConfig(context.Guild.Id);
                if (context.Parameters.IsEmpty())
                {
                    string currentConfig =
                        $"Prefix: `{Core.GetPrefix(context)}`\n" +
                        $"Admin Roles: `{JsonConvert.SerializeObject(_guildConfig.AdminRoleIds)}`\n" +
                        $"Mod Roles: `{JsonConvert.SerializeObject(_guildConfig.ModRoleIds)}`\n" +
                        $"User Roles: `{JsonConvert.SerializeObject(_guildConfig.UserRoles)}`\n" +
                        $"Logging\n" +
                        $"    Channel Id: `{_guildConfig.LoggingChannelId}`\n" +
                        $"    Ignored Channels: `{JsonConvert.SerializeObject(_guildConfig.MessageLoggingIgnoreChannels)}`\n" +
                        $"Muted Role Id: `{_guildConfig.MutedRoleId}`\n" +
                        $"Verification:\n" +
                        $"    Role Id: `{_guildConfig.VerifiedRole}`\n" +
                        $"    Message: Do `{Core.GetPrefix(context)}config verification message` to see the message\n" +
                        $"Auto Roles: `{JsonConvert.SerializeObject(_guildConfig.AutoRoleIds)}`";

                    await context.Message.ReplyAsync(currentConfig);
                }

                #region AdminRoles
                else if (context.Parameters[0].ToLower().Equals("adminroles"))
                {
                    if (context.Parameters.Count == 1)
                    {
                        await context.Message.ReplyAsync($"Please enter a config option");

                        return;
                    }
                    if (context.Parameters.Count == 2)
                    {
                        await context.Message.ReplyAsync($"Please enter a roleId");

                        return;
                    }
                    ulong id;
                    if (ulong.TryParse(context.Parameters[2], out id) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(id)))
                    {
                        if (context.Parameters[1].ToLower().Equals("add"))
                        {
                            if (!Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Contains(id))
                            {
                                Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Add(id);
                                await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to Admin Roles");
                            }
                            else
                            {
                                await context.Message.ReplyAsync($"Admin Roles already contains {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                            }
                        }
                        else if (context.Parameters[1].ToLower().Equals("remove"))
                        {
                            if (Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Contains(id))
                            {
                                Core.GetGuildConfig(context.Guild.Id).AdminRoleIds.Remove(id);
                                await context.Message.ReplyAsync($"Removed {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} from Admin Roles");
                            }
                            else
                            {
                                await context.Message.ReplyAsync(
                                    $"Admin Roles doesn't contain {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                            }
                        }
                        else
                        {
                            await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`.");
                        }
                    }
                    else
                    {
                        await context.Message.ReplyAsync($"That is not a valid roleId");
                    }
                }
                #endregion AdminRoles

                #region ModRoles
                else if (context.Parameters[0].ToLower().Equals("moderatorroles") || context.Parameters[0].ToLower().Equals("modroles"))
                {
                    if (context.Parameters.Count == 1)
                    {
                        await context.Message.ReplyAsync($"Please enter a config option");

                        return;
                    }
                    if (context.Parameters.Count == 2)
                    {
                        await context.Message.ReplyAsync($"Please enter a roleId");

                        return;
                    }
                    ulong id;
                    if (ulong.TryParse(context.Parameters[2], out id) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(id)))
                    {
                        if (context.Parameters[1].ToLower().Equals("add"))
                        {
                            if (!_guildConfig.ModRoleIds.Contains(id))
                            {
                                _guildConfig.ModRoleIds.Add(id);
                                await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to Moderator Roles");
                            }
                            else
                            {
                                await context.Message.ReplyAsync($"Moderator Roles already contains {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                            }
                        }
                        else if (context.Parameters[1].ToLower().Equals("remove"))
                        {
                            if (_guildConfig.ModRoleIds.Contains(id))
                            {
                                {
                                    _guildConfig.ModRoleIds.Remove(id);
                                    await context.Message.ReplyAsync(
                                        $"Removed {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} from Moderator Roles");
                                }
                            }
                            else
                            {
                                await context.Message.ReplyAsync(
                                    $"Moderator Roles doesn't contain {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                            }
                        }
                        else
                        {
                            await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`.");
                        }
                    }
                    else
                    {
                        await context.Message.ReplyAsync($"That is not a valid roleId");
                    }
                }
                #endregion ModRoles

                #region UserRoles

                else if (context.Parameters[0].ToLower().Equals("userroles"))
                {
                    if (config.GetPermissions(context) >= Command.PermissionLevels.Admin)
                    {
                        if (context.Parameters.Count == 1)
                        {
                            await context.Message.ReplyAsync($"Please enter a config option");

                            return;
                        }
                        if (context.Parameters.Count == 2)
                        {
                            await context.Message.ReplyAsync($"Please enter a roleId");

                            return;
                        }
                        ulong id;
                        if (ulong.TryParse(context.Parameters[2], out id) && context.Guild.Roles.Select(r => r.Id).Any(u => u.Equals(id)))
                        {
                            if (context.Parameters[1].ToLower().Equals("add"))
                            {
                                if (!_guildConfig.UserRoles.Any(rg => rg.Value.Contains(id)))
                                {
                                    context.Parameters.RemoveRange(0, 3);
                                    if (context.Parameters.Count != 0)
                                    {
                                        if (_guildConfig.UserRoles.Any(rg => rg.Key.ToLower() == context.Parameters.Rejoin().ToLower()))
                                        {
                                            string groupName = _guildConfig.UserRoles.First(rg => rg.Key.ToLower() == context.Parameters.Rejoin().ToLower()).Key;
                                            _guildConfig.UserRoles[groupName].Add(id);
                                        }
                                        else
                                        {
                                            _guildConfig.UserRoles.Add(context.Parameters.Rejoin(), new List <ulong>());
                                            _guildConfig.UserRoles[context.Parameters.Rejoin()].Add(id);
                                        }
                                        await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to User Roles in group {_guildConfig.UserRoles.First(rg => rg.Key.ToLower() == context.Parameters.Rejoin().ToLower()).Key}");
                                    }
                                    else
                                    {
                                        try
                                        {
                                            _guildConfig.UserRoles.Add("", new List <ulong>());
                                        }
                                        catch (ArgumentException ex)
                                        {
                                            await Core.Logger.LogErrorMessage(ex, context);
                                        }

                                        _guildConfig.UserRoles[""].Add(id);
                                        await context.Message.ReplyAsync($"Added {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} to User Roles");
                                    }
                                }
                                else
                                {
                                    await context.Message.ReplyAsync($"User Roles already contains {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                                }
                            }
                            else if (context.Parameters[1].ToLower().Equals("remove"))
                            {
                                if (_guildConfig.UserRoles.Any(rg => rg.Value.Contains(id)))
                                {
                                    {
                                        _guildConfig.UserRoles.First(rg => rg.Value.Contains(id)).Value.Remove(id);
                                        await context.Message.ReplyAsync(
                                            $"Removed {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name} from User Roles");
                                    }
                                }
                                else
                                {
                                    await context.Message.ReplyAsync($"User Roles doesn't contain {context.Guild.Roles.FirstOrDefault(r => r.Id == id).Name}");
                                }
                            }
                            else
                            {
                                await context.Message.ReplyAsync($"Unknown property `{context.Parameters[1]}`.");
                            }
                        }
                        else
                        {
                            await context.Message.ReplyAsync($"That is not a valid roleId");
                        }
                    }
                    else
                    {
                        await context.Message.ReplyAsync($"You don't have the permissions to do that");
                    }
                }

                #endregion UserRoles

                #region Prefix

                else if (context.Parameters[0].ToLower().Equals("prefix"))
                {
                    try
                    {
                        context.Parameters.RemoveAt(0);
                        _guildConfig.Prefix = context.Parameters.Rejoin();
                        if (context.Message.Content.EndsWith('"') && context.Parameters[0].ToCharArray()[0].Equals('"'))
                        {
                            _guildConfig.Prefix = new Regex("\"(.*?)\"").Match(context.Message.Content).Value.Trim('"');
                        }
                        await context.Message.ReplyAsync($"The prefix has been set to `{_guildConfig.Prefix}`");
                    }
                    catch (Exception ex)
                    {
                        await Core.Logger.LogErrorMessage(ex, context);

                        _guildConfig.Prefix = "";
                        await context.Message.ReplyAsync($"The prefix has been reset to the default of `{Core.GetGlobalPrefix()}`");
                    }
                }

                #endregion Prefix

                #region Logging

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

                            await context.Message.ReplyAsync(m);
                        }
                        else
                        {
                            if (ulong.TryParse(context.Parameters[2], out ulong cId) &&
                                context.Guild.TextChannels.Any(c => c.Id == cId))
                            {
                                if (!_guildConfig.MessageLoggingIgnoreChannels.Contains(cId))
                                {
                                    _guildConfig.MessageLoggingIgnoreChannels.Add(cId);
                                    await context.Message.ReplyAsync($"No longer logging <#{cId}>");
                                }
                                else
                                {
                                    _guildConfig.MessageLoggingIgnoreChannels.Remove(cId);
                                    await context.Message.ReplyAsync($"Resuming logging <#{cId}>");
                                }
                            }
                            else
                            {
                                await context.Message.ReplyAsync("Invalid Channel Id");
                            }
                        }
                    }
                }
                #endregion Logging

                #region MutedRoleId

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

                        return;
                    }
                    else
                    {
                        ulong roleId;
                        if (ulong.TryParse(context.Parameters[0], out roleId) && (context.Guild.Roles.Any(r => r.Id == roleId) || roleId == 0))
                        {
                            _guildConfig.MutedRoleId = roleId;
                            Core.SaveGuildConfig(_guildConfig);
                            await context.Message.ReplyAsync($"MutedRoleId is now `{roleId}`");
                        }
                        else
                        {
                            await context.Message.ReplyAsync("Invalid Role Id");
                        }
                    }
                }

                #endregion MutedRoleId

                #region Verification

                else if (context.Parameters[0].ToLower().Equals("verification"))
                {
                    if (context.Parameters[1].ToLower().Equals("roleid"))
                    {
                        if (context.Parameters.Count == 2)
                        {
                            var roleId = _guildConfig.VerifiedRole;
                            if (roleId == 0)
                            {
                                await context.Message.ReplyAsync("Verification is disabled on this server");
                            }
                            else
                            {
                                await context.Message.ReplyAsync(
                                    $"Verification role is  `{context.Guild.Roles.First(g => g.Id == roleId).Name}`");
                            }
                        }
                        else if (ulong.TryParse(context.Parameters[2], out ulong roleId) && (context.Guild.Roles.Any(g => g.Id == roleId) || roleId == 0))
                        {
                            _guildConfig.VerifiedRole = roleId;
                            if (roleId != 0)
                            {
                                await context.Message.ReplyAsync(
                                    $"Verification role set to `{context.Guild.Roles.First(g => g.Id == roleId).Name}`");
                            }
                            else
                            {
                                await context.Message.ReplyAsync("Verification role cleared. Verification is off for this server.");
                            }
                        }
                        else
                        {
                            await context.Message.ReplyAsync("Invalid RoleId");
                        }
                    }
                    else if (context.Parameters[1].ToLower().Equals("message"))
                    {
                        string pref = Core.GetPrefix(context);

                        string message = context.ParameterString.Replace("  ", " ").Remove(0, "verification message".Length);

                        if (string.IsNullOrEmpty(message) && string.IsNullOrEmpty(_guildConfig.VerifiedMessage))
                        {
                            await context.Message.ReplyAsync("Verification is disabled on this server. Please make sure you have a roleid and message set.");

                            return;
                        }
                        else if (!string.IsNullOrEmpty(message))
                        {
                            _guildConfig.VerifiedMessage = message;
                        }
                        await context.Message.ReplyAsync("Example verification message:");

                        string vm = $"Hey {context.Author.Username}! To get verified on **{context.Guild.Name}** reply to this message with the hidden code in the message below\n\n"
                                    + _guildConfig.VerifiedMessage;

                        string verificationMessage =
                            VerificationEngine.InsertCodeInMessage(vm, VerificationEngine.GetVerificationCode(context.Author.Id, context.Guild.Id));

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

                #endregion Verification

                #region JoinMessage

                else if (context.Parameters[0].ToLower().Equals("joinmessage"))
                {
                    if (context.Parameters.Count >= 2 && context.Parameters[1].ToLower().Equals("channelid"))
                    {
                        if (context.Parameters.Count == 2)
                        {
                            var channelId = _guildConfig.JoinMessageChannelId;
                            if (channelId == 0)
                            {
                                await context.Message.ReplyAsync("Join messages are disabled on this server");
                            }
                            else
                            {
                                await context.Message.ReplyAsync($"Join message channel is <#{channelId}>");
                            }
                        }
                        else if (ulong.TryParse(context.Parameters[2], out ulong channelId) && (context.Guild.Channels.Any(g => g.Id == channelId) || channelId == 0))
                        {
                            _guildConfig.JoinMessageChannelId = channelId;
                            if (channelId != 0)
                            {
                                await context.Message.ReplyAsync(
                                    $"Join message channel set to <#{channelId}>");
                            }
                            else
                            {
                                await context.Message.ReplyAsync("Join message channel cleared. Join messages are off for this server.");
                            }
                        }
                        else
                        {
                            await context.Message.ReplyAsync("Invalid Channel Id");
                        }
                    }
                    else if (context.Parameters.Count >= 2 && context.Parameters[1].ToLower().Equals("message"))
                    {
                        string message = context.ParameterString.Replace("  ", " ").Remove(0, "joinmessage message".Length);

                        if (string.IsNullOrEmpty(message) && string.IsNullOrEmpty(_guildConfig.VerifiedMessage))
                        {
                            await context.Message.ReplyAsync("Join messages are disabled on this server. Please make sure you have a channelid and message set.");

                            return;
                        }
                        else if (!string.IsNullOrEmpty(message))
                        {
                            _guildConfig.JoinMessage = message;
                        }

                        await context.Message.ReplyAsync("Example join message:");

                        await context.Message.ReplyAsync(VerificationEngine.ConstructWelcomeMessage(_guildConfig.JoinMessage, context.Author));
                    }
                    else
                    {
                        await context.Message.ReplyAsync("Invalid Option");
                    }
                }

                #endregion JoinMessage

                #region AutoRole

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

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

                #endregion AutoRole

                #region Antispam

                else if (context.Parameters[0].ToLower().Equals("antispam"))
                {
                    if (context.Parameters.Count != 2)
                    {
                        await context.Message.ReplyAsync("Please a single-word option");
                    }
                    else
                    {
                        switch (context.Parameters[1].ToLower())
                        {
                        case "none":
                            _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.None;
                            await context.Message.ReplyAsync("Antispam Level **None** has been selected! The following options are enabled: None");

                            break;

                        case "basic":
                            _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.Basic;
                            await context.Message.ReplyAsync("Antispam Level **Basic** has been selected! The following options are enabled: None (yet)");

                            break;

                        case "advanced":
                            _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.Advanced;
                            await context.Message.ReplyAsync("Antispam Level **Advanced** has been selected! The following options are enabled: Username Link Kicking");

                            break;

                        case "aggressive":
                            _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.Aggressive;
                            await context.Message.ReplyAsync("Antispam Level **Aggressive** has been selected! The following options are enabled: Username Link Banning");

                            break;

                        case "activeraid":
                            _guildConfig.AntispamLevel = GuildConfig.AntiSpamLevel.ActiveRaid;
                            await context.Message.ReplyAsync("Antispam Level **ActiveRaid** has been selected! The following options are enabled: Username Link Banning");

                            break;

                        default:
                            await context.Message.ReplyAsync("That is not an available option. You can select: `None`, `Basic`, `Advanced`, `Aggressive`, and `ActiveRaid`");

                            break;
                        }
                    }
                }

                #endregion Antispam

                else
                {
                    await context.Message.ReplyAsync($"Unknown property `{context.Parameters[0]}`.");
                }

                Core.SaveGuildConfig(_guildConfig);
            };
            commands.Add(config);

            Command audit = new Command("audit");
            audit.Description        = "Get the audit log of mod commands for the server";
            audit.RequiredPermission = Command.PermissionLevels.Admin;
            audit.ToExecute         += async(context) =>
            {
                var   log         = Core.GetAuditLog(context.Guild.Id);
                ulong uIdToSearch = 0;
                if (!context.Parameters.IsEmpty())
                {
                    if (ulong.TryParse(context.Parameters[0], out uIdToSearch))
                    {
                        log = log.Where(l => l.UserId == uIdToSearch).OrderByDescending(l => l.MessageId).ToList();
                    }
                }

                string message = string.Empty;
                int    i       = 0;
                while (i < log.Count)
                {
                    var cmd = log.ElementAt(i++);
                    if (message.Length + $"{cmd.Message} - <@{cmd.UserId}>\n".Length > 2000)
                    {
                        break;
                    }
                    message = $"{cmd.Message} - <@{cmd.UserId}>\n" + message;
                }
                var builder = new EmbedBuilder()
                              .WithDescription(message)
                              .WithColor(new Color(0xFFFF00));
                await context.Channel.SendMessageAsync("", embed : builder.Build());
            };
            commands.Add(audit);

            return(commands);
        }