Search code examples
arraysdiscordbotscontains

Discord bot on .NET, reacting on specific words


The thing is that I wanted to create a bot that would react on a specific words sending by people in discord channel chat.

    private Task CowMooeing(SocketMessage msg)
    {
        string[] mooes = {"moo", "moooooo", "moooooooooo", "mooooooooooo"};

        foreach (string moo in mooes)
        {
            if (msg.Content.Contains(moo))
                msg.Channel.SendMessageAsync("hi there, you little COWard!");
        }
    }

but. If someone send "moo, moooo, moooo" in chat - the bot would react like multiple times on that.

i tried to replace msg.Content.Contains to msg.Content.Equals(). But in that case it won't work if someone adds an additional text like: i've said "mooo!" - bot won't react on that. So I'm really stuck with that, and the only way I found to solve this problem is to duplicate mooes array in multiple time if mooes[0], if mooes[1] etc. But that's not the best way to do so.

With Regular expressions I've faced an issue where I couldn't use IsMatch or Match with msg.Content =( Help me just a little bit, please


Solution

  • How about just using the Linq Any approach as below? This will only send the one message as the Any will return true if any are found.

    private Task CowMooeing(SocketMessage msg)
    {
        string[] mooes = {"moo", "moooooo", "moooooooooo", "mooooooooooo"};
        if(mooes.Any(x => msg.Content.Contains(x))) {
             msg.Channel.SendMessageAsync("hi there, you little COWard!");
        }
    }
    

    I would also say look into regex regular expressions and they can be great for stuff like this