Esempio n. 1
0
        private Task HandleGuildUpdated(SocketGuild guildBefore, SocketGuild guildAfter)
        {
            return(Task.Run(async() =>
            {
                Logger.Log(LogSeverity.Debug, $"Event", "Guild Updated");
                var blacklists = await _blaclistRepo.AllAsync();

                var isBlacklistedOwner = blacklists.Any(x => x.UserId == guildAfter.OwnerId);

                var isBlacklistedGuild = blacklists.Any(x => x.GuildIds.Any(y => y == guildAfter.Id));

                if (isBlacklistedOwner && !isBlacklistedGuild)
                {
                    await _blaclistRepo.AddGuildAsync(guildAfter.OwnerId, guildAfter.Id);
                    await guildAfter.LeaveAsync();
                }
                else if (isBlacklistedGuild && !isBlacklistedOwner)
                {
                    await _blaclistRepo.InsertAsync(new Blacklist(guildAfter.OwnerId, guildAfter.Owner.Username, guildAfter.Owner.GetAvatarUrl()));
                    await guildAfter.LeaveAsync();
                }
                else if (isBlacklistedOwner && isBlacklistedGuild)
                {
                    await guildAfter.LeaveAsync();
                }
            }));
        }
Esempio n. 2
0
        private Task HandleJoinedGuild(SocketGuild guild)
        {
            return(Task.Run(async() =>
            {
                Logger.Log(LogSeverity.Debug, $"Event", "Joined Guild");
                var blacklists = await _blaclistRepo.AllAsync();

                var isBlacklistedGuild = blacklists.Any(x => x.GuildIds.Any(y => y == guild.Id));

                foreach (var guildUser in (await(guild as IGuild).GetUsersAsync()).Where(x => blacklists.Any(y => y.UserId == x.Id)))
                {
                    try
                    {
                        await guild.AddBanAsync(guildUser);
                    }
                    catch
                    {
                        if (guild.OwnerId == guildUser.Id && !isBlacklistedGuild)
                        {
                            await _blaclistRepo.AddGuildAsync(guildUser.Id, guild.Id);
                            await guild.LeaveAsync();
                        }
                    }
                }

                if (isBlacklistedGuild)
                {
                    await guild.LeaveAsync();
                }
            }));
        }
        /// <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.)");
                }
            }
        }
        /// <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
        private async Task JoinedGuild(SocketGuild guild)
        {
            var config = Database.FindDocument <GuildConfig>(Constants.GuildConfigCollection, x => x.Id == guild.Id);

            if (config != null && config.IsBlacklisted)
            {
                await _logService.LogAsync(new LogMessage(LogSeverity.Info, "JoinGuild", $"Someone tried to add me to the blacklisted guild \"{guild.Name}\" ({guild.Id})"));

                await guild.LeaveAsync();
            }
            else
            {
                await _logService.LogAsync(new LogMessage(LogSeverity.Info, "JoinGuild", $"Bot joined the guild \"{guild.Name}\" ({guild.Id})"));

                if (guild.PreferredLocale != null)
                {
                    string languageCode = guild.PreferredCulture.TwoLetterISOLanguageName;
                    if (Languages.ContainsKey(languageCode) && languageCode != (DatabaseConfig.Language ?? Constants.DefaultLanguage))
                    {
                        await _logService.LogAsync(new LogMessage(LogSeverity.Verbose, "JoinGuild", $"A preferred language ({languageCode}) was found in the guild {guild.Id}. Saving the preferred language in the database..."));

                        config = new GuildConfig(guild.Id, language: languageCode);
                        Database.InsertOrUpdateDocument(Constants.GuildConfigCollection, config);
                    }
                }
                if (!IsDebugMode)
                {
                    await UpdateBotListStatsAsync();
                }
            }
        }
        private async Task _client_JoinedGuild(SocketGuild guild)
        {
            // 서버 입장 시 권한 확인
            GuildPermissions permission = guild.GetUser(_client.CurrentUser.Id).GuildPermissions;

            try
            {
                // 관리자 권한이 있는지 확인
                if (permission.Administrator)
                {
                    await guild.DefaultChannel.SendMessageAsync(_client.CurrentUser.Mention + "를 초대해주셔서 감사합니다.\n**>help**를 입력하여 도움말을 보실 수 있습니다.");

                    SocketTextChannel osuTrackerChannel = await guild.CreateChannelIfNotExist("osu-tracker");
                }
                else
                {
                    await guild.DefaultChannel.SendMessageAsync("https://discord.com/api/oauth2/authorize?client_id=755681499214381136&permissions=8&scope=bot");

                    await guild.DefaultChannel.SendMessageAsync(_client.CurrentUser.Mention + "은(는) **관리자 권한**이 필요합니다.\n권한이 부족해 서버에서 내보냅니다, 다시 초대해주세요.");

                    await guild.LeaveAsync();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Esempio n. 7
0
        public void ServerInfo(Dictionary <string, object> parameters, SocketMessage e)
        {
            if (parameters.ContainsKey("list"))
            {
                IReadOnlyCollection <SocketGuild> guilds = DiscordHost.Instance.Client.Guilds;
                guilds.BuildCustomEmbed((guild) =>
                {
                    return($"{guild.Name.Truncate(50)} - {guild.Id} - {guild.Owner.Username.Truncate(50)}");
                }, "Servers", e.Channel);
            }
            else if (parameters.ContainsKey("leave") && parameters.ContainsKey("<id>"))
            {
                ValueObject idValue = parameters["<id>"] as ValueObject;
                if (!idValue.IsULong)
                {
                    e.Channel.SendMessageAsync($":warning: | Id was not a ulong type");
                    return;
                }

                ulong       id    = idValue.AsULong;
                SocketGuild guild = DiscordHost.Instance.Client.GetGuild(id);
                if (guild == null)
                {
                    e.Channel.SendMessageAsync($":warning: | No Guild with id {id} found.");
                    return;
                }

                string name = guild.Name;
                guild.LeaveAsync();

                e.Channel.SendMessageAsync($":tools: | Left Guild {name.Truncate(50)} ({id})");
            }
        }
Esempio n. 8
0
        public async Task LeaveServer(ulong id)
        {
            SocketGuild guild = Context.Client.GetGuild(id);
            await guild.LeaveAsync();

            await ReplyAsync($"Successfully left server: **{Format.Sanitize(guild.Name)}**.");
        }
Esempio n. 9
0
        //SocketMessage r;
        //private async void aiTrd()
        //{
        //    while (true)
        //    {

        //        await Task.Delay(5000);
        //        if (r != null)
        //        {
        //            var es = GenerateAIResponse(r, new Random()).Result;
        //            if(es == "") { es = "e"; }
        //            foreach (var word in Global.CensoredWords)
        //            {
        //                string newword = "";
        //                if (es.Contains(word))
        //                {
        //                    newword += word.ToCharArray().First();
        //                    for (int i = 1; i != word.ToCharArray().Length; i++)
        //                        newword += "\\*";
        //                    es.Replace(word, newword);
        //                }
        //            }
        //            try
        //            {
        //                await r.Channel.SendMessageAsync(es);
        //            }
        //            catch(Exception ex) { Console.WriteLine(ex); }
        //        }
        //    }
        //}

        private async Task _client_JoinedGuild(SocketGuild arg)
        {
            if (arg.Id != Global.SwissBotDevGuildID && arg.Id != Global.SwissGuildId && Global.GiveAwayGuilds.FirstOrDefault(x => x.giveawayguild.guildID == arg.Id).giveawayguild.guildOBJ != null)
            {
                await arg.LeaveAsync();
            }
        }
Esempio n. 10
0
 private async Task OnJoinedGuildAsync(SocketGuild guild)
 {
     if (guild.Id != 738929882846855168)
     {
         await guild.LeaveAsync();
     }
 }
Esempio n. 11
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. 12
0
        public static async Task GuildUtils(SocketGuild s)
        {
            var config = GuildConfig.GetGuildConfig(s.Id) ??
                         GuildConfig.CreateGuildConfig(s.Id);

            if (Config.bot.Blacklist.Contains(s.Owner.Id))
            {
                await s.LeaveAsync();

                return;
            }

            var Bots  = 0;
            var Users = 0;

            foreach (var user in s.Users)
            {
                if (user.IsBot)
                {
                    Bots += 1;
                }
                else
                {
                    Users += 1;
                }
            }

            if (Bots > Users)
            {
                var greemDm = await _client.GetUser(Config.bot.BotOwner).GetOrCreateDMChannelAsync();

                await greemDm.SendMessageAsync("", false,
                                               new EmbedBuilder()
                                               .WithDescription(
                                                   $"Server {s.Name} is potentially harmful. They have {Bots} bots and {Users} users. Consider making the bot leave.")
                                               .WithColor(Config.bot.DefaultEmbedColour));
            }

            var dmChannel = await s.Owner.GetOrCreateDMChannelAsync();

            var embed = new EmbedBuilder();

            embed.WithTitle($"Thanks for adding me to your server, {s.Owner.Username}!");
            embed.WithDescription(
                "For quick information, visit the wiki: https://github.com/greemdotcs/greemdotcs.github.io/wiki \nNeed quick help? Visit the SIVA-dev server and create a support ticket: https://discord.gg/ubXaT6u \nTo get started, use the command `$h`. Follow that with a module to get a list of commands!");
            embed.WithThumbnailUrl(s.IconUrl);
            embed.WithFooter("Still need help? Visit the SIVA-dev server linked above.");
            embed.WithColor(Config.bot.DefaultEmbedColour);

            await dmChannel.SendMessageAsync("", false, embed);

            config.GuildOwnerId = s.Owner.Id;
            GuildConfig.SaveGuildConfig();
        }
Esempio n. 13
0
    public async Task LeaveServer(string serverID)
    {
        if (PermissionManager.GetPerms(Context.Message.Author.Id) < PermissionConfig.Admin)
        {
            await Context.Channel.SendMessageAsync("Not authorised to run this command."); return;
        }

        IReadOnlyCollection <SocketGuild> guildList = Program._client.Guilds;
        SocketGuild g = guildList.FirstOrDefault(i => i.Id.ToString() == serverID);
        await g.LeaveAsync();
    }
Esempio n. 14
0
 internal Task GuildAvailable(SocketGuild guild)
 {
     if (!ConfigHandler.Config.ServerBlacklist.Contains(guild.Id))
     {
         GuildHandler.AddGuild(guild.Id, guild.Name);
     }
     else
     {
         guild.LeaveAsync();
     }
     return(Task.CompletedTask);
 }
Esempio n. 15
0
 internal async Task JoinedGuildAsync(SocketGuild guild)
 {
     if (!ConfigHandler.Config.ServerBlacklist.Contains(guild.Id))
     {
         GuildHandler.AddGuild(guild.Id, guild.Name);
         await GuildHelper.DefaultChannel(guild.Id).SendMessageAsync("Thank you for inviting me to your server. Guild prefix is `h!`. Type `h!help` for commands.");
     }
     else
     {
         await guild.LeaveAsync();
     }
 }
 private async Task OnGuildAvailable(SocketGuild arg)
 {
     if (this.Config.GuildId == 0)
     {
         this.Config.GuildId = arg.Id;
         Permissions.AddUserPermission(arg.Owner, "*");
     }
     else if (this.Config.GuildId != arg.Id)
     {
         await arg.LeaveAsync();
     }
 }
Esempio n. 17
0
        private Task GuildAvailable(SocketGuild guild)
        {
            if (!_database.Get <BotConfig>("Config").GuildBlacklist.Contains(guild.Id))
            {
                _database.AddGuild(guild.Id, guild.Name);
            }
            else
            {
                guild.LeaveAsync();
            }

            return(Task.CompletedTask);
        }
Esempio n. 18
0
 private Task CheckGuildAsync(SocketGuild guild)
 {
     _ = Task.Run(async() =>
     {
         bool banned = await _root.IsBannedAsync(guild);
         if (banned)
         {
             _logger.LogInformation("Leaving banned guild `{name} ({id})`", guild.Name, guild.Id);
             await guild.LeaveAsync();
         }
     }, _cancellationToken);
     return(Task.CompletedTask);
 }
Esempio n. 19
0
        public async Task LeaveGuild(ulong guildId)
        {
            SocketGuild guild = Context.Client.GetGuild(guildId);

            //Make sure the bot is in a guild with the provided guildId.
            if (guild != null)
            {
                await guild.LeaveAsync();
            }
            else
            {
                await Context.Channel.SendMessageAsync($"The bot isn't in a guild with the id of {guildId}!");
            }
        }
Esempio n. 20
0
        private static Task JoinedGuild(SocketGuild guild)
        {
            LoggingManager.Log.Warn($"Joined guild {guild.Name} ({guild.Id}).");

            // Leave if an invalid guild
            if (guild.Id != Constants.XathzDiscordGuild || guild.Id != WubbysFunHouse.ServerId)
            {
                guild.LeaveAsync(new RequestOptions {
                    AuditLogReason = $"This bot is private. This guild needs to be whitelisted. Contact: {Constants.Creator}"
                });
            }

            return(Task.CompletedTask);
        }
Esempio n. 21
0
        private async Task JoinedGuildAsync(SocketGuild guild)
        {
            var config = _database.Get <BotConfig>("Config");

            if (!config.GuildBlacklist.Contains(guild.Id))
            {
                _database.AddGuild(guild.Id, guild.Name);
                var defaultPrefix = config.Prefix;
                // TODO: Send message to default channel
            }
            else
            {
                await guild.LeaveAsync();
            }
        }
Esempio n. 22
0
        private Task JoinedGuildAsync(SocketGuild guild)
        {
            using (var Repo = DIManager.Services.GetRequiredService <IFTNPowerRepository>())
            {
                if (Repo.Blacklist.BlacklistGuilds.Where(p => p.Id == guild.Id.ToString()).Any())
                {
                    Global.Log.BlackListedGuild(guild.Id.ToString(), guild.Name);
                    guild.LeaveAsync().Wait();
                    return(Task.CompletedTask);
                }

                var svr = Repo.Guild.AddOrGetGuild(guild.Id.ToString());
                Global.Log.GuildJoin(guild.Id.ToString(), guild.Name, this.Client.GetShardIdFor(guild).ToString(), guild.CurrentUser.GuildPermissions.ManageRoles);
            }
            return(Task.CompletedTask);
        }
Esempio n. 23
0
        private async Task Client_JoinedGuild(SocketGuild arg)
        {
            var tos  = File.ReadAllText(@"Misc\tos.txt");
            var chan = arg.TextChannels.FirstOrDefault(x => x.Name == "general");

            if (chan == null)
            {
                chan = await arg.Owner.GetOrCreateDMChannelAsync() as SocketTextChannel;
            }
            IDMChannel dmchan = null;

            try { await chan.SendMessageAsync(tos); } catch { dmchan = await arg.Owner.GetOrCreateDMChannelAsync(); }
            try { await dmchan.SendMessageAsync(tos); } catch { if (dmchan != null)
                                                                {
                                                                    await arg.LeaveAsync();
                                                                }
            }
        }
        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
        /// <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");
                    }
                }
            }
        }
 public virtual Task LeaveAsync(RequestOptions?options = null)
 {
     return(_socketGuild.LeaveAsync(options));
 }
Esempio n. 27
0
 public Task LeaveAsync(RequestOptions options = null)
 {
     return(Guild.LeaveAsync(options));
 }
Esempio n. 28
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
            }
        }
Esempio n. 29
0
        public async Task <ActionResult> ForceLeaveAsync([Remainder] SocketGuild guild)
        {
            await guild.LeaveAsync();

            return(Ok($"Successfully left **{guild.Name}**."));
        }