示例#1
0
文件: Bot.cs 项目: kbtbc/Brock-WhMgr
        public Bot(WhConfig whConfig, string alarmsFilePath)
        {
            _logger.Trace($"WhConfig={whConfig.Discord.GuildId}, OwnerId={whConfig.Discord.OwnerId}, GuildId={whConfig.Discord.GuildId}, WebhookPort={whConfig.WebhookPort}");
            _lang     = new Translator();
            _whConfig = whConfig;
            DataAccessLayer.ConnectionString        = _whConfig.ConnectionStrings.Main;
            DataAccessLayer.ScannerConnectionString = _whConfig.ConnectionStrings.Scanner;

            AppDomain.CurrentDomain.UnhandledException += async(sender, e) =>
            {
                _logger.Debug("Unhandled exception caught.");
                _logger.Error((Exception)e.ExceptionObject);

                if (e.IsTerminating)
                {
                    if (_client != null)
                    {
                        var owner = await _client.GetUserAsync(_whConfig.Discord.OwnerId);

                        if (owner == null)
                        {
                            _logger.Warn($"Failed to get owner from id {_whConfig.Discord.OwnerId}.");
                            return;
                        }

                        await _client.SendDirectMessage(owner, Strings.CrashMessage, null);
                    }
                }
            };

            _gyms = new Dictionary <string, GymDetailsData>();

            _whm = new WebhookManager(_whConfig, alarmsFilePath);
            _whm.PokemonAlarmTriggered    += OnPokemonAlarmTriggered;
            _whm.RaidAlarmTriggered       += OnRaidAlarmTriggered;
            _whm.QuestAlarmTriggered      += OnQuestAlarmTriggered;
            _whm.PokestopAlarmTriggered   += OnPokestopAlarmTriggered;
            _whm.GymAlarmTriggered        += OnGymAlarmTriggered;
            _whm.GymDetailsAlarmTriggered += OnGymDetailsAlarmTriggered;
            _whm.WeatherAlarmTriggered    += OnWeatherAlarmTriggered;
            if (_whConfig.Discord.EnableSubscriptions)
            {
                _whm.PokemonSubscriptionTriggered  += OnPokemonSubscriptionTriggered;
                _whm.RaidSubscriptionTriggered     += OnRaidSubscriptionTriggered;
                _whm.QuestSubscriptionTriggered    += OnQuestSubscriptionTriggered;
                _whm.InvasionSubscriptionTriggered += OnInvasionSubscriptionTriggered;
            }

            _logger.Info("WebhookManager is running...");

            var midnight = new DandTSoftware.Timers.MidnightTimer();

            midnight.TimeReached += async(e) => await ResetQuests();

            midnight.Start();

            _client = new DiscordClient(new DiscordConfiguration
            {
                AutomaticGuildSync = true,
                AutoReconnect      = true,
                EnableCompression  = true,
                Token                 = _whConfig.Discord.Token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true
            });
            _client.Ready += Client_Ready;
            //_client.MessageCreated += Client_MessageCreated;
            _client.ClientErrored += Client_ClientErrored;
            _client.DebugLogger.LogMessageReceived += DebugLogger_LogMessageReceived;

            _interactivity = _client.UseInteractivity
                             (
                new InteractivityConfiguration
            {
                // default pagination behaviour to just ignore the reactions
                PaginationBehaviour = TimeoutBehaviour.Ignore,

                // default pagination timeout to 5 minutes
                PaginationTimeout = TimeSpan.FromMinutes(5),     //TODO: Set prod

                // default timeout for other actions to 2 minutes
                Timeout = TimeSpan.FromMinutes(2)     //TODO: Set prod
            }
                             );

            if (_whConfig.Discord.EnableSubscriptions)
            {
                _subProcessor = new SubscriptionProcessor(_client, _whConfig, _whm);
            }

            DependencyCollection dep;

            using (var d = new DependencyCollectionBuilder())
            {
                d.AddInstance(_dep = new Dependencies(_interactivity, _whm, _subProcessor, _whConfig, _lang, new StripeService(_whConfig.StripeApiKey)));
                dep = d.Build();
            }

            _commands = _client.UseCommandsNext
                        (
                new CommandsNextConfiguration
            {
                StringPrefix         = _whConfig.Discord.CommandPrefix?.ToString(),
                EnableDms            = true,
                EnableMentionPrefix  = string.IsNullOrEmpty(_whConfig.Discord.CommandPrefix),
                EnableDefaultHelp    = false,
                CaseSensitive        = false,
                IgnoreExtraArguments = true,
                Dependencies         = dep
            }
                        );
            _commands.CommandExecuted += Commands_CommandExecuted;
            _commands.CommandErrored  += Commands_CommandErrored;
            _commands.RegisterCommands <Owner>();
            _commands.RegisterCommands <CommunityDay>();
            _commands.RegisterCommands <Nests>();
            _commands.RegisterCommands <ShinyStats>();
            _commands.RegisterCommands <Gyms>();
            _commands.RegisterCommands <Quests>();
            if (_whConfig.Discord.EnableSubscriptions)
            {
                _commands.RegisterCommands <Notifications>();
            }
            if (_whConfig.Discord.EnableCities)
            {
                _commands.RegisterCommands <Feeds>();
            }
        }
示例#2
0
文件: Bot.cs 项目: ZombieCorn80/WhMgr
        /// <summary>
        /// Discord bot class
        /// </summary>
        /// <param name="whConfig">Configuration settings</param>
        public Bot(WhConfigHolder whConfig)
        {
            _logger.Trace($"WhConfig [Servers={whConfig.Instance.Servers.Count}, Port={whConfig.Instance.WebhookPort}]");
            _servers  = new Dictionary <ulong, DiscordClient>();
            _whConfig = whConfig;
            _whm      = new WebhookController(_whConfig);

            // Build form lists for icons
            IconFetcher.Instance.SetIconStyles(_whConfig.Instance.IconStyles);

            // Set translation language
            Translator.Instance.SetLocale(_whConfig.Instance.Locale);

            // Set database connection strings to static properties so we can access within our extension classes
            DataAccessLayer.ConnectionString        = _whConfig.Instance.Database.Main.ToString();
            DataAccessLayer.ScannerConnectionString = _whConfig.Instance.Database.Scanner.ToString();

            // Set unhandled exception event handler
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;

            // Initialize and start midnight reset timer
            var midnight = new DandTSoftware.Timers.MidnightTimer();

            midnight.TimeReached += async(e) => await OnMidnightTimer();

            midnight.Start();

            // Initialize the subscription processor if at least one Discord server wants custom notifications
            // and start database migrator
            if (_whConfig.Instance.Servers.Values.ToList().Exists(x => x.Subscriptions.Enabled))
            {
                // Start database migrator
                var migrator = new DatabaseMigrator();
                while (!migrator.Finished)
                {
                    Thread.Sleep(50);
                }

                _subProcessor = new SubscriptionProcessor(_servers, _whConfig, _whm);
            }

            // Create a DiscordClient object per Discord server in config
            foreach (var(guildId, serverConfig) in _whConfig.Instance.Servers)
            {
                serverConfig.LoadDmAlerts();
                var client = new DiscordClient(new DiscordConfiguration
                {
                    AutomaticGuildSync = true,
                    AutoReconnect      = true,
                    EnableCompression  = true,
                    Token                 = serverConfig.Token,
                    TokenType             = TokenType.Bot,
                    UseInternalLogHandler = true
                });

                // If you are on Windows 7 and using .NETFX, install
                // DSharpPlus.WebSocket.WebSocket4Net from NuGet,
                // add appropriate usings, and uncomment the following
                // line
                //client.SetWebSocketClient<WebSocket4NetClient>();

                // If you are on Windows 7 and using .NET Core, install
                // DSharpPlus.WebSocket.WebSocket4NetCore from NuGet,
                // add appropriate usings, and uncomment the following
                // line
                //client.SetWebSocketClient<WebSocket4NetCoreClient>();

                // If you are using Mono, install
                // DSharpPlus.WebSocket.WebSocketSharp from NuGet,
                // add appropriate usings, and uncomment the following
                // line
                //client.SetWebSocketClient<WebSocketSharpClient>();

                client.Ready              += Client_Ready;
                client.GuildAvailable     += Client_GuildAvailable;
                client.GuildMemberUpdated += Client_GuildMemberUpdated;
                //_client.MessageCreated += Client_MessageCreated;
                client.ClientErrored += Client_ClientErrored;
                client.DebugLogger.LogMessageReceived += DebugLogger_LogMessageReceived;

                // Configure Discord interactivity module
                var interactivity = client.UseInteractivity
                                    (
                    new InteractivityConfiguration
                {
                    // default pagination behaviour to just ignore the reactions
                    PaginationBehaviour = TimeoutBehaviour.Ignore,

                    // default pagination timeout to 5 minutes
                    PaginationTimeout = TimeSpan.FromMinutes(5),

                    // default timeout for other actions to 2 minutes
                    Timeout = TimeSpan.FromMinutes(2)
                }
                                    );

                // Build the dependency collection which will contain our objects that can be globally used within each command module
                DependencyCollection dep;
                using (var d = new DependencyCollectionBuilder())
                {
                    d.AddInstance(new Dependencies(interactivity, _whm, _subProcessor, _whConfig, new StripeService(_whConfig.Instance.StripeApiKey)));
                    dep = d.Build();
                }

                // Discord commands configuration
                var commands = client.UseCommandsNext
                               (
                    new CommandsNextConfiguration
                {
                    StringPrefix = serverConfig.CommandPrefix?.ToString(),
                    EnableDms    = true,
                    // If command prefix is null, allow for mention prefix
                    EnableMentionPrefix = string.IsNullOrEmpty(serverConfig.CommandPrefix),
                    // Use DSharpPlus's built-in help formatter
                    EnableDefaultHelp    = true,
                    CaseSensitive        = false,
                    IgnoreExtraArguments = true,
                    Dependencies         = dep
                }
                               );
                commands.CommandExecuted += Commands_CommandExecuted;
                commands.CommandErrored  += Commands_CommandErrored;
                // Register Discord command handler classes
                commands.RegisterCommands <Owner>();
                commands.RegisterCommands <Event>();
                commands.RegisterCommands <Nests>();
                commands.RegisterCommands <ShinyStats>();
                commands.RegisterCommands <Gyms>();
                commands.RegisterCommands <Quests>();
                commands.RegisterCommands <Settings>();
                if (serverConfig.Subscriptions.Enabled)
                {
                    commands.RegisterCommands <Notifications>();
                }
                if (serverConfig.EnableCities)
                {
                    commands.RegisterCommands <Feeds>();
                }

                _logger.Info($"Configured Discord server {guildId}");
                if (!_servers.ContainsKey(guildId))
                {
                    _servers.Add(guildId, client);
                }

                // Wait 3 seconds between initializing Discord clients
                Task.Delay(3000).GetAwaiter().GetResult();
            }

            RegisterConfigMonitor();
        }