Exemplo n.º 1
0
        private async Task RunAsync()
        {
            socketClient = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel            = LogSeverity.Verbose,
                AlwaysDownloadUsers = true,
                MessageCacheSize    = 100,
                GatewayIntents      = GatewayIntents.DirectMessages | GatewayIntents.GuildMessages |
                                      GatewayIntents.GuildMembers | GatewayIntents.Guilds | GatewayIntents.GuildMessageReactions
            });
            socketClient.Log += Log;

            restClient = new DiscordRestClient(new DiscordRestConfig
            {
                LogLevel = LogSeverity.Verbose
            });
            restClient.Log += Log;

            if (File.Exists("./update"))
            {
                var temp = File.ReadAllText("./update");
                ulong.TryParse(temp, out updateChannel);
                File.Delete("./update");
                Console.WriteLine($"Found an update file! It contained [{temp}] and we got [{updateChannel}] from it!");
            }

            config = await Config.Load();

            dbhelper = new DatabaseHelper();
            logger   = new Logger();

            var map = new ServiceCollection().AddSingleton(socketClient).AddSingleton(config).AddSingleton(logger).AddSingleton(dbhelper).AddSingleton(restClient).BuildServiceProvider();

            await socketClient.LoginAsync(TokenType.Bot, config.Token);

            await socketClient.StartAsync();

            await restClient.LoginAsync(TokenType.Bot, config.Token);

            if (File.Exists("./deadlock"))
            {
                Console.WriteLine("We're recovering from a deadlock.");
                File.Delete("./deadlock");
                foreach (var u in config.OwnerIds)
                {
                    (await restClient.GetUserAsync(u))?
                    .SendMessageAsync($"I recovered from a deadlock.\n`{DateTime.Now.ToShortDateString()}` `{DateTime.Now.ToLongTimeString()}`");
                }
            }

            socketClient.GuildAvailable += Client_GuildAvailable;
            socketClient.Disconnected   += SocketClient_Disconnected;

            await dbhelper.Install(map);

            await logger.Install(map);

            SpoilerWords = JsonStorage.DeserializeObjectFromFile <List <string> >("filter.json");
            RoleColors   = JsonStorage.DeserializeObjectFromFile <Dictionary <string, ulong> >("colors.json");

            handler = new CommandHandler();
            await handler.Install(map);

            try
            {
                socketClient.MessageReceived    += Client_MessageReceived;
                socketClient.ReactionAdded      += Client_ReactionAdded;
                socketClient.ReactionRemoved    += Client_ReactionRemoved;
                socketClient.GuildMemberUpdated += SocketClient_GuildMemberUpdated;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Source}\n{ex.Message}\n{ex.StackTrace}");
            }

            // perpetual queue to add/remove color roles
            Task.Run(async() =>
            {
                while (true)
                {
                    await Task.Delay(3000);

                    try
                    {
                        if (lastRole < DateTimeOffset.Now.AddSeconds(-15))
                        {
                            continue;
                        }

                        List <RoleAddition> temp = new List <RoleAddition>();
                        RoleAddition tempAction  = null;

                        while (RoleAdditions.TryDequeue(out tempAction))
                        {
                            if (config.BlacklistedUsers.ContainsKey(tempAction.userId) &&
                                config.BlacklistedUsers[tempAction.userId] > DateTimeOffset.Now)
                            {
                                continue;
                            }
                            else
                            {
                                temp.Add(tempAction);
                            }
                        }

                        if (temp.Count() != temp.Select(x => x.userId).Distinct().Count())
                        {
                            // SOMEONE clicked on more than one role at a time!
                            Dictionary <ulong, int> counter = new Dictionary <ulong, int>();

                            foreach (var u in temp.Select(x => x.userId))
                            {
                                if (!counter.ContainsKey(u))
                                {
                                    counter[u] = 0;
                                }

                                counter[u]++;
                            }

                            foreach (var u in counter)
                            {
                                if (u.Value > 4)
                                {
                                    try
                                    {
                                        await socketClient.GetUser(u.Key).SendMessageAsync("Hey, slow down! You don't need every color on that list! No more colors for an hour!");
                                    }
                                    catch (Exception ex)
                                    {
                                        // User has their DMs disabled
                                    }

                                    await RemoveAllColors(u.Key);
                                    //config.BlacklistedUsers.Add(u.Key, DateTimeOffset.Now.AddHours(1));
                                    Console.WriteLine($"Blacklisted [{u.Key}] from colors.");

                                    while (temp.Select(x => x.userId).Contains(u.Key))
                                    {
                                        temp.Remove(temp.FirstOrDefault(x => x.userId == u.Key));
                                    }
                                }
                            }
                        }

                        foreach (var ra in temp)
                        {
                            if (ra.remove)
                            {
                                await RemoveAllColors(ra.userId);
                            }
                            else
                            {
                                var user = socketClient.GetGuild(config.HomeGuildId).GetUser(ra.userId) as SocketGuildUser;
                                user.AddRoleAsync(user.Guild.GetRole(ra.roleId));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        await Task.Delay(1000);
                        // idk something errored
                    }
                }
            });

            //var avatar = new Image(File.OpenRead(".\\TaranzaSOUL.png"));
            //await client.CurrentUser.ModifyAsync(x => x.Avatar = avatar);

            await Task.Delay(-1);
        }