Exemple #1
0
        private async Task <bool> IsMultiplayerGameAsync(string username)
        {
            // Get current game name
            ChannelJSON json = await _twitchInfo.GetBroadcasterChannelByIdAsync();

            string gameTitle = json.Game;

            // Grab game id in order to find party member
            TwitchGameCategory game = await _gameDirectory.GetGameIdAsync(gameTitle);

            if (string.IsNullOrEmpty(gameTitle))
            {
                _irc.SendPublicChatMessage("I cannot see the name of the game. It's currently set to either NULL or EMPTY. "
                                           + "Please have the chat verify that the game has been set for this stream. "
                                           + $"If the error persists, please have @{_botConfig.Broadcaster.ToLower()} retype the game in their Twitch Live Dashboard. "
                                           + "If this error shows up again and your chat can see the game set for the stream, please contact my master with !support in this chat");
                return(false);
            }
            else if (game == null || game.Id == 0)
            {
                _irc.SendPublicChatMessage($"I cannot find the game, \"{gameTitle.TrimEnd()}\", in the database. "
                                           + $"Have my master resolve this issue by typing !support in this chat @{username}");
                return(false);
            }

            if (!game.Multiplayer)
            {
                _irc.SendPublicChatMessage("This game is set to single-player only. "
                                           + $"Contact my master with !support in this chat if this isn't correct @{username}");
                return(false);
            }

            return(true);
        }
        private async Task <DateTime> RefreshBossFightAsync()
        {
            try
            {
                // Check if any fighters are queued or fighting
                if (_bossFightSettingsInstance.Fighters.Count > 0)
                {
                    _irc.SendPublicChatMessage($"A boss fight is either queued or in progress @{_botConfig.Broadcaster}");
                    return(DateTime.Now);
                }

                // Get current game name
                ChannelJSON json = await _twitchInfo.GetBroadcasterChannelByIdAsync();

                string gameTitle = json.Game;

                // Grab game id in order to find party member
                TwitchGameCategory game = await _gameDirectory.GetGameIdAsync(gameTitle);

                // During refresh, make sure no fighters can join
                _bossFightSettingsInstance.RefreshBossFight = true;
                await _bossFightSettingsInstance.LoadSettings(_broadcasterInstance.DatabaseId, game?.Id, _botConfig.TwitchBotApiLink);

                _bossFightSettingsInstance.RefreshBossFight = false;

                _irc.SendPublicChatMessage($"Boss fight settings refreshed @{_botConfig.Broadcaster}");
            }
            catch (Exception ex)
            {
                await _errHndlrInstance.LogError(ex, "ReminderFeature", "RefreshBossFight()", false, "!refreshbossfight");
            }

            return(DateTime.Now);
        }
        private async void Run()
        {
            await LoadReminderContextAsync(); // initial load

            DateTime midnightNextDay = DateTime.Today.AddDays(1);

            while (true)
            {
                ChannelJSON channelJSON = await _twitchInfo.GetBroadcasterChannelByIdAsync();

                string gameTitle = channelJSON.Game;

                TwitchGameCategory game = await _gameDirectory.GetGameIdAsync(gameTitle);

                if (game == null || game.Id == 0)
                {
                    _gameId = null;
                }
                else
                {
                    _gameId = game.Id;
                }

                // remove pending reminders
                _delayedMessagesInstance.DelayedMessages.RemoveAll(r => r.ReminderId > 0);

                foreach (RemindUser reminder in _reminders.OrderBy(m => m.RemindEveryMin))
                {
                    if (IsEveryMinReminder(reminder))
                    {
                        continue;
                    }
                    else if (IsCountdownEvent(reminder))
                    {
                        continue;
                    }
                    else
                    {
                        AddDayOfReminder(reminder);
                    }
                }

                if (_refreshReminders)
                {
                    _irc.SendPublicChatMessage("Reminders refreshed!");
                }

                // reset refresh
                midnightNextDay   = DateTime.Today.AddDays(1);
                _refreshReminders = false;

                // wait until midnight to check reminders
                // unless a manual refresh was called
                while (DateTime.Now < midnightNextDay && !_refreshReminders)
                {
                    Thread.Sleep(1000); // 1 second
                }
            }
        }
Exemple #4
0
        private async Task <DateTime> SetGameIgnAsync(TwitchChatter chatter)
        {
            try
            {
                string message = chatter.Message;
                string gameIgn = message.Substring(message.IndexOf(" ") + 1);

                // Get current game name
                ChannelJSON json = await _twitchInfo.GetBroadcasterChannelByIdAsync();

                string gameTitle = json.Game;

                TwitchGameCategory game = await _gameDirectory.GetGameIdAsync(gameTitle);

                InGameUsername ign = await _ign.GetInGameUsernameAsync(_broadcasterInstance.DatabaseId, game);

                if (game == null)
                {
                    _irc.SendPublicChatMessage("The game isn't in the database. "
                                               + $"Please set this as part of the general game IDs or IGNs using !setgenericign or !setgenericid @{chatter.DisplayName}");
                    return(DateTime.Now);
                }

                if (ign == null || (ign != null && ign.GameId == null))
                {
                    await _ign.CreateInGameUsernameAsync(game.Id, _broadcasterInstance.DatabaseId, gameIgn);

                    _irc.SendPublicChatMessage($"Yay! You've set your IGN for {gameTitle} to \"{gameIgn}\" @{chatter.DisplayName}");
                }
                else
                {
                    ign.Message = gameIgn;
                    await _ign.UpdateInGameUsernameAsync(ign.Id, _broadcasterInstance.DatabaseId, ign);

                    _irc.SendPublicChatMessage($"Yay! You've updated your IGN for {gameTitle} to \"{gameIgn}\" @{chatter.DisplayName}");
                }
            }
            catch (Exception ex)
            {
                await _errHndlrInstance.LogError(ex, "InGameNameFeature", "SetGameIgn(TwitchChatter)", false, "!setgameign", chatter.Message);
            }

            return(DateTime.Now);
        }
Exemple #5
0
        public async Task RunAsync()
        {
            try
            {
                // ToDo: Check version number of application
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error Message: {ex.Message}");
                Console.WriteLine();
                Console.WriteLine("Cannot connect to database to verify the correct version of myself");
                Console.WriteLine("Local troubleshooting needed by author of this bot");
                Console.WriteLine();
                Console.WriteLine("Shutting down now...");
                Thread.Sleep(5000);
                Environment.Exit(1);
            }

            try
            {
                // Configure error handler singleton class
                ErrorHandler.Configure(_broadcasterInstance.DatabaseId, _irc, _botConfig);

                // Get broadcaster ID so the user can only see their data from the db
                await SetBroadcasterIdsAsync();

                if (_broadcasterInstance.DatabaseId == 0 || string.IsNullOrEmpty(_broadcasterInstance.TwitchId))
                {
                    Console.WriteLine("Cannot find a broadcaster ID for you. "
                                      + "Please contact the author with a detailed description of the issue");
                    Console.WriteLine();
                    Console.WriteLine("Shutting down now...");
                    Thread.Sleep(5000);
                    Environment.Exit(1);
                }

                // Configure error handler singleton class
                ErrorHandler.Configure(_broadcasterInstance.DatabaseId, _irc, _botConfig);

                /* Connect to local Spotify client */
                _spotify = new SpotifyWebClient(_botConfig);
                await _spotify.ConnectAsync();

                /* Load command classes */
                _commandSystem = new CommandSystem(_irc, _botConfig, _appConfig, _bank, _songRequestBlacklist,
                                                   _libVLCSharpPlayer, _songRequestSetting, _spotify, _twitchInfo, _follower, _gameDirectory,
                                                   _ign, _manualSongRequest, _quote, _partyUp);

                /* Whisper broadcaster bot settings */
                Console.WriteLine();
                Console.WriteLine("---> Extra Bot Settings <---");
                Console.WriteLine($"Currency type: {_botConfig.CurrencyType}");
                Console.WriteLine($"Enable Auto Tweets: {_botConfig.EnableTweets}");
                Console.WriteLine($"Enable Auto Display Songs: {_botConfig.EnableDisplaySong}");
                Console.WriteLine($"Stream latency: {_botConfig.StreamLatency} second(s)");
                Console.WriteLine($"Regular follower hours: {_botConfig.RegularFollowerHours}");
                Console.WriteLine();

                /* Configure YouTube song request from user's YT account (request permission if needed) */
                await GetYouTubeAuthAsync();

                /* Start listening for delayed messages */
                DelayMessage delayMsg = new DelayMessage(_irc);
                delayMsg.Start();

                /* Grab list of chatters from channel */
                _twitchChatterListener.Start();

                /* Get the status of the Twitch stream */
                _twitchStreamStatus = new TwitchStreamStatus(_irc, _twitchInfo, _botConfig.Broadcaster);
                await _twitchStreamStatus.LoadChannelInfoAsync();

                _twitchStreamStatus.Start();

                /* Pull list of followers and check experience points for stream leveling */
                _followerSubscriberListener.Start(_irc, _broadcasterInstance.DatabaseId);

                /* Load/create settings and start the queue for the heist */
                await _bankHeistInstance.LoadSettings(_broadcasterInstance.DatabaseId, _botConfig.TwitchBotApiLink);

                _bankHeist.Start(_irc, _broadcasterInstance.DatabaseId);

                if (string.IsNullOrEmpty(TwitchStreamStatus.CurrentCategory))
                {
                    _irc.SendPublicChatMessage("WARNING: I cannot see the name of the game. It's currently set to either NULL or EMPTY. "
                                               + "Please have the chat verify that the game has been set for this stream. "
                                               + $"If the error persists, please have @{_botConfig.Broadcaster.ToLower()} retype the game in their Twitch Live Dashboard. "
                                               + "If this error shows up again and your chat can see the game set for the stream, please contact my master with !support in this chat");
                }

                // Grab game id in order to find party member
                TwitchGameCategory game = await _gameDirectory.GetGameIdAsync(TwitchStreamStatus.CurrentCategory);

                /* Load/create settings and start the queue for the boss fight */
                await _bossFightInstance.LoadSettings(_broadcasterInstance.DatabaseId, game?.Id, _botConfig.TwitchBotApiLink);

                _bossFight.Start(_irc, _broadcasterInstance.DatabaseId);

                /* Ping to twitch server to prevent auto-disconnect */
                PingSender ping = new PingSender(_irc);
                ping.Start();

                /* Send reminders of certain events */
                ChatReminder chatReminder = new ChatReminder(_irc, _broadcasterInstance.DatabaseId, _botConfig.TwitchBotApiLink, _twitchInfo, _gameDirectory);
                chatReminder.Start();

                /* Load in Twitch users that have bot moderation privileges (separate from channel moderators) */
                await _botModeratorInstance.LoadExistingModerators(_botConfig.TwitchBotApiLink, _broadcasterInstance.DatabaseId);

                /* Load in custom commands */
                await _customCommandInstance.LoadCustomCommands(_botConfig.TwitchBotApiLink, _broadcasterInstance.DatabaseId);

                /* Authenticate to Twitter if possible */
                GetTwitterAuth();

                Console.WriteLine("===== Time to get to work! =====");
                Console.WriteLine();

                /* Finished setup, time to start */
                await GetChatBoxAsync();
            }
            catch (Exception ex)
            {
                await _errHndlrInstance.LogError(ex, "TwitchBotApplication", "RunAsync()", true);
            }
        }
Exemple #6
0
        /// <summary>
        /// Updates the game being played on the Twitch channel
        /// </summary>
        /// <param name="chatter"></param>
        private async Task <DateTime> UpdateGameAsync(TwitchChatter chatter)
        {
            try
            {
                // Get game from command parameter
                string gameTitle = chatter.Message.Substring(chatter.Message.IndexOf(" ") + 1);

                // Send HTTP method PUT to base URI in order to change the game
                RestClient  client  = new RestClient("https://api.twitch.tv/kraken/channels/" + _broadcasterInstance.TwitchId);
                RestRequest request = new RestRequest(Method.PUT);
                request.AddHeader("Cache-Control", "no-cache");
                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("Authorization", "OAuth " + _botConfig.TwitchAccessToken);
                request.AddHeader("Accept", "application/vnd.twitchtv.v5+json");
                request.AddHeader("Client-ID", _botConfig.TwitchClientId);
                request.AddParameter("application/json", "{\"channel\":{\"game\":\"" + gameTitle + "\"}}",
                                     ParameterType.RequestBody);

                IRestResponse response = null;
                try
                {
                    response = await client.ExecuteAsync <Task>(request);

                    string statResponse = response.StatusCode.ToString();
                    if (statResponse.Contains("OK"))
                    {
                        _irc.SendPublicChatMessage($"Twitch channel game status updated to \"{gameTitle}\"");

                        await ChatReminder.RefreshRemindersAsync();

                        await _customCommandInstance.LoadCustomCommands(_botConfig.TwitchBotApiLink, _broadcasterInstance.DatabaseId);

                        _irc.SendPublicChatMessage($"Your commands have been refreshed @{chatter.DisplayName}");

                        // Grab game id in order to find party member
                        TwitchGameCategory game = await _gameDirectory.GetGameIdAsync(gameTitle);

                        // During refresh, make sure no fighters can join
                        _bossFightSettingsInstance.RefreshBossFight = true;
                        await _bossFightSettingsInstance.LoadSettings(_broadcasterInstance.DatabaseId, game?.Id, _botConfig.TwitchBotApiLink);

                        _bossFightSettingsInstance.RefreshBossFight = false;
                    }
                    else
                    {
                        Console.WriteLine(response.Content);
                    }
                }
                catch (WebException ex)
                {
                    if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.BadRequest)
                    {
                        Console.WriteLine("Error 400 detected!!");
                    }
                    response = (IRestResponse)ex.Response;
                    Console.WriteLine("Error: " + response);
                }
            }
            catch (Exception ex)
            {
                await _errHndlrInstance.LogError(ex, "TwitchChannelFeature", "UpdateGame(TwitchChatter)", false, "!updategame");
            }

            return(DateTime.Now);
        }
        /// <summary>
        /// Request party member if game and character exists in party up system
        /// </summary>
        /// <param name="chatter">User that sent the message</param>
        private async Task <DateTime> PartyUpAsync(TwitchChatter chatter)
        {
            try
            {
                int inputIndex = chatter.Message.IndexOf(" ") + 1;

                // check if user entered something
                if (chatter.Message.Length < inputIndex)
                {
                    _irc.SendPublicChatMessage($"Please enter a party member @{chatter.DisplayName}");
                    return(DateTime.Now);
                }

                // get current game info
                ChannelJSON json = await _twitchInfo.GetBroadcasterChannelByIdAsync();

                string             gameTitle       = json.Game;
                string             partyMemberName = chatter.Message.Substring(inputIndex);
                TwitchGameCategory game            = await _gameDirectory.GetGameIdAsync(gameTitle);

                // attempt to add requested party member into the queue
                if (string.IsNullOrEmpty(gameTitle))
                {
                    _irc.SendPublicChatMessage("I cannot see the name of the game. It's currently set to either NULL or EMPTY. "
                                               + "Please have the chat verify that the game has been set for this stream. "
                                               + $"If the error persists, please have @{_botConfig.Broadcaster.ToLower()} retype the game in their Twitch Live Dashboard. "
                                               + "If this error shows up again and your chat can see the game set for the stream, please contact my master with !support in this chat");
                    return(DateTime.Now);
                }
                else if (game == null || game.Id == 0)
                {
                    _irc.SendPublicChatMessage("This game is not part of the \"Party Up\" system");
                    return(DateTime.Now);
                }

                PartyUp partyMember = await _partyUp.GetPartyMemberAsync(partyMemberName, game.Id, _broadcasterInstance.DatabaseId);

                if (partyMember == null)
                {
                    _irc.SendPublicChatMessage($"I couldn't find the requested party member \"{partyMemberName}\" @{chatter.DisplayName}. "
                                               + "Please check with the broadcaster for possible spelling errors");
                    return(DateTime.Now);
                }

                if (await _partyUp.HasUserAlreadyRequestedAsync(chatter.DisplayName, game.Id, _broadcasterInstance.DatabaseId))
                {
                    _irc.SendPublicChatMessage($"You have already requested a party member. "
                                               + $"Please wait until your request has been completed @{chatter.DisplayName}");
                    return(DateTime.Now);
                }

                await _partyUp.AddRequestedPartyMemberAsync(chatter.DisplayName, partyMember.Id);

                _irc.SendPublicChatMessage($"@{chatter.DisplayName}: {partyMemberName} has been added to the party queue");
            }
            catch (Exception ex)
            {
                await _errHndlrInstance.LogError(ex, "PartyUpFeature", "PartyUp(TwitchChatter)", false, "!partyup", chatter.Message);
            }

            return(DateTime.Now);
        }