jammerware / margiebot

MargieBot is a .NET library designed to make building bots for Slack fast, easy, and fun.
MIT License
122 stars 42 forks source link

Bot not receiving OnMessage events for direct messages without @mention? #15

Closed roschler closed 8 years ago

roschler commented 8 years ago

Thanks a ton for creating Margiebot. It's very easy to use and extend.

I have my bot up and running. If I @mention it, it works fine and I receive a message in the WebSocket.OnMessage() event handler. However, when I direct message the bot, I still have to @mention it to get a response. Otherwise, nothing happens. How can I fix this?

roschler commented 8 years ago

Found the problem. I've been testing via triggering the responder that is added "ad hoc" at the end of the GetResponders() method. Here's the code for it. As you can see, the "ad hoc" bot only responds if the bot is mentioned:

            responders.Add(_Margie.CreateResponder(
            (ResponseContext context) =>
            {
                return
                    // ROS: Is this bot mentioned in the message?
                    context.Message.MentionsBot &&
                    // ROS: Have I not responded yet to this message?
                    !context.BotHasResponded &&
                    // ROS: Does the message match any of our trigger phrases?
                    Regex.IsMatch(context.Message.Text, @"\b(hi|hey|hello|what's up|what's happening)\b", RegexOptions.IgnoreCase) &&
                    // ROS: Is the message NOT from us?
                    context.Message.User.ID != context.BotUserID &&
                    // ROS: Is the message NOT from Slack Bot?
                    !context.Message.User.IsSlackbot;
            },
            (ResponseContext context) =>
            {
                return context.Get<Phrasebook>().GetQuery();
            }
        ));

To see an example of a CanRespond() method that responds either to a direct message OR a bot mention, you can look at the CanRespond() method for the WhatsNewResponder, shown below:

    public bool CanRespond(ResponseContext context)
    {
        return (
                context.Message.MentionsBot 
                    || 
                context.Message.ChatHub.Type == SlackChatHubType.DM) 
                    && 
                Regex.IsMatch(context.Message.Text, @"\b(what's new)|(whats new)\b", RegexOptions.IgnoreCase);
    }

I'm finding the Margiebot code to be very well structured and approachable. Just learning the ropes at the moment.