Esempio n. 1
0
        private async Task HandleGuildAvailable(SocketGuild guild)
        {
            //TODO: Maybe fetch shit from the Database here
            Console.WriteLine("Downloading users for guid {0}", guild.Name);
            guild.DownloadUsersAsync().Wait(500);
            //Make sure that the guild exists in the Database
            Console.WriteLine("Downloading done");

            using (var db = new LiteDatabase(Common.dbConnectionString))
            {
                var collection = db.GetCollection <Guild>("guilds");

                Guild gg = collection.FindOne(x => x.DiscordID == guild.Id);

                if (gg == null)
                {
                    //Registering Guild
                    var g = new Guild
                    {
                        Name               = guild.Name,
                        DiscordID          = guild.Id,
                        ActiveTournamentID = 0,
                        SettingsJson       = System.IO.File.ReadAllText("settings.json") //default settings
                    };

                    collection.Insert(g);
                    collection.EnsureIndex(x => x.DiscordID);
                    collection.EnsureIndex(x => x.Id);
                }
            }
        }
Esempio n. 2
0
        private async void GetUsers()
        {
            textBox1.AppendText("Getting users." + System.Environment.NewLine);

            SocketGuild guild = client.GetGuild(Convert.ToUInt64(guildId));
            await guild.DownloadUsersAsync();

            var users = guild.Users;

            List <MednaNetAPIClient.Models.Users> userList = new List <MednaNetAPIClient.Models.Users>();

            foreach (var user in users)
            {
                bool temp = false;

                if (user.Status != UserStatus.Offline)
                {
                    temp = true;
                }

                userList.Add(new MednaNetAPIClient.Models.Users()
                {
                    discordId = user.Id.ToString(),
                    username  = user.Username,
                    isOnline  = temp
                });
            }
            await apiClient.Users.AddDiscordUsers(userList);
        }
Esempio n. 3
0
        static async void LoadDatabase()
        {
            while (guild == null)
            {
                guild = Program.GetGuild();
            }

            await guild.DownloadUsersAsync();

            supporterRole    = guild.GetRole(547202953505800233);
            supporterChannel = guild.GetTextChannel(547204432144891907);
            generalChannel   = guild.GetChannel(334933825383563266) as SocketTextChannel;

            try
            {
                database = FileDatabase.Read <AccountDatabase>("Accounts/accounts");

                Console.WriteLine("Loaded database!");

                foreach (AccountInfo account in database.accounts.Values)
                {
                    await UpdateAsync(account, null);
                }

                Console.WriteLine(database.accounts.Count);
                Console.WriteLine(database.expiryAccounts.Count);
            }
            catch (Exception e)
            {
                Console.WriteLine("Account database not found! " + e.Message);

                database = new AccountDatabase();
            }
        }
        /// <summary>
        /// Handles joining a guild and announcing such.
        /// </summary>
        private async Task HandleJoinedGuildAsync(SocketGuild guild)
        {
            if (this.isReady)
            {
                this.TrackEvent("serverJoin");

                // if it's a bot farm, bail out.
                await guild.DownloadUsersAsync();

                var botCount = guild.Users.Count(u => u.IsBot);
                var botRatio = (double)botCount / guild.Users.Count;
                if (botCount > 30 && botRatio > .5)
                {
                    Log.Warning($"Auto bailed on a bot farm: {guild.Name} (#{guild.Id})");
                    await guild.LeaveAsync();

                    return;
                }

                var defaultChannel = guild.DefaultChannel;
                var owner          = guild.Owner;
                if (defaultChannel != null && guild.CurrentUser.GetPermissions(defaultChannel).SendMessages)
                {
                    await defaultChannel.SendMessageAsync($"(HELLO, I AM UB3R-B0T! .halp for info. {owner.Mention} you're the kickass owner-- you can use .admin to configure some stuff. By using me you agree to these terms: https://discordapp.com/developers/docs/legal)");
                }

                if (this.Config.PruneEndpoint != null)
                {
                    var req = WebRequest.Create($"{this.Config.PruneEndpoint}?id={guild.Id}&restore=1");
                    await req.GetResponseAsync();
                }
            }
        }
Esempio n. 5
0
        public async Task HonkAsync()
        {
            SocketUser sender = Context.Message?.Author;

            List <ulong> userIds = new List <ulong>();
            IReadOnlyCollection <SocketGuild> guilds = Context.Client.Guilds;

            // GooseBot is only a user in GooseTown so Goosetown should be the only Guild (server) returned.
            SocketGuild gooseTown = Context.Client.Guilds.FirstOrDefault();
            await gooseTown.DownloadUsersAsync();

            foreach (SocketGuildUser user in gooseTown.Users)
            {
                if (userIds.Contains(user.Id) ||
                    user.Id == GooseBotUserId ||
                    user.Id == sender?.Id)
                {
                    continue;
                }

                userIds.Add(user.Id);
            }

            Random randy         = new Random();
            int    indexToHonkAt = randy.Next(0, (userIds.Count - 1));

            await ReplyAsync($"<@{userIds[indexToHonkAt]}> https://tenor.com/bgig0.gif");
        }
Esempio n. 6
0
        async Task Ready(SocketGuild discordGuild)
        {
            Console.WriteLine(discordGuild.Name + " is ready");

            TownGuild guild = database.GetGuild(discordGuild);

            if (guild == null || guild.ActivityRoles.Count == 0)
            {
                return;
            }

            _ = Task.Run(async() =>
            {
                try
                {
                    await discordGuild.DownloadUsersAsync();

                    foreach (SocketGuildUser user in discordGuild.Users)
                    {
                        Console.WriteLine("Update " + user.Username);
                        await UpdateRoles(null, user, guild);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    Console.WriteLine(e.StackTrace);
                }

                Console.WriteLine("DONE!");
            });
        }
        /// <summary>
        /// Handles joining a guild and announcing such.
        /// </summary>
        private async Task HandleJoinedGuildAsync(SocketGuild guild)
        {
            if (this.isReady)
            {
                this.AppInsights?.TrackEvent("serverJoin");

                // if it's a bot farm, bail out.
                await guild.DownloadUsersAsync();

                var botCount = guild.Users.Count(u => u.IsBot);
                var botRatio = (double)botCount / guild.Users.Count;
                if (botCount > 30 && botRatio > .5)
                {
                    this.Logger.Log(LogType.Warn, $"Auto bailed on a bot farm: {guild.Name} (#{guild.Id})");
                    await guild.LeaveAsync();

                    return;
                }

                var defaultChannel = guild.DefaultChannel;
                var owner          = guild.Owner;
                if (guild.CurrentUser.GetPermissions(defaultChannel).SendMessages)
                {
                    await defaultChannel.SendMessageAsync($"(HELLO, I AM UB3R-B0T! .halp for info. {owner.Mention} you're the kickass owner-- you can use .admin to configure some stuff.)");
                }
            }
        }
Esempio n. 8
0
        private static async Task DownloadUsers(SocketGuild guild)
        {
            await guild.DownloadUsersAsync();

#if DEBUG
            Console.WriteLine($"Downloaded users from {guild.Name}");
#endif
        }
Esempio n. 9
0
 public static void Refresh(SocketGuild guild)
 {
     Task.Run(async() => {
         Console.WriteLine("downloading user list");
         await guild.DownloadUsersAsync();
         Console.WriteLine("user list downloaded");
     });
 }
Esempio n. 10
0
        private async Task Client_GuildAvailable(SocketGuild guild)
        {
            if (guild.Id == config.HomeGuildId && !initialized)
            {
                // this is used to ensure we don't add multiples of the handler when the bot has to reconnect briefly.
                // I suppose this means that without a full restart, some users might be missed by the bot.
                // This needs to be moved elsewhere.
                initialized = true;

                Task.Run(async() =>
                {
                    await guild.DownloadUsersAsync();

                    var role = guild.GetRole(config.AccessRoleId);

                    List <SocketGuildUser> newUsers = new List <SocketGuildUser>();

                    foreach (var user in guild.Users)
                    {
                        if (!user.Roles.Contains(role))
                        {
                            await user.AddRoleAsync(role);
                        }
                    }

                    //foreach (var kv in VCTCPair)
                    //{
                    //var vc = guild.GetVoiceChannel(kv.Key);
                    //var tc = guild.GetTextChannel(kv.Value);

                    //foreach (var overwrite in tc.PermissionOverwrites.Where(x => x.TargetType == PermissionTarget.User))
                    //{
                    //if (!vc.Users.Select(x => x.Id).Contains(overwrite.TargetId))
                    //await tc.RemovePermissionOverwriteAsync(guild.GetUser(overwrite.TargetId));
                    //}

                    //foreach (var user in vc.Users)
                    //{
                    //if (tc.GetPermissionOverwrite(user) == null)
                    //await tc.AddPermissionOverwriteAsync(user, new OverwritePermissions(viewChannel: PermValue.Allow));
                    //}
                    //}

                    Console.WriteLine("Adding handlers");

                    client.UserJoined            += Client_UserJoined;
                    client.UserLeft              += Client_UserLeft;
                    client.UserVoiceStateUpdated += Client_UserVoiceStateUpdated;
                });
            }
            else if (guild.Id != config.HomeGuildId && guild.Id != 473760817809063936 && guild.Id != 212053857306542080)
            {
                await guild.LeaveAsync(); // seriously this bot is only set up to work with a single server

                // and my testing server because reasons
            }
        }
Esempio n. 11
0
        //public PermissionsService(
        //    IConfigStore<IPermissionConfig> configstore,
        //    CommandService commands,
        //    DiscordShardedClient client,
        //    Func<LogMessage, Task> logAction = null) : this(configstore, commands, logAction)
        //{
        //    ShardedClient = client ?? throw new ArgumentNullException(nameof(client));

        //    client.GetShard(0).Ready += CheckDuplicateModuleNames;
        //    client.GuildAvailable += GuildAvailable;
        //    client.UserJoined += UserJoined;
        //    client.ChannelCreated += ChannelCreated;
        //    client.ChannelDestroyed += ChannelDestroyed;
        //    client.ReactionAdded += ReactionAdded;
        //    client.MessageDeleted += MessageDeleted;
        //}

        #region PermissionEvents
        private Task GuildAvailable(SocketGuild guild)
        {
            Task.Run(async() =>
            {
                using var config = ConfigStore.Load();
                await guild.DownloadUsersAsync().ConfigureAwait(false);
                await config.AddNewGuild(guild, guild.Users).ConfigureAwait(false);
                config.Save();
            });
            return(Task.CompletedTask);
        }
        async Task ApplyRoles(SocketGuild guild)
        {
            await guild.DownloadUsersAsync();

            foreach (ActivityDefinition activity in activities)
            {
                activity.InitializeForGuild(guild);

                //Not awaiting so they all go at once
                activity.ApplyRole(guild);
            }
        }
Esempio n. 13
0
        public static async Task <SocketGuildUser> GetGuildUserAsync(this SocketGuild guild, ulong id)
        {
            SocketGuildUser user = guild.GetUser(id);

            if (user == null)
            {
                await guild.DownloadUsersAsync();

                user = guild.GetUser(id);
            }
            return(user);
        }
Esempio n. 14
0
        public static async Task SyncGuildAsync(this SocketGuild guild)
        {
            if (guild.SyncPromise != null)
            {
                await guild.SyncPromise;
            }

            await guild.DownloadUsersAsync();

            if (guild.DownloaderPromise != null)
            {
                await guild.DownloaderPromise;
            }
        }
Esempio n. 15
0
        public static async Task SyncGuildAsync(this SocketGuild guild)
        {
            if (guild.SyncPromise != null)
            {
                await guild.SyncPromise.ConfigureAwait(false);
            }

            await guild.DownloadUsersAsync().ConfigureAwait(false);

            if (guild.DownloaderPromise != null)
            {
                await guild.DownloaderPromise.ConfigureAwait(false);
            }
        }
Esempio n. 16
0
        public static async Task <SocketGuildUser> GetUserFromGuildAsync(this SocketGuild guild, string userId)
        {
            var idOfUser = Convert.ToUInt64(userId);
            var user     = guild.GetUser(idOfUser);

            if (user == null)
            {
                await guild.DownloadUsersAsync().ConfigureAwait(false);

                user = guild.GetUser(idOfUser);
            }

            return(user);
        }
Esempio n. 17
0
        private async void InitializePermissions()
        {
            await _guild.DownloadUsersAsync();

            foreach (SocketGuildUser user in _guild.Users)
            {
                if (user.Id != _client.CurrentUser.Id)
                {
                    foreach (SocketRole role in user.Roles)
                    {
                        Permissions.AddPlayerRole(user.Id, role.Id);
                    }
                }
            }
        }
Esempio n. 18
0
    public static async Task <int> TotalBotsAsync(SocketGuild g)
    {
        int total = 0;
        await g.DownloadUsersAsync();

        foreach (SocketGuildUser u in  g.Users)
        {
            if (u.IsBot)
            {
                total++;
            }
        }

        return(total);
    }
Esempio n. 19
0
        public static async Task <SocketGuildUser> GetUserFromGuildAsync(this SocketGuild guild, string username, string discriminator)
        {
            bool userFinder(SocketGuildUser user) => user.IsUser() && user.Username == username && user.Discriminator == discriminator;

            var user = guild.Users.FirstOrDefault(userFinder);

            if (user == null)
            {
                await guild.DownloadUsersAsync();

                user = guild.Users.FirstOrDefault(userFinder);
            }

            return(user);
        }
Esempio n. 20
0
        private async Task CheckUsers(CancellationToken token)
        {
            await Guild.DownloadUsersAsync().ConfigureAwait(false);

            if (!Guild.HasAllMembers)
            {
                await Log($"Local Guild Cache is missing users", LogSeverity.Warning);
            }

            foreach (var user in Guild.Users)
            {
                var hasLiveRole = user.Roles.Any(r => r.Id == LiveRoleID);

                if (user.Activity != null && user.Activity.Type == ActivityType.CustomStatus && user.Activity is Game game)
                {
                    if (game.ToString().Replace(" ", string.Empty) == GameToTrack && !hasLiveRole)
                    {
                        await user.AddRoleAsync(Guild.GetRole(LiveRoleID), new RequestOptions()
                        {
                            CancelToken = token
                        });

                        Log($"Added live role to {user}");
                    }

                    else if (game.ToString().Replace(" ", string.Empty) != GameToTrack && hasLiveRole)
                    {
                        await user.RemoveRoleAsync(Guild.GetRole(LiveRoleID), new RequestOptions()
                        {
                            CancelToken = token
                        });

                        Log($"Removed live role from {user}");
                    }
                }

                else if (hasLiveRole)
                {
                    await user.RemoveRoleAsync(Guild.GetRole(LiveRoleID), new RequestOptions()
                    {
                        CancelToken = token
                    });

                    Log($"Removed live role from {user}");
                }
            }
        }
Esempio n. 21
0
 //test method
 public Task Connected(SocketGuild e)
 {
     if (e.Id.ToString() == unoServerID)
     {
         e.DownloadUsersAsync();
         Task.Delay(6000);
         IReadOnlyCollection <SocketGuildUser> members = e.Users;
         int count = 0;
         foreach (SocketGuildUser x in members)
         {
             Console.WriteLine(x.Username);
             count++;
         }
         Console.WriteLine(count);
     }
     return(Task.CompletedTask);
 }
Esempio n. 22
0
File: Guild.cs Progetto: Z3RYX/Azure
        public bool BanForWarns;   // Defaults to false; False kicks the user, True bans the user

        public Guild(SocketGuild guild)
        {
            ID          = guild.Id;
            Prefix      = "//";
            ModlogCount = 0;

            if (guild.TextChannels.Where(x => x.Name == "modlog").Select(x => x.Id).Count() == 0)
            {
                ModlogChannel = null;
                AllowModlog   = false;
            }
            else
            {
                ModlogChannel = guild.TextChannels.Where(x => x.Name == "modlog").Select(x => x.Id).First();
                AllowModlog   = true;
            }

            if (guild.TextChannels.Where(x => x.Name == "tickets" || x.Name == "support-tickets").Select(x => x.Id).Count() == 0)
            {
                TicketChannel = null;
                AllowTickets  = false;
            }
            else
            {
                TicketChannel = guild.TextChannels.Where(x => x.Name == "tickets" || x.Name == "support-tickets").Select(x => x.Id).First();
                AllowTickets  = true;
            }

            if (guild.Roles.Where(x => x.Name.ToLower() == "muted").Select(x => x.Id).Count() == 0)
            {
                MuteRole = null;
            }
            else
            {
                MuteRole = guild.TextChannels.Where(x => x.Name.ToLower() == "muted").Select(x => x.Id).First();
            }

            Tickets = new List <int>();

            guild.DownloadUsersAsync();
            GuildUsers = guild.Users.Select(x => new GuildUser(x)).ToList();

            WarnsForAction = 0;
            BanForWarns    = false;
        }
Esempio n. 23
0
        async Task Ready()
        {
            foreach (TownGuild guild in database.Guilds.FindAll())
            {
                if (guild.ActivityRoles.Count == 0)
                {
                    continue;
                }

                SocketGuild discordGuild = client.GetGuild(guild.GuildId);

                await discordGuild.DownloadUsersAsync();

                foreach (SocketGuildUser user in discordGuild.Users)
                {
                    await UpdateRoles(null, user, guild);
                }
            }
        }
        private async Task <bool> CheckBotGuild(SocketGuild guild)
        {
            // If the server is the Discord bots server, ignore.
            if (guild.Id == Constants.BotsGuildId)
            {
                return(false);
            }

            // Ensure guild is updated.
            if (guild.Users.Count != guild.MemberCount)
            {
                await guild.DownloadUsersAsync();
            }

            // Is this a bot guild?
            if (guild.MemberCount >= 50 && (guild.Users.Count(u => u.IsBot) / (double)guild.MemberCount) >= 0.9)
            {
                try
                {
                    // Bot is typing in default channel.
                    await guild.DefaultChannel.TriggerTypingAsync();

                    // Pause for realism.
                    await Task.Delay(TimeSpan.FromSeconds(1));

                    // Send notice.
                    await guild.DefaultChannel.SendMessageAsync($"It looks like this server is a bot farm, so I'll show myself out. If this is a legitimate server, contact *{Constants.OwnerName}*.");
                }
                catch { }

                // Wait 2 seconds, then leave.
                await Task.Delay(TimeSpan.FromSeconds(2));

                await guild.LeaveAsync();

                // This was a bot server.
                return(true);
            }

            // This is not a bot server.
            return(false);
        }
Esempio n. 25
0
        public async Task GetPhotoUsersAsync()
        {
            await SocketGuild.DownloadUsersAsync();

            var users = SocketGuild.Users;

            Config.PhotoUserIds = new List <ulong>();

            foreach (var user in users)
            {
                if (!user.IsPhotoUser())
                {
                    continue;
                }

                Config.PhotoUserIds.Add(user.Id);
            }

            await PhotoConfig.SaveAsync();
        }
Esempio n. 26
0
        async Task Ready(SocketGuild discordGuild)
        {
            if (discordGuild.Id == 334933825383563266)             //ATT Guild
            {
                const ulong botlogchannel = 533105660993208332;

                SocketTextChannel logChannel = discordGuild.GetTextChannel(botlogchannel);

                await logChannel.SendMessageAsync("Town Crier has Restarted");
            }

            Console.WriteLine(discordGuild.Name + " is ready");

            TownGuild guild = database.GetGuild(discordGuild);

            if (guild == null || guild.ActivityRoles.Count == 0)
            {
                return;
            }

            _ = Task.Run(async() =>
            {
                try
                {
                    await discordGuild.DownloadUsersAsync();

                    foreach (SocketGuildUser user in discordGuild.Users)
                    {
                        Console.WriteLine("Update " + user.Username);
                        await UpdateRoles(null, user, guild);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    Console.WriteLine(e.StackTrace);
                }

                Console.WriteLine("DONE!");
            });
        }
Esempio n. 27
0
        public static async Task <string> GetInfoString(this SocketGuild guild)
        {
            await guild.DownloadUsersAsync();

            return($@"
Server Owner: <@{guild.OwnerId}> (ID: `{guild.OwnerId}`)
Server ID: `{guild.Id}`
Member Count: {guild.MemberCount}
Role Count: {guild.Roles.Count}
Channel Count: {guild.Channels.Count}
Date Created: {guild.CreatedAt.DateTime:D}
Icon: [Click here]({guild.IconUrl})
Banner: {guild.BannerUrl ?? "None"}
Vanity Url Code: {guild.VanityURLCode ?? "None"}
Boosts: {guild.PremiumTier}
Number Of Admins: {guild.Users.Count(Usr => Usr.GuildPermissions.Administrator && !Usr.IsBot)}
Number Of Mods: {guild.Users.Count(Usr => (Usr.GuildPermissions.ManageChannels || Usr.GuildPermissions.ManageGuild || Usr.GuildPermissions.ManageRoles) && !Usr.GuildPermissions.Administrator)}
Number Of Bots: {guild.Users.Count(Usr => Usr.IsBot)}
Raw Perms: `{(guild.CurrentUser == null ? "None" : guild.CurrentUser.GuildPermissions.RawValue)}`
");
        }
Esempio n. 28
0
        /// <summary>
        /// Handles joining a guild and announcing such.
        /// </summary>
        private async Task HandleJoinedGuildAsync(SocketGuild guild)
        {
            if (this.isReady)
            {
                this.TrackEvent("serverJoin");

                // if it's a bot farm, bail out.
                await guild.DownloadUsersAsync();

                var botCount = guild.Users.Count(u => u.IsBot);
                var botRatio = (double)botCount / guild.Users.Count;
                if (botCount > 30 && botRatio > .5)
                {
                    Log.Warning($"Auto bailed on a bot farm: {guild.Name} (#{guild.Id})");
                    await guild.LeaveAsync();

                    return;
                }

                var defaultChannel = guild.DefaultChannel;
                var owner          = guild.Owner;
                if (defaultChannel != null && guild.CurrentUser.GetPermissions(defaultChannel).SendMessages)
                {
                    await defaultChannel.SendMessageAsync($"(HELLO, I AM UB3R-B0T! .halp for info. {owner.Mention} you're the kickass owner-- you can use .admin to configure some stuff. By using me you agree to these terms: https://ub3r-b0t.com/terms)");
                }

                if (this.BotApi != null)
                {
                    try
                    {
                        await this.BotApi.IssueRequestAsync(new BotMessageData(BotType.Discord) { Content = ".prune restore", Prefix = ".", Server = guild.Id.ToString() });
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, $"Error calling prune restore command");
                    }
                }
            }
        }
Esempio n. 29
0
        private async Task _client_Connected()
        {
            Activate();
            Console.WriteLine("Connected");

            IReadOnlyCollection <SocketGuild> guilds = MainClass._client.Guilds;

            Console.WriteLine("Number of guilds " + guilds.Count);
            foreach (SocketGuild guild in guilds)
            {
                SocketGuild sok = MainClass._client.GetGuild(guild.Id);

                sok.DownloadUsersAsync().Wait(500);


                Console.WriteLine(sok.Name);
                ServerUserControl usercontrol = new ServerUserControl();
                if (!string.IsNullOrWhiteSpace(sok.IconUrl))
                {
                    using (WebClient wc = new WebClient())
                    {
                        byte[] imagebyte = wc.DownloadData(sok.IconUrl);
                        using (MemoryStream ms = new MemoryStream(imagebyte))
                        {
                            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                            usercontrol.SetImage(img);
                        }
                    }
                }

                usercontrol.SetComboBox("@everyone");
                usercontrol.SetRoles(sok.Roles);
                usercontrol.SetText(sok.Name);
                usercontrol.SetGuild(sok);

                AddToFlowLayout(usercontrol);
            }
        }
Esempio n. 30
0
        private async Task Client_GuildAvailable(SocketGuild guild)
        {
            if (guild.Id == config.HomeGuildId && !initialized)
            {
                initialized = true;

                Console.WriteLine("Starting db");

                Task.Run(async() =>
                {
                    await guild.DownloadUsersAsync();

                    var loggedUsers = await dbhelper.GetAllusers();
                    var role        = guild.GetRole(config.AccessRoleId);

                    List <LoggedUser> newUsers        = new List <LoggedUser>();
                    List <LoggedUser> unapprovedUsers = new List <LoggedUser>();

                    Console.WriteLine($"Grabbed lists of users [{loggedUsers.Count()} vs {guild.Users.Count()}]");

                    if (existingTable)
                    {
                        Console.WriteLine("Table exists");

                        foreach (var u in guild.Users)
                        {
                            if (!loggedUsers.ContainsKey(u.Id))
                            {
                                // We haven't seen this user yet, get to them later
                                // Probably due to someone joining while the bot was offline

                                // If the account is past the minimum age, just let them in. Don't bother checking the 10 minute timer.

                                newUsers.Add(new LoggedUser()
                                {
                                    UserId         = u.Id,
                                    NewAccount     = u.CreatedAt.Date > DateTimeOffset.Now.AddDays(config.MinimumAccountAge * -1),
                                    ApprovedAccess = !(u.CreatedAt.Date > DateTimeOffset.Now.AddDays(config.MinimumAccountAge * -1))
                                });

                                continue;
                            }
                            else
                            {
                                // We have this user in the list, ensure they have the roles they should
                                if (u.Roles.Contains(role))
                                {
                                    // They have access to the server
                                    if (loggedUsers[u.Id].ApprovedAccess)
                                    {
                                        continue; // and this matches our records
                                    }
                                    else
                                    {
                                        // and this does not match our records
                                        // revoke access, notify admins that someone has a role that they shouldn't

                                        await u.RemoveRoleAsync(role, new RequestOptions()
                                        {
                                            AuditLogReason = "Unapproved access."
                                        });

                                        string output = "";

                                        if (config.AlternateStaffMention)
                                        {
                                            output = $"<@&{config.AlternateStaffId}> {u.Mention} had access to the server when they shouldn't. Check audit log and see who gave them the role.";
                                        }
                                        else
                                        {
                                            output = $"<@&{config.StaffId}> {u.Mention} had access to the server when they shouldn't. Check audit log and see who gave them the role.";
                                        }

                                        await(client.GetGuild(config.HomeGuildId).GetChannel(config.MainChannelId) as ISocketMessageChannel)
                                        .SendMessageAsync(output);
                                    }
                                }
                                else
                                {
                                    // They don't have the role
                                    if (loggedUsers[u.Id].ApprovedAccess)
                                    {
                                        // they don't have the role when they should
                                        // send a post to admins so this can be dealt with manualy

                                        string output = "";

                                        if (config.AlternateStaffMention)
                                        {
                                            output = $"<@&{config.AlternateStaffId}> {u.Mention} needs access.";
                                        }
                                        else
                                        {
                                            output = $"<@&{config.StaffId}> {u.Mention} needs access.";
                                        }

                                        if (loggedUsers[u.Id].ApprovalModId != 0)
                                        {
                                            output = $"{output}\nThey've previously been approved by <@{loggedUsers[u.Id].ApprovalModId}> with the reason `{loggedUsers[u.Id].ApprovalReason}`";
                                        }

                                        await(client.GetGuild(config.HomeGuildId).GetChannel(config.MainChannelId) as ISocketMessageChannel)
                                        .SendMessageAsync(output);
                                    }
                                    else
                                    {
                                        continue; // and this matches our records
                                    }
                                }
                            }
                        }

                        Console.WriteLine("Alright, checked through the user lists");

                        //if (newUsers.Count() > 1)
                        //{
                        //    Console.WriteLine($"aaaaaaaaaAAAAAAAAAAAAAAAAAAAAA {newUsers.Count()}");
                        //    throw new Exception("EVERYTHING IS BROKEN");
                        //}

                        // Add all the new users to the database
                        await dbhelper.BulkAddLoggedUser(newUsers);

                        foreach (var u in newUsers)
                        {
                            if (u.NewAccount)
                            {
                                try
                                {
                                    await guild.GetUser(u.UserId).SendMessageAsync(NewUserNotice);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine($"Error sending new user message to {u.UserId}!\nMessage: {ex.Message}\nSource: {ex.Source}\n{ex.InnerException}");
                                }
                            }
                            else
                            {
                                try
                                {
                                    await guild.GetUser(u.UserId).SendMessageAsync(OfflineJoinWelcome);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine($"Error sending offline user message to {u.UserId}!\nMessage: {ex.Message}\nSource: {ex.Source}\n{ex.InnerException}");
                                }

                                CancellationTokenSource source = new CancellationTokenSource();
                                waitingUsers.Add(u.UserId, source);

                                Task.Run(async() => DelayAddRole(u.UserId, source.Token, minutes: 0), source.Token);

                                Console.WriteLine($"Apparently adding user {u.UserId}");
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Creating new table");

                        // Fresh table, add everyone to the table
                        List <LoggedUser> users = new List <LoggedUser>();

                        foreach (var u in guild.Users)
                        {
                            users.Add(new LoggedUser()
                            {
                                UserId         = u.Id,
                                NewAccount     = u.CreatedAt.Date > DateTimeOffset.Now.AddDays(config.MinimumAccountAge * -1),
                                ApprovedAccess = u.Roles.Contains(role)
                            });
                        }

                        await dbhelper.BulkAddLoggedUser(users);

                        Console.WriteLine("Table created");
                    }

                    Console.WriteLine("Adding handlers");

                    client.UserJoined         += Client_UserJoined;
                    client.UserLeft           += Client_UserLeft;
                    client.GuildMemberUpdated += Client_GuildMemberUpdated;
                });
            }
            else if (guild.Id != config.HomeGuildId)
            {
                await guild.LeaveAsync(); // seriously this bot is only set up to work with a single server
            }
        }