Example #1
0
 private async Task <bool> IsMod(IGuildUser user)
 {
     if (user.GuildPermissions.Administrator)
     {
         return(true);
     }
     using (var db = new DbContext())
     {
         var guildRepo = new GuildRepository(db);
         var modRoleId = (await guildRepo.FetchGuildAsync(Context.Guild.Id)).ModRoleId;
         if (user.Guild.GetRole(modRoleId) != null)
         {
             if (user.RoleIds.Any(x => x == modRoleId))
             {
                 return(true);
             }
         }
         return(false);
     }
 }
Example #2
0
        public async Task CustomMute(double hours, IGuildUser userToMute, [Remainder] string reason = "No reason.")
        {
            if (hours > 168)
            {
                throw new Exception("You may not mute a user for more than a week.");
            }
            if (hours < 1)
            {
                throw new Exception("You may not mute a user for less than 1 hour.");
            }
            using (var db = new DbContext())
            {
                string time = "hours";
                if (hours == 1)
                {
                    time = "hour";
                }
                var guildRepo = new GuildRepository(db);
                var guild     = await guildRepo.FetchGuildAsync(Context.Guild.Id);

                var mutedRole = Context.Guild.GetRole(guild.MutedRoleId);
                if (mutedRole == null)
                {
                    throw new Exception($"You may not mute users if the muted role is not valid.\nPlease use the " +
                                        $"{guild.Prefix}SetMutedRole command to change that.");
                }
                var muteRepo = new MuteRepository(db);
                if (await IsMod(userToMute))
                {
                    throw new Exception("You cannot mute another mod!");
                }
                await InformSubject(Context.User, "Mute", userToMute, reason);

                await userToMute.AddRoleAsync(mutedRole);

                await muteRepo.AddMuteAsync(userToMute.Id, Context.Guild.Id, TimeSpan.FromHours(hours), DateTime.Now);

                await Logger.ModLog(Context, "Mute", new Color(255, 114, 14), reason, userToMute, $"\n**Length:** {hours} {time}");
                await ReplyAsync($"{Context.User.Mention} has successfully muted {userToMute.Mention} for {hours} {time}!");
            }
        }
Example #3
0
        public async Task ChangeDMSettings()
        {
            using (var db = new DbContext())
            {
                var guildRepo = new GuildRepository(db);
                switch ((await guildRepo.FetchGuildAsync(Context.Guild.Id)).DM)
                {
                case true:
                    await guildRepo.ModifyAsync(x => { x.DM = false; return(Task.CompletedTask); }, Context.Guild.Id);
                    await ReplyAsync($"{Context.User.Mention}, You have successfully disabled DM messages!");

                    break;

                case false:
                    await guildRepo.ModifyAsync(x => { x.DM = true; return(Task.CompletedTask); }, Context.Guild.Id);
                    await ReplyAsync($"{Context.User.Mention}, You have successfully enabled DM messages!");

                    break;
                }
            }
        }
Example #4
0
        public async Task SetNSFWRole(IRole nsfwRole)
        {
            if (nsfwRole.Position >= Context.Guild.CurrentUser.Roles.OrderByDescending(x => x.Position).First().Position)
            {
                throw new Exception("You may not set a rank role that is higher in hierarchy than DEA's highest role.");
            }
            using (var db = new DbContext())
            {
                var guildRepo = new GuildRepository(db);
                await guildRepo.ModifyAsync(x => { x.NSFWRoleId = nsfwRole.Id; return(Task.CompletedTask); }, Context.Guild.Id);

                var nsfwChannel = Context.Guild.GetChannel((await guildRepo.FetchGuildAsync(Context.Guild.Id)).NSFWChannelId);
                if (nsfwChannel != null && Context.Guild.CurrentUser.GuildPermissions.Administrator)
                {
                    await nsfwChannel.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, new OverwritePermissions().Modify(null, null, null, PermValue.Deny));

                    await nsfwChannel.AddPermissionOverwriteAsync(nsfwRole, new OverwritePermissions().Modify(null, null, null, PermValue.Allow));
                }
                await ReplyAsync($"{Context.User.Mention}, You have successfully set the NSFW role to {nsfwRole.Mention}.");
            }
        }
Example #5
0
        public async Task Unmute(IGuildUser userToUnmute, [Remainder] string reason = "No reason.")
        {
            using (var db = new DbContext())
            {
                var guildRepo   = new GuildRepository(db);
                var mutedRoleId = (await guildRepo.FetchGuildAsync(Context.Guild.Id)).MutedRoleId;
                if (userToUnmute.RoleIds.All(x => x != mutedRoleId))
                {
                    throw new Exception("You cannot unmute a user who isn't muted.");
                }
                var muteRepo = new MuteRepository(db);
                await InformSubject(Context.User, "Unmute", userToUnmute, reason);

                await userToUnmute.RemoveRoleAsync(Context.Guild.GetRole(mutedRoleId));

                await muteRepo.RemoveMuteAsync(userToUnmute.Id, Context.Guild.Id);

                await Logger.ModLog(Context, "Unmute", new Color(12, 255, 129), reason, userToUnmute);
                await ReplyAsync($"{Context.User.Mention} has successfully unmuted {userToUnmute.Mention}!");
            }
        }
Example #6
0
        public async Task CleanAsync(int count = 25, [Remainder] string reason = "No reason.")
        {
            if (count < Config.MIN_CLEAR)
            {
                throw new Exception($"You may not clear less than {Config.MIN_CLEAR} messages.");
            }
            if (count > Config.MAX_CLEAR)
            {
                throw new Exception($"You may not clear more than {Config.MAX_CLEAR} messages.");
            }
            var guild = await GuildRepository.FetchGuildAsync(Context.Guild.Id);

            if (Context.Channel.Id == guild.ModLogId || Context.Channel.Id == guild.DetailedLogsId)
            {
                throw new Exception("For security reasons, you may not use this command in a log channel.");
            }
            var messages = await Context.Channel.GetMessagesAsync(count).Flatten();

            await Context.Channel.DeleteMessagesAsync(messages);

            await Logger.ModLog(Context, "Clear", new Color(34, 59, 255), reason, null, $"\n**Quantity:** {count}");
        }
Example #7
0
        public async Task LeaveGang()
        {
            using (var db = new SQLite.Models.DbContext())
            {
                var gangRepo  = new GangRepository(db);
                var guildRepo = new GuildRepository(db);
                var gang      = await gangRepo.FetchGangAsync(Context.User.Id, Context.Guild.Id);

                var prefix = (await guildRepo.FetchGuildAsync(Context.Guild.Id)).Prefix;
                if (gang.LeaderId == Context.User.Id)
                {
                    throw new Exception($"You may not leave a gang if you are the owner. Either destroy the gang with the `{prefix}DestroyGang` command, or " +
                                        $"transfer the ownership of the gang to another member with the `{prefix}TransferLeadership` command.");
                }
                await gangRepo.RemoveMemberAsync(Context.User.Id, Context.Guild.Id);
                await ReplyAsync($"{Context.User.Mention}, You have successfully left {gang.Name}");

                var channel = await Context.Client.GetUser(gang.LeaderId).CreateDMChannelAsync();

                await channel.SendMessageAsync($"{Context.User} has left {gang.Name}.");
            }
        }
Example #8
0
        public static async Task ModLog(SocketCommandContext context, string action, Color color, string reason, IUser subject = null, string extra = "")
        {
            using (var db = new DbContext())
            {
                var guildRepo = new GuildRepository(db);
                var guild     = await guildRepo.FetchGuildAsync(context.Guild.Id);

                EmbedFooterBuilder footer = new EmbedFooterBuilder()
                {
                    IconUrl = "http://i.imgur.com/BQZJAqT.png",
                    Text    = $"Case #{guild.CaseNumber}"
                };
                EmbedAuthorBuilder author = new EmbedAuthorBuilder()
                {
                    IconUrl = context.User.GetAvatarUrl(),
                    Name    = $"{context.User.Username}#{context.User.Discriminator}"
                };

                string userText = null;
                if (subject != null)
                {
                    userText = $"\n** User:** { subject} ({ subject.Id})";
                }
                var builder = new EmbedBuilder()
                {
                    Author      = author,
                    Color       = color,
                    Description = $"**Action:** {action}{extra}{userText}\n**Reason:** {reason}",
                    Footer      = footer
                }.WithCurrentTimestamp();

                if (context.Guild.GetTextChannel(guild.ModLogChannelId) != null)
                {
                    await context.Guild.GetTextChannel(guild.ModLogChannelId).SendMessageAsync("", embed: builder);

                    await guildRepo.ModifyAsync(x => { x.CaseNumber++; return(Task.CompletedTask); }, context.Guild.Id);
                }
            }
        }
Example #9
0
        public async Task JoinNSFW()
        {
            var guild = await GuildRepository.FetchGuildAsync(Context.Guild.Id);

            var NsfwRole = Context.Guild.GetRole((ulong)guild.NsfwRoleId);

            if (NsfwRole == null)
            {
                throw new Exception("Everyone will always be able to use NSFW commands since there has been no NSFW role that has been set.\n" +
                                    $"In order to change this, an administrator may use the `{guild.Prefix}SetNSFWRole` command.");
            }
            if ((Context.User as IGuildUser).RoleIds.Any(x => x == guild.NsfwRoleId))
            {
                await(Context.User as IGuildUser).RemoveRoleAsync(NsfwRole);
                await ReplyAsync($"{Context.User.Mention}, You have successfully disabled your ability to use NSFW commands.");
            }
            else
            {
                await(Context.User as IGuildUser).AddRoleAsync(NsfwRole);
                await ReplyAsync($"{Context.User.Mention}, You have successfully enabled your ability to use NSFW commands.");
            }
        }
Example #10
0
        public static async Task Cooldown(SocketCommandContext context, string command, TimeSpan timeSpan)
        {
            using (var db = new DbContext())
            {
                var guildRepo = new GuildRepository(db);
                var builder   = new EmbedBuilder()
                {
                    Title       = $"{command} cooldown for {context.User}",
                    Description = $"{timeSpan.Hours} Hours\n{timeSpan.Minutes} Minutes\n{timeSpan.Seconds} Seconds",
                    Color       = new Color(49, 62, 255)
                };
                if ((await guildRepo.FetchGuildAsync(context.Guild.Id)).DM)
                {
                    var channel = await context.User.CreateDMChannelAsync();

                    await channel.SendMessageAsync("", embed : builder);
                }
                else
                {
                    await context.Channel.SendMessageAsync("", embed : builder);
                }
            }
        }
Example #11
0
        public async Task HelpAsync(string commandOrModule = null)
        {
            string prefix = (await GuildRepository.FetchGuildAsync(Context.Guild.Id)).Prefix;

            if (commandOrModule != null)
            {
                if (commandOrModule.StartsWith(prefix))
                {
                    commandOrModule = commandOrModule.Remove(0, prefix.Length);
                }
                foreach (var module in _service.Modules)
                {
                    if (module.Name.ToLower() == commandOrModule.ToLower())
                    {
                        var longestInModule = 0;
                        foreach (var cmd in module.Commands)
                        {
                            if (cmd.Aliases.First().Length > longestInModule)
                            {
                                longestInModule = cmd.Aliases.First().Length;
                            }
                        }
                        var moduleInfo = $"**{module.Name} Commands **: ```asciidoc\n";
                        foreach (var cmd in module.Commands)
                        {
                            moduleInfo += $"{prefix}{cmd.Aliases.First()}{new string(' ', (longestInModule + 1) - cmd.Aliases.First().Length)} :: {cmd.Summary}\n";
                        }
                        moduleInfo += "```";
                        await ReplyAsync(moduleInfo);

                        return;
                    }
                }

                foreach (var module in _service.Modules)
                {
                    foreach (var cmd in module.Commands)
                    {
                        foreach (var alias in cmd.Aliases)
                        {
                            if (alias == commandOrModule.ToLower())
                            {
                                var command = new EmbedBuilder()
                                {
                                    Title       = $"{cmd.Name}",
                                    Color       = new Color(0x00AE86),
                                    Description = $"**Description:** {cmd.Summary}\n"
                                };
                                if (cmd.Remarks != null)
                                {
                                    command.Description += $"**Usage:** `{prefix}{cmd.Remarks}`";
                                }
                                await ReplyAsync("", embed : command);

                                return;
                            }
                        }
                    }
                }
                string modules = null;
                foreach (var module in _service.Modules)
                {
                    modules += $"{module.Name}, ";
                }
                await ReplyAsync($"This command/module does not exist. Current list of modules: {modules.Substring(0, modules.Length - 2)}.");
            }
            else
            {
                var help = new EmbedBuilder()
                {
                    Title       = "Welcome to DEA",
                    Color       = new Color(0x00AE86),
                    Description = $@"DEA is a multi-purpose Discord Bot mainly known for it's infamous Cash System with multiple subtleties referencing to the show Narcos, which inspired the creation of this masterpiece.

For all information about command usage and setup on your Discord Sever, view the documentation: <https://realblazeit.github.io/DEA/>

This command may be used for view the commands for each of the following modules: System, Administration, Moderation, General, Gambling and Crime. It may also be used the view the usage of a specific command.

In order to **add DEA to your Discord Server**, click the following link: <https://discordapp.com/oauth2/authorize?client_id={Context.Client.CurrentUser.Id}&scope=bot&permissions=477195286> 

If you have any other questions, you may join the **Official DEA Discord Server:** <https://discord.me/Rush>, a server home to infamous meme events such as a raids and insanity. Join for the dankest community a man could desire."
                };

                var channel = await Context.User.CreateDMChannelAsync();

                await channel.SendMessageAsync("", embed : help);
                await ReplyAsync($"{Context.User.Mention}, you have been DMed with all the command information!");
            }
        }
Example #12
0
        private async Task HandleCommandAsync(SocketMessage s)
        {
            var msg = s as SocketUserMessage;

            if (msg == null)
            {
                return;
            }

            PrettyConsole.NewLine(msg.Content);



            var Context = new SocketCommandContext(_client, msg);

            PrettyConsole.NewLine((await GuildRepository.FetchGuildAsync(Context.Guild.Id)).Prefix);

            if (Context.User.IsBot)
            {
                return;
            }

            if (!(Context.Channel is SocketTextChannel))
            {
                return;
            }

            if (!(Context.Guild.CurrentUser as IGuildUser).GetPermissions(Context.Channel as SocketTextChannel).SendMessages)
            {
                return;
            }

            int    argPos = 0;
            string prefix = (await GuildRepository.FetchGuildAsync(Context.Guild.Id)).Prefix;

            if (msg.HasStringPrefix(prefix, ref argPos) ||
                msg.HasMentionPrefix(_client.CurrentUser, ref argPos))
            {
                PrettyConsole.Log(LogSeverity.Debug, $"Guild: {Context.Guild.Name}, User: {Context.User}", msg.Content);
                var result = await _service.ExecuteAsync(Context, argPos, _map);

                if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
                {
                    var cmd = _service.Search(Context, argPos).Commands.First().Command;
                    if (result.ErrorReason.Length == 0)
                    {
                        return;
                    }
                    switch (result.Error)
                    {
                    case CommandError.BadArgCount:
                        await msg.Channel.SendMessageAsync($"{Context.User.Mention}, You are incorrectly using this command. Usage: `{prefix}{cmd.Remarks}`");

                        break;

                    case CommandError.ParseFailed:
                        await msg.Channel.SendMessageAsync($"{Context.User.Mention}, Invalid number.");

                        break;

                    default:
                        await msg.Channel.SendMessageAsync($"{Context.User.Mention}, {result.ErrorReason}");

                        break;
                    }
                }
            }
            else if (msg.ToString().Length >= Config.MIN_CHAR_LENGTH && !msg.ToString().StartsWith(":"))
            {
                var user = await UserRepository.FetchUserAsync(Context);

                var rate = Config.TEMP_MULTIPLIER_RATE;
                if (DateTimeOffset.Now.Subtract(user.Message).TotalMilliseconds > user.MessageCooldown.TotalMilliseconds)
                {
                    await UserRepository.ModifyAsync(x => {
                        x.Cash += user.TemporaryMultiplier *user.InvestmentMultiplier;
                        x.TemporaryMultiplier = user.TemporaryMultiplier + rate;
                        x.Message             = DateTimeOffset.Now;
                        return(Task.CompletedTask);
                    }, Context);

                    await RankHandler.Handle(Context.Guild, Context.User.Id);
                }
            }
        }
Example #13
0
        public override async Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IDependencyMap map)
        {
            var user   = context.User as IGuildUser;
            var dbUser = await UserRepository.FetchUserAsync(context as SocketCommandContext);

            var guild = await GuildRepository.FetchGuildAsync(context.Guild.Id);

            switch (attribute)
            {
            case Attributes.BotOwner:
                if (!DEABot.Credentials.OwnerIds.Any(x => x == context.User.Id))
                {
                    return(PreconditionResult.FromError("Only an owner of this bot may use this command."));
                }
                break;

            case Attributes.ServerOwner:
                if (user.Guild.OwnerId != user.Id && !user.RoleIds.Any(x => guild.ModRoles.Any(y => y.RoleId == x && y.PermissionLevel >= 3)))
                {
                    return(PreconditionResult.FromError("Only the owner of this server may use this command."));
                }
                break;

            case Attributes.Admin:
                if (!(context.User as IGuildUser).GuildPermissions.Administrator && !user.RoleIds.Any(x => guild.ModRoles.Any(y => y.RoleId == x && y.PermissionLevel >= 2)))
                {
                    return(PreconditionResult.FromError("The administrator permission is required to use this command."));
                }
                break;

            case Attributes.Moderator:
                if (!user.RoleIds.Any(x => guild.ModRoles.Any(y => y.RoleId == x)))
                {
                    return(PreconditionResult.FromError("Only a moderator may use this command."));
                }
                break;

            case Attributes.Nsfw:
                if (!guild.Nsfw)
                {
                    return(PreconditionResult.FromError($"This command may not be used while NSFW is disabled. An administrator may enable with the " +
                                                        $"`{guild.Prefix}ChangeNSFWSettings` command."));
                }
                var nsfwChannel = await context.Guild.GetChannelAsync((ulong)guild.NsfwId);

                if (nsfwChannel != null && context.Channel.Id != guild.NsfwId)
                {
                    return(PreconditionResult.FromError($"You may only use this command in {(nsfwChannel as ITextChannel).Mention}."));
                }
                var nsfwRole = context.Guild.GetRole((ulong)guild.NsfwRoleId);
                if (nsfwRole != null && (context.User as IGuildUser).RoleIds.All(x => x != guild.NsfwRoleId))
                {
                    return(PreconditionResult.FromError($"You do not have permission to use this command.\nRequired role: {nsfwRole.Mention}"));
                }
                break;

            case Attributes.InGang:
                if (!(await GangRepository.InGangAsync(context.User.Id, context.Guild.Id)))
                {
                    return(PreconditionResult.FromError("You must be in a gang to use this command."));
                }
                break;

            case Attributes.NoGang:
                if (await GangRepository.InGangAsync(context.User.Id, context.Guild.Id))
                {
                    return(PreconditionResult.FromError("You may not use this command while in a gang."));
                }
                break;

            case Attributes.GangLeader:
                if (!(await GangRepository.InGangAsync(context.User.Id, context.Guild.Id)))
                {
                    return(PreconditionResult.FromError("You must be in a gang to use this command."));
                }
                break;

            case Attributes.Jump:
                if (dbUser.Cash < guild.JumpRequirement)
                {
                    return(PreconditionResult.FromError($"You do not have the permission to use this command.\nRequired cash: {guild.JumpRequirement.ToString("C", Config.CI)}."));
                }
                break;

            case Attributes.Steal:
                if (dbUser.Cash < guild.StealRequirement)
                {
                    return(PreconditionResult.FromError($"You do not have the permission to use this command.\nRequired cash: {guild.StealRequirement.ToString("C", Config.CI)}."));
                }
                break;

            case Attributes.Bully:
                if (dbUser.Cash < guild.BullyRequirement)
                {
                    return(PreconditionResult.FromError($"You do not have the permission to use this command.\nRequired cash: {guild.BullyRequirement.ToString("C", Config.CI)}."));
                }
                break;

            case Attributes.Rob:
                if (dbUser.Cash < guild.RobRequirement)
                {
                    return(PreconditionResult.FromError($"You do not have the permission to use this command.\nRequired cash: {guild.RobRequirement.ToString("C", Config.CI)}."));
                }
                break;

            case Attributes.FiftyX2:
                if (dbUser.Cash < guild.FiftyX2Requirement)
                {
                    return(PreconditionResult.FromError($"You do not have the permission to use this command.\nRequired cash: {guild.FiftyX2Requirement.ToString("C", Config.CI)}."));
                }
                break;

            default:
                throw new Exception($"ERROR: The {attribute} attribute does not exist!");
            }
            return(PreconditionResult.FromSuccess());
        }
Example #14
0
        public async Task Invest(string investString = null)
        {
            var guild = await GuildRepository.FetchGuildAsync(Context.Guild.Id);

            var user = await UserRepository.FetchUserAsync(Context);

            double cash = user.Cash;

            switch (investString)
            {
            case "line":
                if (Config.LINE_COST > cash)
                {
                    await ReplyAsync($"{Context.User.Mention}, you do not have enough money. Balance: {cash.ToString("C", Config.CI)}");

                    break;
                }
                if (user.MessageCooldown == Config.LINE_COOLDOWN)
                {
                    await ReplyAsync($"{Context.User.Mention}, you have already purchased this investment.");

                    break;
                }
                await UserRepository.EditCashAsync(Context, -Config.LINE_COST);

                await UserRepository.ModifyAsync(x => { x.MessageCooldown = Config.LINE_COOLDOWN; return(Task.CompletedTask); }, Context);
                await ReplyAsync($"{Context.User.Mention}, don't forget to wipe your nose when you are done with that line.");

                break;

            case "pound":
            case "lb":
                if (Config.POUND_COST > cash)
                {
                    await ReplyAsync($"{Context.User.Mention}, you do not have enough money. Balance: {cash.ToString("C", Config.CI)}");

                    break;
                }
                if (user.InvestmentMultiplier >= Config.POUND_MULTIPLIER)
                {
                    await ReplyAsync($"{Context.User.Mention}, you already purchased this investment.");

                    break;
                }
                await UserRepository.EditCashAsync(Context, -Config.POUND_COST);

                await UserRepository.ModifyAsync(x => { x.InvestmentMultiplier = Config.POUND_MULTIPLIER; return(Task.CompletedTask); }, Context);
                await ReplyAsync($"{Context.User.Mention}, ***DOUBLE CASH SMACK DAB CENTER N***A!***");

                break;

            case "kg":
            case "kilo":
            case "kilogram":
                if (Config.KILO_COST > cash)
                {
                    await ReplyAsync($"{Context.User.Mention}, you do not have enough money. Balance: {cash.ToString("C", Config.CI)}");

                    break;
                }
                if (user.InvestmentMultiplier != Config.POUND_MULTIPLIER)
                {
                    await ReplyAsync($"{Context.User.Mention}, you must purchase the pound of cocaine investment before buying this one.");

                    break;
                }
                if (user.InvestmentMultiplier >= Config.KILO_MULTIPLIER)
                {
                    await ReplyAsync($"{Context.User.Mention}, you already purchased this investment.");

                    break;
                }
                await UserRepository.EditCashAsync(Context, -Config.KILO_COST);

                await UserRepository.ModifyAsync(x => { x.InvestmentMultiplier = Config.KILO_MULTIPLIER; return(Task.CompletedTask); }, Context);
                await ReplyAsync($"{Context.User.Mention}, only the black jews would actually enjoy 4$/msg.");

                break;

            default:
                var builder = new EmbedBuilder()
                {
                    Title       = "Current Available Investments:",
                    Color       = new Color(0x0000FF),
                    Description = ($"\n**Cost: {Config.LINE_COST}$** | Command: `{guild.Prefix}investments line` | Description: " +
                                   $"One line of blow. Seems like nothing, yet it's enough to lower the message cooldown from 30 to 25 seconds." +
                                   $"\n**Cost: {Config.POUND_COST}$** | Command: `{guild.Prefix}investments pound` | Description: " +
                                   $"This one pound of coke will double the amount of cash you get per message\n**Cost: {Config.KILO_COST}$** | Command: " +
                                   $"`{guild.Prefix}investments kilo` | Description: A kilo of cocaine is more than enough to " +
                                   $"quadruple your cash/message.\n These investments stack with the chatting multiplier. However, they do not stack with themselves."),
                };
                await ReplyAsync("", embed : builder);

                break;
            }
        }
Example #15
0
        public static async Task Handle(IGuild guild, ulong userId)
        {
            using (var db = new DbContext())
            {
                var   guildRepo = new GuildRepository(db);
                var   userRepo  = new UserRepository(db);
                float cash      = await userRepo.GetCashAsync(userId);

                var user = await guild.GetUserAsync(userId);                            //FETCHES THE USER

                var currentUser = await guild.GetCurrentUserAsync() as SocketGuildUser; //FETCHES THE BOT'S USER

                var guildData = await guildRepo.FetchGuildAsync(guild.Id);              //FETCHES THE GUILD DATA

                var          role1         = guild.GetRole(guildData.Rank1Id);          //FETCHES ALL RANK ROLES
                var          role2         = guild.GetRole(guildData.Rank2Id);
                var          role3         = guild.GetRole(guildData.Rank3Id);
                var          role4         = guild.GetRole(guildData.Rank4Id);
                var          sponsorRole   = guild.GetRole(Config.SPONSORED_ROLE_ID);
                List <IRole> rolesToAdd    = new List <IRole>();
                List <IRole> rolesToRemove = new List <IRole>();
                if (guild != null && user != null)
                {
                    //CHECKS IF THE ROLE EXISTS AND IF IT IS LOWER THAN THE BOT'S HIGHEST ROLE
                    if (role1 != null && role1.Position < currentUser.Roles.OrderByDescending(x => x.Position).First().Position)
                    {
                        //ADDS ROLE IF THEY HAVE THE REQUIRED CASH
                        if (cash >= Config.RANK1 && !user.RoleIds.Any(x => x == role1.Id))
                        {
                            rolesToAdd.Add(role1);
                        }
                        //REMOVES ROLE IF THEY DO NOT HAVE REQUIRED CASH
                        if (cash < Config.RANK1 && user.RoleIds.Any(x => x == role1.Id))
                        {
                            rolesToRemove.Add(role1);
                        }
                    }
                    if (role2 != null && role2.Position < currentUser.Roles.OrderByDescending(x => x.Position).First().Position)
                    {
                        if (cash >= Config.RANK2 && !user.RoleIds.Any(x => x == role2.Id))
                        {
                            rolesToAdd.Add(role2);
                        }
                        if (cash < Config.RANK2 && user.RoleIds.Any(x => x == role2.Id))
                        {
                            rolesToRemove.Add(role2);
                        }
                    }
                    if (role3 != null && role3.Position < currentUser.Roles.OrderByDescending(x => x.Position).First().Position)
                    {
                        if (cash >= Config.RANK3 && !user.RoleIds.Any(x => x == role3.Id))
                        {
                            rolesToAdd.Add(role3);
                        }
                        if (cash < Config.RANK3 && user.RoleIds.Any(x => x == role3.Id))
                        {
                            rolesToRemove.Add(role3);
                        }
                    }
                    if (role4 != null && role4.Position < currentUser.Roles.OrderByDescending(x => x.Position).First().Position)
                    {
                        if (cash >= Config.RANK4 && !user.RoleIds.Any(x => x == role4.Id))
                        {
                            rolesToAdd.Add(role4);
                        }
                        if (cash < Config.RANK4 && user.RoleIds.Any(x => x == role4.Id))
                        {
                            rolesToRemove.Add(role4);
                        }
                    }
                    if (sponsorRole != null && sponsorRole.Position < currentUser.Roles.OrderByDescending(x => x.Position).First().Position)
                    {
                        if (Config.SPONSOR_IDS.Any(x => x == user.Id) && !user.RoleIds.Any(x => x == sponsorRole.Id))
                        {
                            rolesToAdd.Add(sponsorRole);
                        }
                        if (!Config.SPONSOR_IDS.Any(x => x == user.Id) && user.RoleIds.Any(x => x == sponsorRole.Id))
                        {
                            rolesToRemove.Add(sponsorRole);
                        }
                    }
                    if (rolesToAdd.Count >= 1)
                    {
                        await user.AddRolesAsync(rolesToAdd);
                    }
                    if (rolesToRemove.Count >= 1)
                    {
                        await user.RemoveRolesAsync(rolesToRemove);
                    }
                }
            }
        }
Example #16
0
        public async Task Gang([Remainder] string gangName = null)
        {
            using (var db = new SQLite.Models.DbContext())
            {
                var gangRepo  = new GangRepository(db);
                var guildRepo = new GuildRepository(db);
                if (gangName == null && !(await gangRepo.InGangAsync(Context.User.Id, Context.Guild.Id)))
                {
                    throw new Exception($"You are not in a gang.");
                }
                Gang gang;
                if (gangName == null)
                {
                    gang = await gangRepo.FetchGangAsync(Context.User.Id, Context.Guild.Id);
                }
                else
                {
                    gang = await gangRepo.FetchGangAsync(gangName, Context.Guild.Id);
                }
                var members = "";
                var leader  = "";
                if (Context.Client.GetUser(gang.LeaderId) != null)
                {
                    leader = Context.Client.GetUser(gang.LeaderId).Username;
                }
                SocketGuildUser member2 = Context.Guild.GetUser(gang.Member2Id), member3 = Context.Guild.GetUser(gang.Member3Id),
                                member4 = Context.Guild.GetUser(gang.Member4Id), member5 = Context.Guild.GetUser(gang.Member5Id);
                if (member2 != null)
                {
                    members += $"{member2.Username}, ";
                }
                if (member3 != null)
                {
                    members += $"{member3.Username}, ";
                }
                if (member4 != null)
                {
                    members += $"{member4.Username}, ";
                }
                if (member5 != null)
                {
                    members += $"{member5.Username}, ";
                }
                var InterestRate = 0.025f + ((gang.Wealth / 100) * .000075f);
                if (InterestRate > 0.1)
                {
                    InterestRate = 0.1f;
                }
                var builder = new EmbedBuilder()
                {
                    Title       = gang.Name,
                    Color       = new Color(0x00AE86),
                    Description = $"__**Leader:**__ {leader}\n" +
                                  $"__**Members:**__ {members.Substring(0, members.Length - 2)}\n" +
                                  $"__**Wealth:**__ {gang.Wealth.ToString("C2")}\n" +
                                  $"__**Interest rate:**__ {InterestRate.ToString("P")}"
                };
                if ((await guildRepo.FetchGuildAsync(Context.Guild.Id)).DM)
                {
                    var channel = await Context.User.CreateDMChannelAsync();

                    await channel.SendMessageAsync("", embed : builder);
                }
                else
                {
                    await ReplyAsync("", embed : builder);
                }
            }
        }