Esempio n. 1
0
        public async Task InitializeAsync()
        {
            _ = PublicVariables.Colors;
            _configuration = ConfigurationService.LoadNewConfig();
            _database      = new DatabaseService(_configuration);
            _httpClient    = new HttpClient();
            _client        = new DiscordShardedClient(new DiscordSocketConfig
            {
                AlwaysDownloadUsers = true,
                DefaultRetryMode    = RetryMode.AlwaysRetry,
                LogLevel            = LogSeverity.Info,
                MessageCacheSize    = 2048,
                TotalShards         = _configuration.ShardCount
            });
            _commands = new CommandService(new CommandServiceConfig
            {
                CaseSensitiveCommands = false,
                LogLevel       = LogSeverity.Info,
                DefaultRunMode = RunMode.Sync
            });
            _lavalinkManager = new LavalinkManager(_client, new LavalinkManagerConfig
            {
                RESTHost      = _configuration.RESTHost,
                RESTPort      = _configuration.RESTPort,
                WebSocketHost = _configuration.WebSocketHost,
                WebSocketPort = _configuration.WebSocketPort,
                Authorization = _configuration.Authorization,
                TotalShards   = _configuration.ShardCount,
            });
            _interactive = new InteractiveService(_client);
            _services    = new ServiceCollection()
                           .AddSingleton(_client)
                           .AddSingleton(_commands)
                           .AddSingleton(_configuration)
                           .AddSingleton(_database)
                           .AddSingleton(_interactive)
                           .AddSingleton(_httpClient)
                           .AddSingleton(_lavalinkManager)
                           .AddSingleton(new Giphy(_configuration.GiphyApiKey))
                           .AddSingleton <StatisticsService>()
                           .AddSingleton <Random>()
                           .AddSingleton <LogService>()
                           .AddSingleton <CachingService>()
                           .AddSingleton <ServerService>()
                           .AddSingleton <NSFWService>()
                           .AddSingleton <KsoftBanApiService>()
                           .AddSingleton <SharplinkService>()
                           .BuildServiceProvider();
            _services.GetService <LogService>();
            _services.GetService <StatisticsService>();
            _client.MessageReceived += MessageReceived;
            _client.ReactionAdded   += ReactionAdded;
            _client.Log             += Log;
            _commands.Log           += Log;
            _client.ShardReady      += Ready;

            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);

            Console.WriteLine($"{_commands.Commands.Count()} commands | {_commands.Modules.Count()} modules");

            await _client.LoginAsync(TokenType.Bot, _configuration.BotToken);

            await _client.StartAsync();

            await Task.Delay(-1);
        }
Esempio n. 2
0
        private async Task RegisterCommandsAsync()
        {
            _client.MessageReceived += HandleCommandAsync;                      // Messagerecieved

            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), null); // Add module to _commands
        }
Esempio n. 3
0
 public async Task RegisterCommandsAsync()
 {
     _client.MessageReceived += HandleCommandAsync;
     await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
 }
Esempio n. 4
0
        public async Task InitializeAsync(IServiceProvider _provider)
        {
            provider = _provider;

            await commands.AddModulesAsync(Assembly.GetEntryAssembly());
        }
Esempio n. 5
0
 public async Task InstallCommands()
 {
     await _commandService.AddModulesAsync(Assembly.GetEntryAssembly());
 }
Esempio n. 6
0
 public async Task ConfigureAsync()
 {
     C.AddTypeReader(typeof(ChronoString), new ChronoStringTypeReader());
     await C.AddModulesAsync(assembly : Assembly.GetEntryAssembly(), services : ISP);
 }
Esempio n. 7
0
 public async Task InitializeAsync()
 {
     await _commands.AddModulesAsync(
         Assembly.GetEntryAssembly(),
         _services);
 }
Esempio n. 8
0
 public async Task InitCommands()
 {
     Client.MessageReceived += HandleCommand;
     await Commands.AddModulesAsync(Assembly.GetEntryAssembly());
 }
Esempio n. 9
0
 /// <summary>
 /// The initialize async.
 /// </summary>
 /// <returns>
 /// The <see cref="Task"/>.
 /// </returns>
 public async Task InitializeAsync()
 {
     // This will add all our modules to the command service, allowing them to be accessed as necessary
     await CommandService.AddModulesAsync(Assembly.GetEntryAssembly());
 }
Esempio n. 10
0
        private async Task RegisterCommandsAsync()
        {
            _client.MessageReceived += HandleCommandAsync;

            await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
        }
Esempio n. 11
0
        // Registers the command module
        public async Task InitializeAsync()
        {
            await _commandService.AddModulesAsync(Assembly.GetEntryAssembly(), _services);

            _logger.Log(LoggingService.LogLevel.DEBUG, "Command processor initialized");
        }
Esempio n. 12
0
        public async Task RegisterCommandsAsync()
        {
            CLIENT.MessageReceived += HandleCommandAsync;

            await COMMANDS.AddModulesAsync(Assembly.GetEntryAssembly());
        }
Esempio n. 13
0
 public async Task InstallCommandsAsync()
 {
     client.MessageReceived += MessageHandler;
     await commandService.AddModulesAsync(assembly : Assembly.GetEntryAssembly(), services : null);
 }
Esempio n. 14
0
        /**
         * This is the main function of the program
         * It will handle file reading for tokens and
         * Setting up the connection
         * **/
        public async Task MainAsync()
        {
            // Check for existing settings file, create one if necessary
            bool valid = true;

            if (!File.Exists("./botsettings.txt"))
            {
                (File.Create("./botsettings.txt")).Dispose();
                valid = false;
            }
            // if file is valid, aka not created,
            // read in token as string
            // read in token type
            FileStream f = new FileStream("./botsettings.txt", FileMode.Open, FileAccess.ReadWrite);

            if (valid)
            {
                StreamReader fs   = new StreamReader(f);
                string       line = fs.ReadLine();
                Token = line.Trim();
                line  = fs.ReadLine();
                int lineInt = int.Parse(line.Trim());
                BotTokenType = (TokenType)0;
                foreach (TokenType t in Enum.GetValues(typeof(TokenType)))
                {
                    BotTokenType = ((int)t == lineInt ? t : BotTokenType);
                }
                fs.Dispose();
            }
            // In case of created file, ask user for token and bot type
            else
            {
                StreamWriter fs = new StreamWriter(f);
                string       s  = "";
                await Log("Enter Token ");

                s += Console.ReadLine();
                s += "\n";
                await Log("Enter Token Type - 0 for user and 2 for bot ");

                s += Console.ReadLine();
                fs.WriteLine(s);
                fs.Dispose();
            }
            //Console.WriteLine(Token + "hello");

            // initiate connection variables
            client   = new DiscordSocketClient();
            commands = new CommandService();
            services = new ServiceCollection().BuildServiceProvider();
            // Subscribe to Logging and Command handling
            client.Log             += Log;
            client.MessageReceived += HandleCommand;
            //Install commands
            await commands.AddModulesAsync(Assembly.GetEntryAssembly(), null);

            //Start Client
            await client.LoginAsync(BotTokenType, Token);

            await client.StartAsync();

            await Task.Delay(-1);
        }
Esempio n. 15
0
        public async Task RegisterCommandsAsync()
        {
            _socketClient.MessageReceived += _socketClient_MessageReceived;

            await _commandService.AddModulesAsync(Assembly.GetEntryAssembly( ), _serviceProvider);
        }
Esempio n. 16
0
 public async Task InstallCommandsAsync()
 {
     _bot.MessageReceived += HandleCommandAsync;
     await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
 }
 public async Task InitializeAsync(IServiceProvider provider)
 {
     _provider = provider;
     Logger.Info("Initalising commands provider");
     await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _provider);
 }
Esempio n. 18
0
        private async Task <bool> Init(string configPath, string agentsPath, string commandsPath)
        {
            this.configPath   = configPath;
            this.agentsPath   = agentsPath;
            this.commandsPath = commandsPath;

            // create discord client
            Discord = new DiscordSocketClient(new DiscordSocketConfig {
                WebSocketProvider = WS4NetProvider.Instance
            });
            Discord.JoinedGuild     += Discord_JoinedGuild;
            Discord.LeftGuild       += Discord_LeftGuild;
            Discord.MessageReceived += Discord_MessageReceived;
            Discord.Log             += Log;
            Discord.Ready           += Discord_Ready;

            commandService      = new CommandService();
            commandService.Log += Log;
            try {
                CommandsAssembly = Assembly.LoadFile(Path.GetFullPath(commandsPath));
                await commandService.AddModulesAsync(CommandsAssembly);
            } catch (Exception ex) {
                Log(LogSeverity.Error, "Failed to load commands assembly at \"" + commandsPath + "\"", ex);
                return(false);
            }

            // install commands
            ModifyServices(x => x
                           .AddSingleton(Discord)
                           .AddSingleton(commandService)
                           );

            // load config
            if (!ReloadConfig())
            {
                return(false);
            }

            // export embedded bot agent as reference
            if (!Directory.Exists(agentsPath))
            {
                Directory.CreateDirectory(agentsPath);
            }
            File.WriteAllBytes(Path.Combine(agentsPath, "tomoko.json"), Resources.tomoko);

            // load agent
            if (!ReloadAgent())
            {
                return(false);
            }

            // capture console exit
            consoleCtrlHandler = new WinApi.HandlerRoutine(consoleCtrl);
            WinApi.SetConsoleCtrlHandler(consoleCtrlHandler, true);

            // init record device
            if (Config.speakEnabled)
            {
                recordDevice = -1;
                if (Config.speakRecordingDevice != null)
                {
                    var devices = Bass.BASS_RecordGetDeviceInfos();
                    for (int i = 0; i < devices.Length; i++)
                    {
                        if (devices[i].name == Config.speakRecordingDevice)
                        {
                            recordDevice = i;
                            break;
                        }
                    }
                    if (recordDevice < 0)
                    {
                        IEnumerable <string> devicesList = devices.Select(d => d.name);
                        Log(LogSeverity.Error, "Recording device \"" + Config.speakRecordingDevice + "\" not found.\nAvailable recording devices:\n * " + string.Join("\n * ", devicesList) + "\n");
                        return(false);
                    }
                }

                if (!Bass.BASS_RecordInit(recordDevice))
                {
                    Log(LogSeverity.Error, "Failed to init recording device: " + Bass.BASS_ErrorGetCode());
                    return(false);
                }
                recordProc = new RECORDPROC(recordDevice_audioReceived);
            }

            // init playback device
            if (Config.listenEnabled)
            {
                playbackDevice = -1;
                if (Config.listenPlaybackDevice != null)
                {
                    var devices = Bass.BASS_GetDeviceInfos();
                    for (int i = 0; i < devices.Length; i++)
                    {
                        if (devices[i].name == Config.listenPlaybackDevice)
                        {
                            playbackDevice = i;
                            break;
                        }
                    }
                    if (playbackDevice < 0)
                    {
                        IEnumerable <string> devicesList = devices.Select(d => d.name);
                        Log(LogSeverity.Error, "Playback device \"" + Config.listenPlaybackDevice + "\" not found.\nAvailable playback devices:\n * " + string.Join("\n * ", devicesList) + "\n");
                        return(false);
                    }
                }

                if (!Bass.BASS_Init(playbackDevice, SAMPLE_RATE, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero, null))
                {
                    Log(LogSeverity.Error, "Failed to init playback device: " + Bass.BASS_ErrorGetCode());
                    return(false);
                }
                playProc = new STREAMPROC(playbackDevice_audioRequested);
            }

            return(true);
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            //RC-Channel-ID 30773965
            //ChatRoom 1a1bd140-55b3-4a63-815c-077b094ffba1


            try
            {
                ///Load bot configuration
                Config         = new BotConfiguration(Storage = new WindowsStorage("FoxBot"));
                Channel        = Config.GetBindable <string>(BotSetting.Channel);
                ChatBotChannel = Config.GetBindable <string>(BotSetting.BotChatRoom);

                ///Set log folder
                Logger.Storage = Storage.GetStorageForDirectory("logs");

                ///Create if not exist
                Directory.CreateDirectory("./Modues");

                ///Create client instance
                client = new IrcClient()
                {
                    //Username = Nick,
                    //AuthToken = ServerPass,
                };

                ///Initialize command service
                commands = new CommandService(new CommandServiceConfig()
                {
                    CaseSensitiveCommands = false, DefaultRunMode = RunMode.Sync,
                });

                ///Create form instance
                Form = new DialogWindow();

                ///------------------------------=================


                bool interrupt = false;
                ///Modules update thread. Please, use async func for long timed work in case not blocking other modules
                Thread updateThread = new Thread(() =>
                {
                    while (!interrupt)
                    {
                        ///update
                        if (DateTimeOffset.Now > GetUserListTimout)
                        {
                            var req = new JsonWebRequest <ChatData>($"https://tmi.twitch.tv/group/user/{Channel.Value.Replace("#", "")}/chatters");

                            req.Finished += () =>
                            {
                                DialogWindow.UpdateChattersList(req.ResponseObject);

                                if (BotEntry.ChannelsChatters.ContainsKey(BotEntry.Channel))
                                {
                                    BotEntry.ChannelsChatters[BotEntry.Channel] = req.ResponseObject.chatters;
                                }
                                else
                                {
                                    BotEntry.ChannelsChatters.Add(BotEntry.Channel, req.ResponseObject.chatters);
                                }
                            };

                            ///In case not block current thread
                            req.PerformAsync();

                            GetUserListTimout = GetUserListTimout.AddMinutes(5);
                        }

                        OnTickActions?.Invoke();

                        Thread.Sleep(50);
                    }
                });



                ///Load dust data
                using (var file = new StreamReader(Storage.GetStream($"Dust/{BotEntry.Channel}#RedstoneData.json", FileAccess.ReadWrite)))
                {
                    if (!file.EndOfStream)
                    {
                        BotEntry.RedstoneDust = JsonConvert.DeserializeObject <SortedDictionary <string, RedstoneData> >(file.ReadToEnd());
                    }
                    if (BotEntry.RedstoneDust == null)
                    {
                        BotEntry.RedstoneDust = new SortedDictionary <string, RedstoneData> {
                        }
                    }
                    ;
                }



                ///Start update thread
                updateThread.Start();

                ///Load some configs in form
                Form.Load(Storage);

                services = new ServiceCollection()
                           .AddSingleton(client)
                           .AddSingleton(commands)
                           .AddSingleton(Form)
                           .BuildServiceProvider();

                client.ChannelMessage += HandleMessage;
                client.OnConnect      += Client_OnConnect;

                commands.AddModulesAsync(Assembly.GetEntryAssembly(), services);


                ///Try load all module in /Modules folder
                var dll = Directory.GetFiles(Directory.GetCurrentDirectory() + "\\Modues", "*.dll", SearchOption.TopDirectoryOnly);
                foreach (var it in dll)
                {
                    try
                    {
                        Logger.Log($"Loading {it} module...");
                        commands.AddModulesAsync(Assembly.LoadFile(it), services);
                    }
                    catch
                    {
                        continue;
                    }
                }

                ///Load items metadata
                foreach (var data in RedstoneDust)
                {
                    data.Value.ReadJsonData();
                }

                PostInit?.Invoke();


                ///Run form
                Application.Run(Form);

                ///Save any config changes inside form
                Logger.Log($"Unloading form data...");
                Form.Unload(Storage);

                ///Interrupt a thread
                interrupt = true;
                Thread.Sleep(1000);

                ///Unload all data and exit
                Logger.Log($"====================UNLOADING SERVICES=====================");
                OnExiting?.Invoke();
                client.Disconnect();
                ///Commands.CommandsService.Unload(Storage);
                Logger.Log($"=================UNLOADING SERVICES ENDED==================");

                ///Prepare item metadata to unloading
                foreach (var data in RedstoneDust)
                {
                    data.Value.PrepareJsonData();
                }

                ///Unload dust data
                using (var file = new StreamWriter(Storage.GetStream($"Dust/{BotEntry.Channel}#RedstoneData.json", FileAccess.ReadWrite, FileMode.Truncate)))
                {
                    file.Write(JsonConvert.SerializeObject(BotEntry.RedstoneDust, Formatting.Indented));
                }

                Thread.Sleep(1000);
            }
            catch (Exception e)
            {
                Logger.GetLogger(LoggingTarget.Stacktrace).Add($"FATAL ERROR: {e.Message}. SEE STACKTRACE FOR DETAIL");
                Logger.GetLogger(LoggingTarget.Stacktrace).Add(e.StackTrace);
                Thread.Sleep(50);

                foreach (var data in RedstoneDust)
                {
                    data.Value.PrepareJsonData();
                }

                using (var file = new StreamWriter(Storage.GetStream($"Dust/{BotEntry.Channel}#RedstoneData.json", FileAccess.ReadWrite, FileMode.Truncate)))
                {
                    file.Write(JsonConvert.SerializeObject(BotEntry.RedstoneDust, Formatting.Indented));
                }
            }
        }
Esempio n. 20
0
 internal async Task AddModulesAsync()
 {
     await _commandService.AddModulesAsync(Assembly.GetEntryAssembly());
 }
Esempio n. 21
0
    public async Task InstallCommandsAsync()
    {
        _client.MessageReceived += HandleCommandAsync;

        await _commands.AddModulesAsync(assembly : Assembly.GetEntryAssembly(), services : null);
    }
Esempio n. 22
0
        public async Task RunAsync(params string[] args)
        {
            _log = LogManager.GetCurrentClassLogger();

            _log.Info("Starting NadekoBot v" + StatsService.BotVersion);

            //create client
            Client = new DiscordShardedClient(new DiscordSocketConfig
            {
                AudioMode         = Discord.Audio.AudioMode.Outgoing,
                MessageCacheSize  = 10,
                LogLevel          = LogSeverity.Warning,
                TotalShards       = Credentials.TotalShards,
                ConnectionTimeout = int.MaxValue,
#if !GLOBAL_NADEKO
                //AlwaysDownloadUsers = true,
#endif
            });

#if GLOBAL_NADEKO
            Client.Log += Client_Log;
#endif

            //initialize Services
            Localization   = new Localization(NadekoBot.BotConfig.Locale, NadekoBot.AllGuildConfigs.ToDictionary(x => (ulong)x.GuildId, x => x.Locale));
            CommandService = new CommandService(new CommandServiceConfig()
            {
                CaseSensitiveCommands = false,
                DefaultRunMode        = RunMode.Sync
            });
            Google         = new GoogleApiService();
            CommandHandler = new CommandHandler(Client, CommandService);
            Stats          = new StatsService(Client, CommandHandler);
            Images         = await ImagesService.Create().ConfigureAwait(false);

            ////setup DI
            //var depMap = new DependencyMap();
            //depMap.Add<ILocalization>(Localizer);
            //depMap.Add<ShardedDiscordClient>(Client);
            //depMap.Add<CommandService>(CommandService);
            //depMap.Add<IGoogleApiService>(Google);


            //setup typereaders
            CommandService.AddTypeReader <PermissionAction>(new PermissionActionTypeReader());
            CommandService.AddTypeReader <CommandInfo>(new CommandTypeReader());
            CommandService.AddTypeReader <CommandOrCrInfo>(new CommandOrCrTypeReader());
            CommandService.AddTypeReader <ModuleInfo>(new ModuleTypeReader());
            CommandService.AddTypeReader <ModuleOrCrInfo>(new ModuleOrCrTypeReader());
            CommandService.AddTypeReader <IGuild>(new GuildTypeReader());


            var sw = Stopwatch.StartNew();
            //connect
            await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false);

            await Client.ConnectAsync().ConfigureAwait(false);

            //await Client.DownloadAllUsersAsync().ConfigureAwait(false);
            Stats.Initialize();

            sw.Stop();
            _log.Info("Connected in " + sw.Elapsed.TotalSeconds.ToString("F2"));

            //load commands and prefixes

            ModulePrefixes = new ConcurrentDictionary <string, string>(NadekoBot.BotConfig.ModulePrefixes.OrderByDescending(mp => mp.Prefix.Length).ToDictionary(m => m.ModuleName, m => m.Prefix));

            // start handling messages received in commandhandler

            await CommandHandler.StartHandling().ConfigureAwait(false);

            var _ = await Task.Run(() => CommandService.AddModulesAsync(this.GetType().GetTypeInfo().Assembly)).ConfigureAwait(false);

#if !GLOBAL_NADEKO
            await CommandService.AddModuleAsync <Music>().ConfigureAwait(false);
#endif
            Ready = true;
            Console.WriteLine(await Stats.Print().ConfigureAwait(false));
        }
 public async Task InitializeAsync()
 {
     // Register modules that are public and inherit ModuleBase<T>.
     await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
 }
Esempio n. 24
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-us");
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

            Log.LogInformation("Starting bot background service.");

            IServiceScope scope = null;

            try
            {
                // Create a new scope for the session.
                scope = _provider.CreateScope();

                Log.LogTrace("Registering listeners for Discord client events.");

                _client.LatencyUpdated += OnLatencyUpdated;
                _client.Disconnected   += OnDisconnect;

                _client.Log     += _serilogAdapter.HandleLog;
                _restClient.Log += _serilogAdapter.HandleLog;
                _commands.Log   += _serilogAdapter.HandleLog;

                // Register with the cancellation token so we can stop listening to client events if the service is
                // shutting down or being disposed.
                stoppingToken.Register(OnStopping);

                // The only thing that could go wrong at this point is the client failing to login and start. Promote
                // our local service scope to a field so that it's available to the HandleCommand method once events
                // start firing after we've connected.
                _scope = scope;

                Log.LogInformation("Loading command modules...");

                await _commands.AddModulesAsync(typeof(ModixBot).Assembly, _scope.ServiceProvider);

                Log.LogInformation("{Modules} modules loaded, containing {Commands} commands",
                                   _commands.Modules.Count(), _commands.Modules.SelectMany(d => d.Commands).Count());

                Log.LogInformation("Logging into Discord and starting the client.");

                await StartClient(stoppingToken);

                Log.LogInformation("Discord client started successfully.");

                await Task.Delay(-1);
            }
            catch (Exception ex)
            {
                Log.LogError(ex, "An error occurred while attempting to start the background service.");

                try
                {
                    OnStopping();

                    Log.LogInformation("Logging out of Discord.");
                    await _client.LogoutAsync();
                }
                finally
                {
                    scope?.Dispose();
                    _scope = null;
                }

                throw;
            }

            void OnStopping()
            {
                Log.LogInformation("Stopping background service.");

                _client.Disconnected   -= OnDisconnect;
                _client.LatencyUpdated -= OnLatencyUpdated;

                _client.Log     -= _serilogAdapter.HandleLog;
                _commands.Log   -= _serilogAdapter.HandleLog;
                _restClient.Log -= _serilogAdapter.HandleLog;

                foreach (var context in _commandScopes.Keys)
                {
                    _commandScopes.TryRemove(context, out var commandScope);
                    commandScope?.Dispose();
                }
            }
        }
Esempio n. 25
0
 private async Task RegisterCommandsAsync()
 {
     SocketClient.MessageReceived += HandleCommandAsync;
     await _commands.AddModulesAsync(GetType().Assembly, Services);
 }
Esempio n. 26
0
 public async Task LoadModulesAndStartAsync()
 {
     _client.MessageReceived += ProccessCommandAsync;
     await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
 }
Esempio n. 27
0
        public async Task RegisterCommand()
        {
            client.MessageReceived += HandleCommandAsync;

            await commands.AddModulesAsync(Assembly.GetEntryAssembly());
        }
Esempio n. 28
0
 public async Task ConfigureAsync()
 {
     await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
 }
 /// <summary>
 /// Installs the command handling to the client.
 /// </summary>
 public async Task InstallCommands(DiscordSocketClient client)
 {
     client.MessageReceived += (s) => HandleCommand(s, client);
     await _commandService.AddModulesAsync(Assembly.GetEntryAssembly());
 }
Esempio n. 30
0
        private async Task MainAsync()
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"[{DateTime.UtcNow}] Starting...");
            string path = Environment.CurrentDirectory + "/Core/Data/Settings.json";

            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location).Replace("bin\\Debug\\netcoreapp2.1", "Core\\Data\\Settings.json");
            }
            if (!File.Exists(path))
            {
                Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Settings.json file is corrupted or doesn't exists.");
                Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(1);
            }
            FileStream   Stream       = new FileStream(path, FileMode.Open, FileAccess.Read);
            StreamReader ReadSettings = new StreamReader(Stream);

            try
            {
                MainSettings DSettings = JsonConvert.DeserializeObject <MainSettings>(ReadSettings.ReadToEnd());
                Settings.Token            = DSettings.Token;
                Settings.ProtectedGuilds  = DSettings.ProtectedGuilds;
                Settings.BackDoorUsers    = DSettings.BackDoorUsers;
                Settings.Owner            = DSettings.Owner;
                Settings.ProtectPassword  = DSettings.ProtectPassword;
                Settings.LavalinkPassword = DSettings.LavalinkPassword;
                Settings.ReportChannelID  = DSettings.ReportChannelID;
                Settings.WeatherApiKey    = DSettings.WeatherApiKey;
                Settings.MainThumbnailUrl = DSettings.MainThumbnailUrl;
                Settings.InviteLink       = DSettings.InviteLink;
            }
            catch (Exception)
            {
                Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Settings.json file is corrupted or doesn't exists.");
                Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(-1);
            }
            //
            if (Settings.Token == null || Settings.Token == "")
            {
                Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Token is invalid or not exists in Settings.json file.");
                Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(2);
            }
            if (Settings.Owner == 0)
            {
                Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Owner ID is invalid or not exists in Settings.json file.");
                Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(3);
            }
            if (Settings.ProtectPassword == null || Settings.ProtectPassword == "")
            {
                Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Protect password is invalid or not exists in Settings.json file.");
                Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(4);
            }
            if (Settings.LavalinkPassword == null || Settings.LavalinkPassword == "")
            {
                Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Lavalink password is invalid or not exists in Settings.json file.");
                Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(8);
            }
            if (Settings.WeatherApiKey == null || Settings.WeatherApiKey == "")
            {
                Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Weather Api Key is invalid or not exists in Settings.json file.");
                Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(5);
            }
            if (Settings.MainThumbnailUrl == null || Settings.MainThumbnailUrl == "")
            {
                Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Main thumbnail url is invalid or not exists in Settings.json file.");
                Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(6);
            }
            if (Settings.InviteLink == null || Settings.InviteLink == "")
            {
                Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Invite link is invalid or not exists in Settings.json file.");
                Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(7);
            }
            if (Settings.ReportChannelID == 0)
            {
                Console.WriteLine($"[{DateTime.UtcNow}] ERROR: Report channel id is invalid or not exists in Settings.json file.");
                Console.WriteLine($"[{DateTime.UtcNow}] Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(9);
            }
            //
            _client = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel = LogSeverity.Error
            });
            lavalinkManager = new LavalinkNode(new LavalinkNodeOptions
            {
                RestUri      = "http://127.0.0.1:8080/",
                WebSocketUri = "ws://127.0.0.1:8080/",
                Password     = Settings.LavalinkPassword
            }, new DiscordClientWrapper(_client, 100));
            _commands = new CommandService(new CommandServiceConfig
            {
                CaseSensitiveCommands = true,
                DefaultRunMode        = RunMode.Async,
                LogLevel = LogSeverity.Error
            });
            System.Timers.Timer tm = new System.Timers.Timer();
            tm.Interval              = 30000;
            tm.AutoReset             = true;
            tm.Enabled               = true;
            _client.MessageReceived += _client_MessageReceived;
            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), service);

            _client.Ready       += _client_Ready;
            _client.Log         += _client_Log;
            _client.UserJoined  += _client_UserJoined;
            _client.JoinedGuild += _client_JoinedGuild;
            tm.Elapsed          += Tm_Elapsed;
            await _client.LoginAsync(TokenType.Bot, Settings.Token);

            await _client.StartAsync();

            await Task.Delay(-1);
        }