示例#1
0
        //// Disabled by Catherine Renelle - Memory Leak Fix
        ////private string _connectionString;
        #endregion

        public async Task MainAsync(string[] args)
        {
            Console.WriteLine(args.Join(", "));
            int shardId;

            if (!int.TryParse(args[0], out shardId))
            {
                throw new Exception("INVALID SHARD ARGUMENT");
            }

            _restClient = new DiscordRestClient();

            //Setup config
            ConfigService.InitializeLoader();
            ConfigService.LoadConfig();

            if (!int.TryParse(ConfigService.GetConfigData("shardCount"), out Utility.TOTAL_SHARDS))
            {
                throw new Exception("INVALID SHARD COUNT");
            }

            //setup discord client
            _client = new DiscordSocketClient(new DiscordSocketConfig()
            {
                LogLevel            = LogSeverity.Info,
                AlwaysDownloadUsers = false,
                MessageCacheSize    = 0,
                TotalShards         = Utility.TOTAL_SHARDS,
                ShardId             = shardId
            });

            Utility.SHARD_ID = shardId;

            _client.Log += Log;

            string token = "";

            ConfigService.GetConfig().TryGetValue("token2", out token);

            await _restClient.LoginAsync(TokenType.Bot, token);

            //setup DB

            Utility.SORA_VERSION = ConfigService.GetConfigData("version");

            // setup banservice
            _banService = new BanService();

            //Setup Services
            ProfileImageGeneration.Initialize();
            _interactive = new InteractiveService(_client);
            //Instantiate the dependency map and add our services and client to it
            var serviceProvider = ConfigureServices();

            // first setup weebservice
            await serviceProvider.GetRequiredService <WeebService>().InitializeAsync();

            //setup command handler
            await serviceProvider.GetRequiredService <CommandHandler>().InitializeAsync(serviceProvider);

            //SETUP other dependency injection services
            serviceProvider.GetRequiredService <ReminderService>().Initialize();
            serviceProvider.GetRequiredService <WaifuService>().Initialize();
            serviceProvider.GetRequiredService <ProfileService>().Initialize();
            serviceProvider.GetRequiredService <StarboardService>().Initialize();
            serviceProvider.GetRequiredService <SelfAssignableRolesService>().Initialize();
            serviceProvider.GetRequiredService <RatelimitingService>().SetTimer();


            //Set up an event handler to execute some state-reliant startup tasks
            _client.Ready += async() =>
            {
                SentryService.Install(_client);
            };


            //Connect to Discord
            await _client.LoginAsync(TokenType.Bot, token);

            await _client.StartAsync();

            // initialize Autoreconnect Feature
            _autoReconnectService = new AutoReconnectService(_client, LogPretty);

            // setup ban users
            _banService.FetchBannedUsers();

            //INITIALIZE CACHE
            CacheService.Initialize();

            //build webserver and inject service
            try
            {
                int port = int.Parse(ConfigService.GetConfigData("port"));
                var host = new WebHostBuilder()
                           .UseKestrel()                                               // MVC webserver is called Kestrel when self hosting
                           .UseUrls("http://*****:*****@"/web/") // Required to be set and exist. Create web folder in the folder the bot runs from. Folder can be empty.
                           .UseWebRoot(Directory.GetCurrentDirectory() + @"/web/")     // Same as above.
                           .UseStartup <Startup>()                                     // Use Startup class in Startup.cs
                           .ConfigureServices(services =>
                {
                    services.AddSingleton(_client);         // Injected Discord client
                    services.AddSingleton(_banService);     // Injected Discord client
                    services.AddCors(options =>
                    {
                        options.AddPolicy("AllowLocal", builder => builder.WithOrigins("localhost"));                                                             // Enable CORS to only allow calls from localhost
                    });
                    services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); // Fixes JSON Recursion issues in API response.
                })
                           .Build();                                                                                                                              // Actually creates the webhost
                Console.WriteLine($"WEB API STARTED ON PORT: {port+shardId}");
                await host.RunAsync();                                                                                                                            // Run in tandem to client
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendMessage(e.ToString());
            }

            //Hang indefinitely
            await Task.Delay(-1);
        }