IRC聊天命令解析

本文关键字:命令 聊天 IRC | 更新日期: 2023-09-27 17:58:12

固定我把代码放在这里给任何其他需要帮助解决自己问题的人(假设他们有我的问题。

FIXED CODE THAT WORKS
    public static bool CommandExists(String value)
    {
        string[] commands = File.ReadAllText("commands.txt")
                       .Split()
                       .Where(x => x.StartsWith(value))
                       .Distinct()
                       .ToArray();
        return commands.Contains(value);
    }
    public static string CommandParse(String value, string nick)
    {
        IEnumerable<string> lines;
        lines = File.ReadLines("commands.txt");
        IEnumerable<string> command = lines
            .Where(d => d.StartsWith(value, 
                StringComparison.CurrentCultureIgnoreCase));
        foreach (string line in command) {
            string vals = line
                .Replace("@nick", nick)
                .Replace("@upnick", nick.ToUpper())
                .Replace(value + " ", "");
            return vals;
        }
        return null;
    }

所以我试了几个小时,环顾四周,找不到任何与我想做的事情有关的东西

我正在阅读一个名为"commands.txt"的文本文件,我正在尝试解析文本。内容如下:

!help Hello, current commands are: !help, !ver
!ver Testing this

现在如果我拉

string x1 = File.ReadAllLines("commands.txt").ToString();
string[] x2 = x1.Split(' ');
string x3 = x2[0];
Console.WriteLine(x3);

我得到"索引超出数组的界限"。我不知道自己做错了什么。如果命令存在,我还试图使用"static bool"来调用,到目前为止我得到了

public static bool CommandExists(String value)
{
    if (File.ReadAllLines("commands.txt").Contains(value.ToString())) {
        return true;
    }
    else
    { 
        return false; 
    }
}

但这并不奏效。

是什么导致了该异常?

编辑:CommandParse()

    public static string CommandParse(string value, string nick)
    {
        string[] commands = File.ReadAllText("commands.txt")
               .Split()
               .Where(x => x.StartsWith("!"+value.ToLower()))
               .Distinct()
               .ToArray();
        string cmd = commands[1]
            .Replace("@nick", nick)
            .Replace("@nickup", nick.ToUpper());
        return cmd;
    }

现在我知道它返回True,我如何使它不返回True,而是返回命令本身

IRC聊天命令解析

ReadAllLines返回一个字符串数组,您使用的是ToString,而不是获取行,而是获取不包含任何while空格的字符串数组的类型名称,因此Split(' ')不会更改任何内容。如果要读取所有文本,请使用ReadAllText方法。

string x1 = File.ReadAllText("commands.txt");

您的所有命令似乎都以!开头,因此您可以将所有命令放入如下数组中:

string[] commands = File.ReadAllText("commands.txt")
                   .Split()
                   .Where(x => x.StartsWith("!"))
                   .Distinct()
                   .ToArray();

然后你的方法会像这样:

public static bool CommandExists(String value)
{
    string[] commands = File.ReadAllText("commands.txt")
                   .Split()
                   .Where(x => x.StartsWith("!"))
                   .Distinct()
                   .ToArray();
    return commands.Contains(value);
}

如果要在开始时排除!,请在Where之后添加.Select(x => x.TrimStart('!'))