I am trying to add custom middleware to detect the intent of user message in slackbot, but the middleware is triggered multiple times (usually 4 ~ 5 times) for one message.
I am sharing my controller and middleware what I am using.
This is my middleware:
import { SlackBotWorker } from "botbuilder-adapter-slack";
import { BotkitMessage } from "botkit";
import { NextFunction, Response } from "express";
import { logger } from "src/app";
import { chatCompletion } from "src/clients/openai/chat-completion";
import { OPEN_AI_INTENT_DETECTION_MESSAGE } from "./system-messages";
// Detect the intent from users' message and added intent to message object of botkit using this middleware
export const openAIIntentDetectionMiddleware = async (bot: SlackBotWorker, message: BotkitMessage, next: NextFunction) => {
try {
const userMessage = message.text ?? '';
if (userMessage !== '') {
const response = await chatCompletion({ messages: [{ role: 'system', content: OPEN_AI_INTENT_DETECTION_MESSAGE }, { role: 'user', content: userMessage }] });
const analyzedData = response ? JSON.parse(response) : { intent: 'default-fallback-intent', info: null };
logger.debug('Open AI intent detection response:', { analyzedData });
message.intent = analyzedData.intent;
message.info = analyzedData.info;
message.gptMessage = analyzedData.message;
} else {
message.intent = 'default-fallback-intent';
message.info = null;
}
} catch (error) {
// Handle any errors here, such as API request failures.
logger.error('Open AI intent detection failed:', { error })
}
next();
}
And this is my controller:
import { SlackAdapter } from 'botbuilder-adapter-slack';
import { Botkit } from 'botkit';
import { SLACK_WEBHOOK } from '../../constants';
import { logger } from '../../app';
import { openAIIntentDetectionMiddleware } from './middleware/openai-intent-detection.middleware';
export const initSlackController = (adapter: SlackAdapter): Botkit => {
const controller = new Botkit({
dialogStateProperty: `botbuilder-adapter-slack`,
adapter,
webhook_uri: SLACK_WEBHOOK,
webserver: server,
storage,
// ...other options
});
controller.middleware.receive.use(openAIIntentDetectionMiddleware);
controller.ready(async () => {
// ... my controllers
logger.info(`Slackbot Modules Loaded!`);
});
return controller;
};