Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
require('dotenv').config()
const { BotStateSet, BotFrameworkAdapter, MemoryStorage, ConversationState, UserState } = require('botbuilder');
const { MessageFactory, CardFactory } = require('botbuilder');
const { LuisRecognizer } = require('botbuilder-ai');
const restify = require('restify');
// Create server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log(`${server.name} listening to ${server.url}`);
});
const luisModel = new LuisRecognizer({
appId: process.env.LuisAppId,
subscriptionKey: process.env.LuisSubKey,
serviceEndpoint: `https://${process.env.LuisRegion}.api.cognitive.microsoft.com`
});
// Create adapter
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Add state middleware
const storage = new MemoryStorage();
const convoState = new ConversationState(storage);
const userState = new UserState(storage);
adapter.use(new BotStateSet(convoState, userState));
console.log(`${server.name} listening to ${server.url}`);
});
// Create adapter
const adapter = new BotFrameworkAdapter({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
// Create LuisRecognizers and QnAMaker
// The LUIS applications are public, meaning you can use your own subscription key to test the applications.
// For QnAMaker, users are required to create their own knowledge base.
// The exported LUIS applications and QnAMaker knowledge base can be found adjacent to this sample bot.
// The corresponding LUIS application JSON is `dispatchSample.json`
const dispatcher = new LuisRecognizer({
appId: '0b18ab4f-5c3d-4724-8b0b-191015b48ea9',
subscriptionKey: process.env.LUIS_SUBSCRIPTION_KEY,
serviceEndpoint: 'https://westus.api.cognitive.microsoft.com/',
verbose: true
});
// The corresponding LUIS application JSON is `homeautomation.json`
const homeAutomation = new LuisRecognizer({
appId: 'c6d161a5-e3e5-4982-8726-3ecec9b4ed8d',
subscriptionKey: process.env.LUIS_SUBSCRIPTION_KEY,
serviceEndpoint: 'https://westus.api.cognitive.microsoft.com/',
verbose: true
});
// The corresponding LUIS application JSON is `weather.json`
const weather = new LuisRecognizer({
public static async executeLuisQuery(logger: Logger, context: TurnContext): Promise {
const bookingDetails = new BookingDetails();
try {
const recognizer = new LuisRecognizer({
applicationId: process.env.LuisAppId,
endpoint: `https://${ process.env.LuisAPIHostName }`,
endpointKey: process.env.LuisAPIKey,
}, {}, true);
const recognizerResult = await recognizer.recognize(context);
const intent = LuisRecognizer.topIntent(recognizerResult);
bookingDetails.intent = intent;
if (intent === 'Book_flight') {
// We need to get the result from the LUIS JSON which at every level returns an array
bookingDetails.destination = LuisHelper.parseCompositeEntity(recognizerResult, 'To', 'Airport');
bookingDetails.origin = LuisHelper.parseCompositeEntity(recognizerResult, 'From', 'Airport');
constructor(conversationState, userState, botConfig) {
if (!conversationState) throw new Error('Missing parameter. conversationState is required');
if (!userState) throw new Error('Missing parameter. userState is required');
if (!botConfig) throw new Error('Missing parameter. botConfig is required');
// Add the LUIS recognizer.
const luisConfig = botConfig.findServiceByNameOrId(LUIS_CONFIGURATION);
if (!luisConfig || !luisConfig.appId) throw new Error('Missing LUIS configuration. Please follow README.MD to create required LUIS applications.\n\n');
this.luisRecognizer = new LuisRecognizer({
applicationId: luisConfig.appId,
// CAUTION: Its better to assign and use a subscription key instead of authoring key here.
endpointKey: luisConfig.authoringKey,
endpoint: luisConfig.getEndpoint()
});
// Create the property accessors for user and conversation state
this.userProfileAccessor = userState.createProperty(USER_PROFILE_PROPERTY);
this.dialogState = conversationState.createProperty(DIALOG_STATE_PROPERTY);
// Create top-level dialog(s)
this.dialogs = new DialogSet(this.dialogState);
// Add the Greeting dialog to the set
this.dialogs.add(new GreetingDialog(GREETING_DIALOG, this.userProfileAccessor));
this.conversationState = conversationState;
constructor(config, telemetryClient) {
const luisIsConfigured = config && config.applicationId && config.endpointKey && config.endpoint;
if (luisIsConfigured) {
// Set the recognizer options depending on which endpoint version you want to use e.g v2 or v3.
// More details can be found in https://docs.microsoft.com/azure/cognitive-services/luis/luis-migration-api-v3
const recognizerOptions = {
apiVersion: 'v3',
telemetryClient: telemetryClient
};
this.recognizer = new LuisRecognizer(config, recognizerOptions);
}
}
nativeLanguages: ['en'],
setUserLanguage: setUserLanguage,
getUserLanguage: getUserLanguage
});
adapter.use(languageTranslator);
// Add locale converter middleware
const localeConverter = new LocaleConverter({
toLocale: 'en-us',
setUserLocale: setUserLocale,
getUserLocale: getUserLocale
});
adapter.use(localeConverter);
// Add Luis recognizer middleware
const luisRecognizer = new LuisRecognizer({
appId: "xxxxxx",
subscriptionKey: "xxxxxx"
});
adapter.use(luisRecognizer);
// Listen for incoming requests
server.post('/api/messages', (req, res) => {
// Route received request to adapter for processing
adapter.processActivity(req, res, async (context) => {
if (context.activity.type != 'message') {
await context.sendActivity(`[${context.activity.type} event detected]`);
} else {
let results = luisRecognizer.get(context);
for (const intent in results.intents) {
await context.sendActivity(`intent: ${intent.toString()} : ${results.intents[intent.toString()]}`)
}
if (!onTurnAccessor) throw new Error('Missing parameter. On turn property accessor is required.');
if (!conversationState) throw new Error('Missing parameter. Conversation state is required.');
if (!userProfileAccessor) throw new Error('Missing parameter. User profile accessor is required.');
if (!botConfig) throw new Error('Missing parameter. Bot configuration is required.');
// keep on turn accessor
this.onTurnAccessor = onTurnAccessor;
// add dialogs
this.addDialog(new WhatCanYouDoDialog());
this.addDialog(new QnADialog(botConfig, userProfileAccessor));
// add recognizer
const luisConfig = botConfig.findServiceByNameOrId(LUIS_CONFIGURATION);
if (!luisConfig || !luisConfig.appId) throw new Error(`Cafe Dispatch LUIS model not found in .bot file. Please ensure you have all required LUIS models created and available in the .bot file. See readme.md for additional information.\n`);
this.luisRecognizer = new LuisRecognizer({
applicationId: luisConfig.appId,
endpoint: luisConfig.getEndpoint(),
// CAUTION: Authoring key is used in this example as it is appropriate for prototyping.
// When implimenting for deployment/production, assign and use a subscription key instead of an authoring key.
endpointKey: luisConfig.authoringKey
});
}
/**
// ask user for missing information
await validatorContext.context.sendActivity(newReservation.getMissingPropertyReadOut());
}
// We don't yet have everything we need. Return false.
return false;
});
// Keep a copy of accessors for use within this class.
this.reservationsAccessor = reservationsAccessor;
this.onTurnAccessor = onTurnAccessor;
this.userProfileAccessor = userProfileAccessor;
// add recognizer
const luisConfig = botConfig.findServiceByNameOrId(LUIS_CONFIGURATION);
if (!luisConfig || !luisConfig.appId) throw new Error(`Book Table Turn.N LUIS configuration not found in .bot file. Please ensure you have all required LUIS models created and available in the .bot file. See readme.md for additional information\n`);
this.luisRecognizer = new LuisRecognizer({
applicationId: luisConfig.appId,
endpoint: luisConfig.getEndpoint(),
// CAUTION: Its better to assign and use a subscription key instead of authoring key here.
endpointKey: luisConfig.subscriptionKey
});
}
/**
constructor(application, luisPredictionOptions, includeApiResults) {
this.luisRecognizer = new LuisRecognizer(application, luisPredictionOptions, true);
}
config.languageModels.forEach((model: LuisService): void => {
const luisService: LuisService = new LuisService(model);
const luisApp: LuisApplication = {
applicationId: luisService.appId,
endpointKey: luisService.subscriptionKey,
endpoint: luisService.getEndpoint()
};
if (cognitiveModelSet.luisServices !== undefined) {
cognitiveModelSet.luisServices.set(luisService.id, new LuisRecognizer(luisApp, luisPredictionOptions));
}
});