howdyai / botkit

Botkit is an open source developer tool for building chat bots, apps and custom integrations for major messaging platforms.
MIT License
11.39k stars 2.28k forks source link

Slack app_mention event not treated as a message #2156

Closed elisherer closed 2 years ago

elisherer commented 2 years ago

While using the app_mention event in Slack (vs using message.channel) (See reference from Slack's docs)

"message" events are treated as messages while "app_mention" are treated as events (can be listened to with controller.on('app_mention'))

Steps to reproduce:

The expected is that when mentioned the bot from any conversation it will trigger the messages API (i.e controller.hears) While in actual it doesn't.

Context:

Other information

I assume the issue is in SlackAdapter.processActivity https://github.com/howdyai/botkit/blob/93650237bd19a8cc8aac379436c30f8bb0116c14/packages/botbuilder-adapter-slack/src/slack_adapter.ts#L644 The assumption that a message must have a 'message' type event is wrong and it should be changed to the following:

    if ((event.event.type === 'message' || event.event.type === 'app_mention') && !event.event.subtype) {

I managed to make it work adding another middleware just before adding SlackMessageTypeMiddleware.

SlackAppMentionToMessageMiddleware.js

const { MiddlewareSet, ActivityTypes } = require("botbuilder");

class SlackAppMentionToMessageMiddleware extends MiddlewareSet {
  /**
   * @param context {TurnContext}
   * @param next {function(): Promise<any>}
   */
  async onTurn(context, next) {
    if (
      context.activity.type === "event" &&
      context.activity.channelData &&
      context.activity.channelData.type === "app_mention"
    ) {
      context.activity.type = ActivityTypes.Message;
      context.activity.text = context.activity.channelData.text;
    }
    await next();
  }
}

exports.SlackAppMentionToMessageMiddleware = SlackAppMentionToMessageMiddleware;

Usage

...
  adapter.use(new SlackAppMentionToMessageMiddleware());

  adapter.use(new SlackMessageTypeMiddleware());
stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

benbrown commented 2 years ago

Solving this with the middleware as you did was the correct way to do it! Thanks for documenting this for others.