예제 #1
0
        void AddCommand(IChatWriter chat, ChatCommandData data)
        {
            if (data.Arguments.Count < 3)
            {
                chat.SendMessage($"Add command. Usage: !{data.CommandAlias} add <command> !<optional subcommand> <text>.");
                return;
            }

            string command    = data.Arguments[1].ToLowerInvariant();
            string subCommand = data.Arguments[2].ToLowerInvariant();
            string text       = data.Arguments.ValueOrDefault(3)?.ToLowerInvariant();

            bool isSubCommand = text != null && subCommand.StartsWith("!");

            text = string.Join(" ", data.Arguments.Skip(isSubCommand ? 3 : 2));

            // If only 2 arguments are passed to this subcommand.
            if (isSubCommand)
            {
                subCommand = subCommand.TrimStart('!');
                CommandCollection.AddSubCommand(command, subCommand, text);
                chat.SendMessage($"Added sub command '{command} {subCommand}'.");
            }
            else
            {
                CommandCollection.AddCommand(command, text);
                chat.SendMessage($"Added command '{command}'.");
            }
        }
예제 #2
0
        public async Task Process(IChatWriter chat, ChatCommandData data)
        {
            if (chat == null)
            {
                throw new ArgumentNullException(nameof(chat));
            }
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            if (CommandCollection == null)
            {
                chat.SendMessage("Error: Unable to operate on custom commands.");
                return;
            }

            Console.WriteLine($"Arguments: {string.Join(", ", data.Arguments)}.");

            string subCommand = data.Arguments.ValueOrDefault(0)?.ToLowerInvariant();

            if (subCommand == null || !subCommands.ContainsKey(subCommand))
            {
                string commands = string.Join("|", subCommands.Keys);
                chat.SendMessage($"Usage: !{data.CommandAlias} <{commands}>. Was; {subCommand}");
            }
            // Execute subcommand if found.
            else
            {
                subCommands[subCommand](chat, data);
            }

            await FinalizeAsync;
        }
예제 #3
0
        public async Task CustomChatCommandCanAddSubCommands()
        {
            var data = new ChatCommandData("command", new[] { "add", "test", "!sub", "test_message" });
            await command.Process(chat, data);

            Assert.That(collection.ContainsSubCommand("test", "sub"), Is.True);
            Assert.That(collection.Commands["test"].Subcommands["sub"], Is.EqualTo("test_message"));
        }
예제 #4
0
        public async Task CustomChatCommandCanRemoveCommands()
        {
            collection.AddCommand("test", "sub");
            Assert.That(collection.ContainsCommand("test"), Is.True);
            var data = new ChatCommandData("command", new[] { "remove", "test" });
            await command.Process(chat, data);

            Assert.That(collection.ContainsCommand("test"), Is.False);
        }
예제 #5
0
        public async Task CustomChatCommandCanAddCommands()
        {
            var data = new ChatCommandData("command", new[] { "add", "test", "test_message" });
            await command.Process(chat, data);

            Assert.That(chat.PreviousMessage, Contains.Substring("Added"));
            Assert.That(collection.ContainsCommand("test"), Is.True);
            Assert.That(collection.Commands["test"].Text, Is.EqualTo("test_message"));
        }
예제 #6
0
        public async Task CustomChatCommandPrintsUsageWithInvalidSubCommand()
        {
            var data = new ChatCommandData("command", new[] { "invalid" });
            await command.Process(chat, data);

            Assert.That(chat.PreviousMessage, Contains.Substring("add"));
            Assert.That(chat.PreviousMessage, Contains.Substring("remove"));
            Assert.That(chat.PreviousMessage, Contains.Substring("list"));
        }
예제 #7
0
        public async Task CustomChatCommandPrintsUsageWithoutArguments()
        {
            var data = new ChatCommandData("command", new string[] { });
            await command.Process(chat, data);

            Assert.That(chat.PreviousMessage, Contains.Substring("add"));
            Assert.That(chat.PreviousMessage, Contains.Substring("remove"));
            Assert.That(chat.PreviousMessage, Contains.Substring("list"));
        }
예제 #8
0
        public async Task CustomChatCommandPrintsErrorWithoutCommandCollection()
        {
            var data = new ChatCommandData("command", new string[] { });

            command.CommandCollection = null;
            await command.Process(chat, data);

            Assert.That(chat.PreviousMessage, Contains.Substring("Error"));
        }
예제 #9
0
        public async Task Process(IChatWriter chat, ChatCommandData data)
        {
            if (data.Arguments.Count == 0)
            {
                chat.SendMessage($"Usage: !{data.CommandAlias} [item]. Possible values: helm, armor, weapon, shield, weapon2, shield2, belt, gloves, boots, ring(s), and amulet.");
                return;
            }

            // Resolve valid item names.
            string itemName = data.Arguments[0]?.ToLowerInvariant();

            ItemRequest.Slot?itemSlot = ResolveItemSlot(itemName);
            if (!itemSlot.HasValue)
            {
                chat.SendMessage("Invalid item name.");
                return;
            }

            // Attempt to get a response.
            ItemResponse response;

            try { response = await QueryItem(itemSlot.Value); }
            catch (TimeoutException)
            {
                chat.SendMessage("Failed to get a response from item server!");
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception: {0}", e);
                throw;
            }

            if (!response.IsValid)
            {
                chat.SendMessage("Invalid request!");
            }
            else if (!response.Success)
            {
                chat.SendMessage($"{itemName.CapitalizeFirst()} not equipped!");
            }
            else if (response.Items.Count > 0)
            {
                foreach (var item in response.Items)
                {
                    var itemBuilder = new StringBuilder(item.ItemName);
                    if (item.Properties.Count > 0)
                    {
                        itemBuilder.Append(": ");
                        itemBuilder.Append(string.Join(", ", item.Properties));
                    }

                    chat.SendMessage(itemBuilder.ToString().Replace("\n", ""));
                }
            }
        }
예제 #10
0
        public async Task CustomChatCommandCanListCommands()
        {
            var data = new ChatCommandData("command", new[] { "list" });
            await command.Process(chat, data);

            Assert.That(chat.PreviousMessage, Contains.Substring("No custom"));
            collection.AddCommand("command_one", "test");
            collection.AddCommand("command_two", "data");
            await command.Process(chat, data);

            Assert.That(chat.PreviousMessage, Contains.Substring("command_one"));
            Assert.That(chat.PreviousMessage, Contains.Substring("command_two"));
        }
예제 #11
0
        void ListCommand(IChatWriter chat, ChatCommandData data)
        {
            if (CommandCollection == null)
            {
                chat.SendMessage("Error: Unable to operate on custom commands.");
                return;
            }

            if (CommandCollection.Commands.Count == 0)
            {
                chat.SendMessage("No custom commands added.");
                return;
            }

            string commands = string.Join(", ", CommandCollection.Commands.Keys);

            chat.SendMessage($"Available commands: {commands}.");
        }
예제 #12
0
        void RemoveCommand(IChatWriter chat, ChatCommandData data)
        {
            if (data.Arguments.Count < 2)
            {
                chat.SendMessage($"Remove command. Usage: !{data.CommandAlias} remove <command> <optional subcommand>.");
                return;
            }

            string command    = data.Arguments[1].ToLowerInvariant();
            string subCommand = data.Arguments.ValueOrDefault(2)?.ToLowerInvariant();

            if (subCommand == null)
            {
                CommandCollection.RemoveCommand(command);
                chat.SendMessage($"Removed command '{command}'.");
            }
            else
            {
                subCommand = subCommand.TrimStart('!');
                CommandCollection.RemoveSubCommand(command, subCommand);
                chat.SendMessage($"Removed sub command '{command} {subCommand}'.");
            }
        }
예제 #13
0
        public async Task Process(IChatWriter chat, ChatCommandData data)
        {
            if (data.Arguments.Count == 0)
            {
                chat.SendMessage($"Usage !{data.CommandAlias} [class]. Values: amazon, assassin, barbarian, druid, necromancer, paladin, sorceress, and some abbreviations.");
                return;
            }

            string characterClass = DiabloClassHelper.ResolveClassName(data.Arguments[0]);

            if (string.IsNullOrEmpty(characterClass))
            {
                chat.SendMessage($"Invalid class name.");
                return;
            }

            // Get the current leaderboard for the specified class.
            var client      = new SpeedrunClient();
            var leaderboard = await client.QueryLeaderboardAsync();

            IList <GameRecord> records = leaderboard.ValueOrDefault(characterClass);

            // Format records for printing.
            string message = string.Join(", ",
                                         from record in records
                                         let time = record.Time.ToString(@"hh\:mm\:ss")
                                                    select $"{record.Category} in {time} [{record.User}]");

            if (records.Count == 0)
            {
                message = "No records available.";
            }

            message = $"{ characterClass.CapitalizeFirst() } records: {message}";
            chat.SendMessage(message);
        }
예제 #14
0
        public void CustomChatCommandThrowsWithoutChat()
        {
            var data = new ChatCommandData("command", new string[] { });

            Assert.That(() => command.Process(null, data), Throws.ArgumentNullException);
        }
예제 #15
0
        void HandleCommand(TwitchChatMessage message)
        {
            string text = message.Text.Trim();

            if (string.IsNullOrEmpty(text))
            {
                return;
            }
            if (!text.StartsWith("!"))
            {
                return;
            }

            // Get command name.
            string command   = "";
            int    position  = 1;
            int    nextSpace = text.IndexOf(' ', position);

            if (nextSpace < 0)
            {
                command = text.Substring(position);
            }
            else
            {
                command = text.Substring(position, nextSpace - position);
            }
            if (string.IsNullOrEmpty(command))
            {
                return;
            }
            command = command.ToLowerInvariant();

            // Get command arguments.
            List <string> arguments = new List <string>();

            if (nextSpace >= 0)
            {
                string argumentsText = text.Substring(nextSpace).Trim();
                if (!string.IsNullOrEmpty(argumentsText))
                {
                    arguments = argumentsText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                }
            }

            ChatCommandData commandData = new ChatCommandData(command, arguments);

            IChatCommand chatCommand;

            if (chatCommands.TryGetValue(command, out chatCommand))
            {
                // Restrict moderator commands.
                if (chatCommand.IsModeratorCommand && !message.User.IsModerator)
                {
                    return;
                }

                // Found the chat command, all valid command have a cooldown.
                if (!HandleCommandCooldown(message))
                {
                    return;
                }

                // Do invidual chat command handling.
                var chatWriter = new TwitchChatWriter(client.Connection);
                chatCommand.Process(chatWriter, commandData);
            }
            else if (commandCollection.ContainsCommand(command))
            {
                // Found the chat command, all valid command have a cooldown.
                if (!HandleCommandCooldown(message))
                {
                    return;
                }

                // Fall back to custom commands if no hard-coded commands are found.
                if (arguments.Count > 0 && commandCollection.ContainsSubCommand(command, arguments[0]))
                {
                    client.Connection.Send(commandCollection.Commands[command].Subcommands[arguments[0]]);
                }
                else
                {
                    client.Connection.Send(commandCollection.Commands[command].Text);
                }
            }
        }