Esempio n. 1
0
    void OnChatCommandReceived(TwitchChatCommand chatCommand)
    {
        if (chatCommand.Command == RESET_COMMAND || chatCommand.Command == RESET_COMMAND2)
        {
            if (_gameState != EGameState.Playing)
            {
                Restart();
                return;
            }
        }

        string parameterX = chatCommand.Parameters[0];
        string parameterY = chatCommand.Parameters[1];

        int x = Int32.Parse(parameterX) - 1;
        int y = char.ToUpper(parameterY.ToCharArray()[0]) - 64 - 1;

        if (x < GridSizeX && x >= 0 && y < GridSizeY && y >= 0)
        {
            if (chatCommand.Command == CHECK_COMMAND || chatCommand.Command == CHECK_COMMAND2)
            {
                OnTileClick(_tiles[x, y]);
                lastUserToMakeCommand = chatCommand.User.Username;
            }

            if (chatCommand.Command == FLAG_COMMAND || chatCommand.Command == FLAG_COMMAND2)
            {
                OnTileRightClick(_tiles[x, y]);
                lastUserToMakeCommand = chatCommand.User.Username;
            }
        }
    }
Esempio n. 2
0
        private T ParsePayload <T>(TwitchChatCommand command) where T : TwitchCommandPayload
        {
            try
            {
                T    template     = Activator.CreateInstance <T>();
                Type templateType = template.GetType();

                templateType.BaseType.GetProperty("Command", BindingFlags.Public | BindingFlags.Instance).SetValue(template, command);

                HashSet <TwitchCommandPropertyAttribute> requiredProperties = new HashSet <TwitchCommandPropertyAttribute>();

                TwitchCommandPropertyAttribute[] attributes = (TwitchCommandPropertyAttribute[])templateType.GetCustomAttributes(typeof(TwitchCommandPropertyAttribute), true);
                foreach (TwitchCommandPropertyAttribute attribute in attributes)
                {
                    if (attribute.Required)
                    {
                        requiredProperties.Add(attribute);
                    }
                }

                PropertyInfo[] properties = template.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                foreach (PropertyInfo property in properties)
                {
                    if (property.GetCustomAttribute(typeof(TwitchCommandPropertyAttribute), true) is TwitchCommandPropertyAttribute attribute)
                    {
                        if (command.Parameters.Length <= attribute.Position)
                        {
                            Logger.Error($"{nameof(T)} command requires the {property.Name} argument.");
                            return(default);
 private Task Run()
 {
     return(Task.Run(() => {
         TwitchChatCommand command;
         Task task;
         StringBuilder builder;
         List <string> commandList;
         string commandName;
         foreach (var message in queue.GetConsumingEnumerable())
         {
             command = new TwitchChatCommand(message);
             var paramCount = command.HasParameters ? command.Parameters.Count : 0;
             _logger.LogInformation($"Command '{command.Command}' parsed with {paramCount} parameters.");
             task = NotifyCommandObservers(command);
             if (CommandRegex.IsMatch(command.Command))
             {
                 builder = new StringBuilder();
                 builder.Append($"@{command.Message.TwitchUser.DisplayName} my available commands are ");
                 commandList = new List <string>();
                 foreach (var observer in _observers)
                 {
                     commandName = observer.GetPrimaryCommand(command);
                     if (!string.IsNullOrWhiteSpace(commandName))
                     {
                         commandList.Add(commandName);
                     }
                 }
                 builder.Append(string.Join(" ", commandList.OrderBy(q => q).ToArray()));
                 task = _client.SendPublicChatMessageAsync(builder.ToString(), command.Message.IrcChannel);
             }
         }
     }));
 }
    private void CommandReceived(TwitchChatCommand _chatCommand)
    {
        if (!bool_gameStarted)
        {
            SendChatMessage($"{_chatCommand.User.DisplayName}, das Spiel hat noch nicht begonnen!");
            return;
        }

        if (!Enum.TryParse(_chatCommand.Command.Remove(0, 1), true, out currentCommandType))
        {
            SendChatMessage($"{_chatCommand.User.DisplayName}, dein Befehl wurde nicht erkannt: (Befehl: { _chatCommand.Command })");
            return;
        }

        switch (currentCommandType)
        {
        case CommandType.Einheit:
            try
            {
                onChangeUnitCommandReceived?.Invoke(_chatCommand.User, (UnitType)Enum.Parse(typeof(UnitType), _chatCommand.Parameters[0], true));
            }
            catch (Exception)
            {
                SendChatMessage($"{_chatCommand.User.DisplayName}, der Parameter wurde nicht erkannt: (Parameter: { _chatCommand.Parameters[0] })");
                throw;
            }
            break;

        case CommandType.Kamera:
            try
            {
                onVoteCameraPosCommandReceived?.Invoke(_chatCommand.User, (CameraPositions)Enum.Parse(typeof(CameraPositions), _chatCommand.Parameters[0], true));
            }
            catch (Exception)
            {
                SendChatMessage($"{_chatCommand.User.DisplayName}, der Parameter wurde nicht erkannt: (Parameter: { _chatCommand.Parameters[0] })");
                throw;
            }
            break;

        case CommandType.Team:
            try
            {
                onChooseTeamCommandReceived?.Invoke(_chatCommand.User, (Teams)Enum.Parse(typeof(Teams), _chatCommand.Parameters[0], true));
            }
            catch (Exception)
            {
                SendChatMessage($"{_chatCommand.User.DisplayName}, der Parameter wurde nicht erkannt: (Parameter: { _chatCommand.Parameters[0] })");
                throw;
            }
            break;

        case CommandType.Hilfe:
            SendChatMessage("Mögliche Commands: \"$Hilfe\" zeigt alle Commands.");
            SendChatMessage("\"$Team Blau/Rot\" trägt einen in das jeweile Team Blau oder Rot ein insofern noch kein Team gewählt und Platz ist.");
            SendChatMessage("\"Einheit Heiler/Tank/Bogenschütze\" ändert die gewählte Unit ab dem nächsten Spawn insofern einem Team beigetreten wurde.");
            SendChatMessage("\"Kamera BlauesTor/RotesTor/Mitte/Übersicht\" votet für die nächste Kamerawinkel Änderung, kann gespamt werden, auch als nicht Spieler.");
            break;
        }
    }
Esempio n. 5
0
        private void OnChatCommandReceived(TwitchChatCommand chatCommand)
        {
            if (chatCommand.Command == START_COMMAND)
            {
                if (MatchManager.instance.HasStarted)
                {
                    return;
                }
                MatchManager.instance.Begin();
                return;
            }

            if (!MatchManager.instance.HasStarted)
            {
                return;
            }

            if (chatCommand.Command == MOVE_COMMAND)
            {
                string parameter = chatCommand.Parameters[0];
                if (directions.ContainsKey(parameter))
                {
                    Vector3 direction = directions[parameter];
                    GameUI.instance.UpdateUser(chatCommand.User);
                    MatchManager.instance.Move(direction);
                }
                return;
            }

            Debug.Log($"Unknown Command received: {chatCommand.Command}");
        }
Esempio n. 6
0
 public string GetPrimaryCommand(TwitchChatCommand Command)
 {
     if (Command.Message.ChannelOwner.UserName.ToLower() == _config.SoundsChannel.ToLower())
     {
         return(PrimaryCommand);
     }
     return(String.Empty);
 }
Esempio n. 7
0
        private void Initialize()
        {
            string                  payload = $"@badge-info=subscriber/1;badges=moderator/1,subscriber/0;client-nonce=60576a3018294221da54321a7397db58;color=;display-name=francoe1;emotes=;first-msg=0;flags=;id=9e4e255d-3c8d-4cdb-88ca-62ab7a3c37a9;mod=1;room-id=130747120;subscriber=1;tmi-sent-ts=1635094303777;turbo=0;user-id=147383910;user-type=mod :[email protected] PRIVMSG #rhomita :{COMMAND_NAME} {COMMAND_PARAMS}";
            TwitchInputLine         command = new TwitchInputLine(payload, COMMAND_PREFIX);
            TwitchChatMessageParser message = new TwitchChatMessageParser(command);

            _command = new TwitchChatCommand(message.User, message.Sent, message.Bits, message.Id);
            _handler = new TwitchCommandHandler(COMMAND_PREFIX);
        }
Esempio n. 8
0
    public void ReadMessageChatCommandTest()
    {
        const string            COMMAND     = "!start";
        string                  PAYLOAD     = $"@badge-info=subscriber/1;badges=moderator/1,subscriber/0;client-nonce=60576a3018294221da54321a7397db58;color=;display-name=francoe1;emotes=;first-msg=0;flags=;id=9e4e255d-3c8d-4cdb-88ca-62ab7a3c37a9;mod=1;room-id=130747120;subscriber=1;tmi-sent-ts=1635094303777;turbo=0;user-id=147383910;user-type=mod :[email protected] PRIVMSG #rhomita :{COMMAND}";
        TwitchInputLine         command     = new TwitchInputLine(PAYLOAD, COMMAND_PREFIX);
        TwitchChatMessageParser message     = new TwitchChatMessageParser(command);
        TwitchChatCommand       chatCommand = new TwitchChatCommand(message.User, message.Sent, message.Bits, message.Id);

        Assert.IsTrue(chatCommand.Command == COMMAND);
    }
Esempio n. 9
0
        private bool TryParseParameter(TwitchChatCommand command, out int numberOfDice, out int maxDiceSides, out int offset)
        {
            offset       = 0;
            numberOfDice = 0;
            maxDiceSides = 0;
            // match !roll
            if (!command.HasParameters)
            {
                numberOfDice = 1;
                maxDiceSides = 6;
                return(true);
            }

            var Parameter = command.Parameters[0];
            // match !roll 3d6
            var match = NDMPattern.Match(Parameter);

            if (match.Success && int.TryParse(match.Groups[1].Value, out numberOfDice) && int.TryParse(match.Groups[2].Value, out maxDiceSides) && numberOfDice > 0 && maxDiceSides > 0)
            {
                if (match.Groups[3].Success && !int.TryParse(match.Groups[3].Value, out offset))
                {
                    return(false);
                }
                return(true);
            }

            // match !roll d6
            match = DMPattern.Match(Parameter);
            if (match.Success && int.TryParse(match.Groups[1].Value, out maxDiceSides) && maxDiceSides > 0)
            {
                numberOfDice = 1;
                if (match.Groups[2].Success && !int.TryParse(match.Groups[2].Value, out offset))
                {
                    return(false);
                }
                return(true);
            }

            // match !roll 6
            match = MPattern.Match(Parameter);
            if (match.Success && int.TryParse(match.Groups[1].Value, out maxDiceSides) && maxDiceSides > 0)
            {
                numberOfDice = 1;
                if (match.Groups[2].Success && !int.TryParse(match.Groups[2].Value, out offset))
                {
                    return(false);
                }
                return(true);
            }

            numberOfDice = 0;
            maxDiceSides = 0;
            return(false);
        }
Esempio n. 10
0
        public bool ProcessCommand(TwitchChatCommand chatCommand)
        {
            if (!_registers.ContainsKey(chatCommand.Command))
            {
                Logger.Warning($"The command {chatCommand.Command} is not registered.");
                return(false);
            }

            _registers[chatCommand.Command](chatCommand);
            Logger.Info($"Process Command:{chatCommand.Command}");
            return(true);
        }
Esempio n. 11
0
 private async Task NotifyCommandObservers(TwitchChatCommand command)
 {
     await Task.Run(() =>
     {
         foreach (var observer in _observers)
         {
             if (observer.IsCommandSupported(command.Command))
             {
                 observer.Update(command);
             }
         }
     });
 }
Esempio n. 12
0
    void ShowCommand(TwitchChatCommand chatCommand)
    {
        TwitchConnectData a          = ScriptableObject.CreateInstance <TwitchConnectData>();
        string            parameters = string.Join(" - ", chatCommand.Parameters);
        string            message    =
            $"Command: '{chatCommand.Command}' - Username: {chatCommand.User.DisplayName} - Bits: {chatCommand.Bits} - Sub: {chatCommand.User.IsSub} - Parameters: {parameters}";

        TwitchChatClient.instance.SendChatMessage($"Hello {chatCommand.User.DisplayName}! I received your message.");
        TwitchChatClient.instance.SendChatMessage(
            $"Hello {chatCommand.User.DisplayName}! This message will be sent in 5 seconds.", 5);

        AddText(message);
    }
Esempio n. 13
0
        private void ReadChatMessage(string message)
        {
            string displayName = _messageRegexp.Match(message).Groups[1].Value;
            bool   isSub       = _messageRegexp.Match(message).Groups[2].Value == "1";
            string idUser      = _messageRegexp.Match(message).Groups[3].Value;
            string username    = _messageRegexp.Match(message).Groups[4].Value;
            string messageSent = _messageRegexp.Match(message).Groups[5].Value;
            int    bits        = 0;

            TwitchUser twitchUser = TwitchUserManager.AddUser(username);

            twitchUser.SetData(idUser, displayName, isSub);

            if (messageSent.Length == 0)
            {
                return;
            }

            MatchCollection matches = cheerRegexp.Matches(messageSent);

            foreach (Match match in matches)
            {
                if (match.Groups.Count != 2)
                {
                    continue;                          // First group is 'cheerXX', second group is XX.
                }
                string value = match.Groups[1].Value;
                if (!Int32.TryParse(value, out int bitsAmount))
                {
                    continue;
                }
                bits += bitsAmount;
            }

            if (messageSent[0] == commandPrefix[0])
            {
                TwitchChatCommand chatCommand = new TwitchChatCommand(twitchUser, messageSent, bits);
                onChatCommandReceived?.Invoke(chatCommand);
            }
            else
            {
                TwitchChatMessage chatMessage = new TwitchChatMessage(twitchUser, messageSent, bits);
                onChatMessageReceived?.Invoke(chatMessage);
            }
        }
Esempio n. 14
0
    private void ShowCommand(TwitchChatCommand chatCommand)
    {
        TwitchConnectData a          = ScriptableObject.CreateInstance <TwitchConnectData>();
        string            parameters = string.Join(" - ", chatCommand.Parameters);
        string            message    =
            $"Command: '{chatCommand.Command}' - " +
            $"Username: {chatCommand.User.DisplayName} - " +
            $"Bits: {chatCommand.Bits} - " +
            $"Sub: {chatCommand.User.IsSub} - " +
            $"Badges count: {chatCommand.User.Badges.Count} - " +
            $"Badges: {string.Join("/", chatCommand.User.Badges.Select(badge => badge.Name))} - " +
            $"Badge versions: {string.Join("/", chatCommand.User.Badges.Select(badge => badge.Version))} - " +
            $"Parameters: {parameters}";

        TwitchChatClient.instance.SendChatMessage($"Hello {chatCommand.User.DisplayName}! I received your message.");
        TwitchChatClient.instance.SendChatMessage(
            $"Hello {chatCommand.User.DisplayName}! This message will be sent in 5 seconds.", 5);

        AddText(message);
    }
        private void ReadChatLine()
        {
            if (_twitchClient.Available <= 0)
            {
                return;
            }
            string          source    = _reader.ReadLine();
            TwitchInputLine inputLine = new TwitchInputLine(source, _commandPrefix);

            onTwitchInputLine?.Invoke(inputLine);

            switch (inputLine.Type)
            {
            case TwitchInputType.LOGIN:
                if (inputLine.IsValidLogin(_twitchConnectConfig))
                {
                    _isAuthenticated = true;
                    _onSuccess?.Invoke();
                    _onSuccess = null;
                    Debug.Log("<color=green>¡Success Twitch Connection!</color>");
                }
                else
                {
                    _onError?.Invoke(LOGIN_WRONG_USERNAME);
                    _onError = null;
                    Debug.Log("<color=red>¡Error Twitch Connection: Token is valid but it belongs to another user!</color>");
                }
                break;

            case TwitchInputType.NOTICE:
                string lineMessage = inputLine.Message;
                string userErrorMessage;
                string errorMessage;
                if (lineMessage.Contains(TwitchChatRegex.LOGIN_FAILED_MESSAGE))
                {
                    userErrorMessage = LOGIN_FAILED_MESSAGE;
                    errorMessage     = LOGIN_FAILED_MESSAGE;
                }
                else if (lineMessage.Contains(TwitchChatRegex.LOGIN_WRONG_REQUEST_MESSAGE))
                {
                    userErrorMessage = LOGIN_WRONG_REQUEST_MESSAGE;
                    errorMessage     = LOGIN_WRONG_REQUEST_MESSAGE;
                }
                else
                {
                    userErrorMessage = LOGIN_UNEXPECTED_ERROR_MESSAGE;
                    errorMessage     = lineMessage;
                }
                _onError?.Invoke(userErrorMessage);
                _onError = null;
                Debug.Log($"<color=red>Twitch connection error: {errorMessage}</color>");
                break;

            case TwitchInputType.PING:
                _writer.WriteLine(COMMAND_PONG);
                _writer.Flush();
                break;

            case TwitchInputType.MESSAGE_COMMAND:
            {
                TwitchChatMessageParser payload     = new TwitchChatMessageParser(inputLine);
                TwitchChatCommand       chatCommand = new TwitchChatCommand(payload.User, payload.Sent, payload.Bits, payload.Id);
                onChatCommandReceived?.Invoke(chatCommand);
            }
            break;

            case TwitchInputType.MESSAGE_CHAT:
            {
                TwitchChatMessageParser payload     = new TwitchChatMessageParser(inputLine);
                TwitchChatMessage       chatMessage = new TwitchChatMessage(payload.User, payload.Sent, payload.Bits, payload.Id);
                onChatMessageReceived?.Invoke(chatMessage);
            }
            break;

            case TwitchInputType.MESSAGE_REWARD:
            {
                TwitchChatRewardParser payload    = new TwitchChatRewardParser(inputLine);
                TwitchChatReward       chatReward = new TwitchChatReward(payload.User, payload.Sent, payload.Id);
                onChatRewardReceived?.Invoke(chatReward);
            }
            break;

            case TwitchInputType.JOIN: TwitchUserManager.AddUser(inputLine.UserName); break;

            case TwitchInputType.PART: TwitchUserManager.RemoveUser(inputLine.UserName); break;
            }
        }
Esempio n. 16
0
 public async Task Update(TwitchChatCommand Command)
 {
     await Task.Run(() => { queue.Add(Command); });
 }
Esempio n. 17
0
 public string GetPrimaryCommand(TwitchChatCommand Command)
 {
     return(PrimaryCommand);
 }