### Install botbuilder-testing Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-testing/README.md Installs the botbuilder-testing library using npm. This is the first step to using the testing utilities. ```bash npm install --save botbuilder-testing ``` -------------------------------- ### Start Local Bot Development Server Source: https://github.com/microsoft/botbuilder-js/blob/main/docs/functional-tests/functional_tests_on_bots_from_scratch_to_ci.md This command starts the Node.js development server for the bot. It should be executed in the terminal from the directory containing the bot's entry point file (e.g., index.js). ```bash node index.js ``` -------------------------------- ### Install Generator Dependencies Source: https://github.com/microsoft/botbuilder-js/blob/main/generators/generator-botbuilder/README.md Installs the npm dependencies required for the generator-botbuilder package. This command should be run after navigating into the generator's directory. ```bash npm install ``` -------------------------------- ### beginDialog Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/classes/botbuilder_ai.qnamakerdialog.md Starts the QnA Maker dialog and pushes it onto the dialog stack. ```APIDOC ## [METHOD] beginDialog ### Description Called when the dialog is started and pushed onto the dialog stack. It processes the initial turn and determines if the dialog remains active. ### Method ASYNC ### Parameters #### Path Parameters - **dc** (DialogContext) - Required - The DialogContext for the current turn of conversation. - **options** (object) - Optional - Initial information, including QnA Maker context data. ### Response #### Success Response (200) - **Promise** - A promise resolving to the turn result indicating if the dialog is still active. ### Response Example { "status": "complete", "result": null } ``` -------------------------------- ### Install botframework-schema Preview Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botframework-schema/README.md Installs the preview version of the botframework-schema package using npm. It's recommended to lock down the version in package.json to avoid build breaks during the preview phase. ```bash npm install --save botframework-schema@preview ``` -------------------------------- ### Install Bot Builder AI package Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-ai/README.md Commands to install the botbuilder-ai package via npm and configure registry settings for daily builds or standard releases. ```bash npm install --save botbuilder-ai ``` ```bash npm config set registry https://botbuilder.myget.org/F/botbuilder-v4-js-daily/npm/ ``` ```bash npm config set registry https://registry.npmjs.org/ ``` -------------------------------- ### Install Bot Builder and Restify (Bash) Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder/README.md Installs the botbuilder and restify modules using npm. BotBuilder is the core framework, and Restify is used here to create an HTTP server for the bot. ```bash npm install --save botbuilder npm install --save restify ``` -------------------------------- ### Install botframework-connector using npm Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botframework-connector/README.md This command installs the botframework-connector package, which is required for building bots that communicate with the Bot Connector service. Ensure you have Node.js version 6.x.x or higher installed. ```bash npm install botframework-connector ``` -------------------------------- ### Install Azure Resource Management SDK Source: https://github.com/microsoft/botbuilder-js/blob/main/tools/resourceManagement/README.md Command to install the azure-arm-resource package via npm for use in Node.js projects. ```bash npm install azure-arm-resource ``` -------------------------------- ### Install Bot Builder Azure package Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-azure/README.md Commands to install the botbuilder-azure package via npm. Includes instructions for switching between daily builds and the standard registry. ```bash npm install --save botbuilder-azure ``` ```bash npm config set registry https://botbuilder.myget.org/F/botbuilder-v4-js-daily/npm/ ``` ```bash npm config set registry https://registry.npmjs.org/ ``` -------------------------------- ### Install Bot Builder Package (Bash) Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder/README.md Installs the latest version of the botbuilder package using npm. This is the primary command for adding the core library to your Node.js project. ```bash npm install --save botbuilder ``` -------------------------------- ### Install Bot Builder Dialogs Declarative Package Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-dialogs-declarative/README.md Installs the latest version of the botbuilder-dialogs-declarative package using npm. This command specifies a registry for daily builds. ```bash npm install --save botbuilder-dialogs-declarative registry=https://botbuilder.myget.org/F/botbuilder-v4-js-daily/npm/ ``` -------------------------------- ### Install Bot Builder Dialogs Package Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-dialogs/README.md Installs the latest version of the botbuilder-dialogs package using npm. This is the standard method for adding the library to your project. ```bash npm install --save botbuilder-dialogs ``` -------------------------------- ### Connect Bot to Channels with CloudAdapter (JavaScript) Source: https://context7.com/microsoft/botbuilder-js/llms.txt The CloudAdapter is the recommended adapter for connecting bots to various channels, supporting both HTTP and WebSocket streaming. It handles authentication and processes incoming requests. This example sets up a basic HTTP server using restify and configures the adapter with authentication credentials. It requires 'botbuilder' and 'restify' packages. ```javascript const { CloudAdapter, ConfigurationBotFrameworkAuthentication } = require('botbuilder'); const restify = require('restify'); // Create HTTP server const server = restify.createServer(); server.use(restify.plugins.bodyParser()); // Create adapter with authentication const botFrameworkAuthentication = new ConfigurationBotFrameworkAuthentication({ MicrosoftAppId: process.env.MicrosoftAppId, MicrosoftAppPassword: process.env.MicrosoftAppPassword, MicrosoftAppTenantId: process.env.MicrosoftAppTenantId }); const adapter = new CloudAdapter(botFrameworkAuthentication); // Error handler adapter.onTurnError = async (context, error) => { console.error(`[onTurnError] unhandled error: ${error}`); await context.sendActivity('The bot encountered an error.'); // Clear conversation state on error await conversationState.clear(context); }; // Create bot instance const bot = new EchoBot(); // Listen for incoming requests server.post('/api/messages', async (req, res) => { await adapter.process(req, res, (context) => bot.run(context)); }); server.listen(process.env.port || 3978, () => { console.log(`Bot listening on port ${process.env.port || 3978}`); }); ``` -------------------------------- ### GuidEntityRecognizer Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-dialogs-adaptive/etc/botbuilder-dialogs-adaptive.api.md Recognizes GUID (Globally Unique Identifier) entities within text. ```APIDOC ## GuidEntityRecognizer ### Description Recognizes GUID (Globally Unique Identifier) entities within text. This recognizer is useful for extracting unique identifiers from user input. ### Method Not applicable (This is a class definition, not an endpoint). ### Endpoint Not applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Test Bot Interactions with TestAdapter in JavaScript Source: https://context7.com/microsoft/botbuilder-js/llms.txt This snippet illustrates how to use TestAdapter for unit testing bots. It simulates user messages and asserts bot responses without needing a live channel. Examples include echoing user input, handling conversation updates like welcome messages, and testing dialog flows with TextPrompt and WaterfallDialog. ```javascript const { TestAdapter, TurnContext } = require('botbuilder'); const assert = require('assert'); describe('EchoBot', () => { it('should echo user input', async () => { const adapter = new TestAdapter(async (context) => { if (context.activity.type === 'message') { await context.sendActivity(`Echo: ${context.activity.text}`); } }); await adapter .send('Hello') .assertReply('Echo: Hello') .send('World') .assertReply('Echo: World'); }); it('should handle conversation updates', async () => { const adapter = new TestAdapter(async (context) => { if (context.activity.type === 'conversationUpdate') { if (context.activity.membersAdded?.length > 0) { await context.sendActivity('Welcome!'); } } }); await adapter .send({ type: 'conversationUpdate', membersAdded: [{ id: 'user1', name: 'User 1' }] }) .assertReply('Welcome!'); }); it('should test dialog flow', async () => { const conversationState = new ConversationState(new MemoryStorage()); const dialogState = conversationState.createProperty('dialogState'); const adapter = new TestAdapter(async (context) => { const dialogSet = new DialogSet(dialogState); dialogSet.add(new TextPrompt('namePrompt')); dialogSet.add(new WaterfallDialog('greeting', [ async (step) => step.prompt('namePrompt', 'What is your name?'), async (step) => { await step.context.sendActivity(`Hello, ${step.result}!`); return step.endDialog(); } ])); const dc = await dialogSet.createContext(context); const result = await dc.continueDialog(); if (result.status === DialogTurnStatus.empty) { await dc.beginDialog('greeting'); } await conversationState.saveChanges(context); }); await adapter .send('hi') .assertReply('What is your name?') .send('John') .assertReply('Hello, John!'); }); }); ``` -------------------------------- ### BeginSkill Dialog Configuration (TypeScript) Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-dialogs-adaptive/etc/botbuilder-dialogs-adaptive.api.md Defines the configuration interface for the BeginSkill dialog, which allows a bot to start another skill. It includes properties for activity templates, interruption handling, and skill endpoint details. ```typescript export class BeginSkill extends SkillDialog implements BeginSkillConfiguration { static $kind: string; constructor(options?: SkillDialogOptions); activity: TemplateInterface, DialogStateManager>; activityProcessed: BoolExpression; allowInterruptions: BoolExpression; beginDialog(dc: DialogContext, options?: BeginSkillDialogOptions): Promise; botId: StringExpression; connectionName: StringExpression; continueDialog(dc: DialogContext): Promise; disabled?: BoolExpression; endDialog(turnContext: TurnContext, instance: DialogInstance, reason: DialogReason): Promise; getConverter(property: keyof BeginSkillConfiguration): Converter | ConverterFactory; protected onComputeId(): string; protected onPreBubbleEvent(dc: DialogContext, e: DialogEvent): Promise; repromptDialog(turnContext: TurnContext, instance: DialogInstance): Promise; resultProperty?: StringExpression; resumeDialog(dc: DialogContext, reason: DialogReason, result?: any): Promise>; skillAppId: StringExpression; skillEndpoint: StringExpression; skillHostEndpoint: StringExpression; } export interface BeginSkillConfiguration extends DialogConfiguration { activity?: TemplateInterfaceProperty, DialogStateManager>; activityProcessed?: BoolProperty; allowInterruptions?: BoolProperty; botId?: StringProperty; connectionName?: StringProperty; disabled?: BoolProperty; resultProperty?: StringProperty; skillAppId?: StringProperty; skillEndpoint?: StringProperty; skillHostEndpoint?: StringProperty; } export type BoolProperty = boolean | BoolExpression | Property; ``` -------------------------------- ### Handle Incoming Bot Messages with ActivityHandler (JavaScript) Source: https://context7.com/microsoft/botbuilder-js/llms.txt The ActivityHandler class provides an event-driven mechanism to process various incoming user activities. This example demonstrates handling messages, new member additions, and reactions, emitting events that can be subscribed to for custom logic. It requires the 'botbuilder' package. ```javascript const { ActivityHandler, MessageFactory } = require('botbuilder'); class EchoBot extends ActivityHandler { constructor() { super(); // Handle incoming messages this.onMessage(async (context, next) => { const replyText = `Echo: ${context.activity.text}`; await context.sendActivity(MessageFactory.text(replyText, replyText)); await next(); }); // Handle new members joining the conversation this.onMembersAdded(async (context, next) => { const membersAdded = context.activity.membersAdded; const welcomeText = 'Hello and welcome!'; for (const member of membersAdded) { if (member.id !== context.activity.recipient.id) { await context.sendActivity(MessageFactory.text(welcomeText)); } } await next(); }); // Handle reactions added to messages this.onReactionsAdded(async (context, next) => { for (const reaction of context.activity.reactionsAdded) { await context.sendActivity(`You reacted with: ${reaction.type}`); } await next(); }); } } module.exports.EchoBot = EchoBot; ``` -------------------------------- ### Initialize Restify server and Bot Adapter Source: https://github.com/microsoft/botbuilder-js/blob/main/docs/functional-tests/functional_tests_on_bots_from_scratch_to_ci.md Sets up the Restify web server and configures the BotFrameworkAdapter with middleware, state management, and error handling. ```javascript const restify = require('restify'); const path = require('path'); const { BotFrameworkAdapter, MemoryStorage, UserState, ConversationState, InspectionState, InspectionMiddleware } = require('botbuilder'); const { MyBot } = require('./bots/myBot'); const ENV_FILE = path.join(__dirname, '.env'); require('dotenv').config({ path: ENV_FILE }); const adapter = new BotFrameworkAdapter({ appId: process.env.MicrosoftAppId, appPassword: process.env.MicrosoftAppPassword }); var memoryStorage = new MemoryStorage(); var inspectionState = new InspectionState(memoryStorage); var userState = new UserState(memoryStorage); var conversationState = new ConversationState(memoryStorage); adapter.use(new InspectionMiddleware(inspectionState, userState, conversationState, { appId: process.env.MicrosoftAppId, appPassword: process.env.MicrosoftAppPassword })); adapter.onTurnError = async (context, error) => { console.error(`\n [onTurnError]: ${ error }`); await context.sendActivity(`Oops. Something went wrong!`); }; var bot = new MyBot(conversationState); let server = restify.createServer(); server.listen(process.env.port || process.env.PORT || 3978, function() { console.log(`\n${ server.name } listening to ${ server.url }`); }); server.post('/api/messages', (req, res) => { adapter.processActivity(req, res, async (turnContext) => { await bot.run(turnContext); }); }); ``` -------------------------------- ### Initialize Node.js Project (Bash) Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder/README.md Initializes a new Node.js project in the current directory. This command creates a package.json file, which manages project dependencies and scripts. ```bash npm init ``` -------------------------------- ### Create ConnectorClient and send message in Node.js Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botframework-connector/README.md This JavaScript example demonstrates how to create an authenticated ConnectorClient using MicrosoftAppCredentials. It then initializes a conversation and sends a message activity to a recipient. This requires your bot's App ID and password, along with the bot and user IDs. ```javascript var { ConnectorClient, MicrosoftAppCredentials } = require('botframework-connector'); async function connectToSlack() { var credentials = new MicrosoftAppCredentials('', ''); var botId = ''; var recipientId = ''; var client = new ConnectorClient(credentials, { baseUri: 'https://slack.botframework.com' }); var conversationResponse = await client.conversations.createConversation({ bot: { id: botId }, members: [ { id: recipientId } ], isGroup: false }); var activityResponse = await client.conversations.sendToConversation(conversationResponse.id, { type: 'message', from: { id: botId }, recipient: { id: recipientId }, text: 'This a message from Bot Connector Client (NodeJS)' }); console.log('Sent reply with ActivityId:', activityResponse.id); } ``` -------------------------------- ### Configure and Initialize LUIS Recognizer Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-ai/README.md Demonstrates importing the necessary modules, defining the LUIS application configuration, and instantiating the LuisRecognizer class for use in a bot. ```javascript const { LuisRecognizer, QnAMaker } = require('botbuilder-ai'); const luisApplication = { applicationId: process.env.appId, endpointKey: process.env.subscriptionKey, azureRegion: process.env.region } const luisPredictionOptions = { includeAllIntents: true, log: true, staging: false } const luisRecognizer = new LuisRecognizer(luisApplication, luisPredictionOptions, true); ``` -------------------------------- ### QnA Maker Configuration Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/README.md Configuration interfaces for setting up QnA Maker dialogs and clients. ```APIDOC ## GET /qnamaker/configuration ### Description Retrieves the configuration schema for initializing a QnA Maker dialog. ### Method GET ### Endpoint /qnamaker/configuration ### Response #### Success Response (200) - **QnAMakerDialogConfiguration** (Object) - The configuration object containing knowledge base ID and endpoint keys. #### Response Example { "knowledgeBaseId": "string", "endpointKey": "string", "host": "string" } ``` -------------------------------- ### Manage Dialog Flows with DialogSet and DialogContext Source: https://context7.com/microsoft/botbuilder-js/llms.txt Demonstrates how to initialize a DialogSet and use DialogContext to manage the dialog stack. It shows how to continue an existing dialog or begin a new one based on the current turn status. ```javascript const { ConversationState, MemoryStorage, ActivityHandler } = require('botbuilder'); const { DialogSet, DialogTurnStatus } = require('botbuilder-dialogs'); class DialogBot extends ActivityHandler { constructor(conversationState, userState, dialog) { super(); this.conversationState = conversationState; this.userState = userState; this.dialog = dialog; this.dialogState = this.conversationState.createProperty('DialogState'); this.onMessage(async (context, next) => { const dialogSet = new DialogSet(this.dialogState); dialogSet.add(this.dialog); const dialogContext = await dialogSet.createContext(context); const results = await dialogContext.continueDialog(); if (results.status === DialogTurnStatus.empty) { await dialogContext.beginDialog(this.dialog.id); } await next(); }); this.onDialog(async (context, next) => { await this.conversationState.saveChanges(context, false); await this.userState.saveChanges(context, false); await next(); }); } } ``` -------------------------------- ### Initialize QnAMaker Instance Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/classes/botbuilder_ai.qnamaker.md Demonstrates how to instantiate the QnAMaker class by providing the required endpoint configuration and optional telemetry settings. ```typescript const qnaMaker = new QnAMaker({ knowledgeBaseId: "YOUR_KB_ID", endpointKey: "YOUR_ENDPOINT_KEY", host: "YOUR_HOST_URL" }, options, telemetryClient, true); ``` -------------------------------- ### QnACardBuilder - getQnAPromptsCard Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/classes/botbuilder_ai.qnacardbuilder.md Returns an activity with answer text and a hero card attachment, containing buttons for multi turn prompts. ```APIDOC ## getQnAPromptsCard ### Description Returns an activity with answer text and a hero card attachment, containing buttons for multi turn prompts. ### Method Static ### Endpoint N/A (This is a static method within a class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **result** (QnAMakerResult) - Required - QnAMaker result containing the answer text and multi turn prompts to be displayed. ### Response #### Success Response (Partial) * **Partial** - Activity representing the prompts as a card ### Request Example ```json { "result": { "answers": [ { "score": 0.9, "questions": ["What is QnA Maker?"], "answer": "QnA Maker is a cloud-based AI service.", "source": "knowledgebase.pdf", "shortAnswer": "QnA Maker is a cloud-based AI service.", "dialog": { "isContextOnly": false, "prompts": [ { "displayOrder": 0, "qnaId": 1, "qna": "What is QnA Maker?" } ] } } ], "questions": [], "detectedQuestions": [] } } ``` ### Response Example ```json { "type": "message", "text": "QnA Maker is a cloud-based AI service.", "attachments": [ { "contentType": "application/vnd.microsoft.card.hero", "content": { "text": "QnA Maker is a cloud-based AI service.", "buttons": [ { "type": "imBack", "title": "What is QnA Maker?", "value": "What is QnA Maker?" } ] } } ] } ``` ``` -------------------------------- ### Install Bot Builder Core Package Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-core/README.md Installs the latest published version of the botbuilder-core package using npm. This is the standard method for adding the library to your bot project. ```bash npm install --save botbuilder-core ``` -------------------------------- ### Get Location Card Action Interface in TypeScript Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botframework-schema/etc/botframework-schema.api.md Represents an action to get the user's location. It includes optional parameters to control the user experience, such as choosing a location on a map. ```typescript // @public export interface GetLocationCardAction { parameters?: GetLocationActionParameters; type: 'VivaAction.GetLocation'; } ``` -------------------------------- ### Initialize LuisRecognizer with LUIS Application Configuration (LuisApplication) Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/classes/botbuilder_ai.luisrecognizer.md This constructor initializes a LuisRecognizer instance using a LuisApplication configuration object. It allows for more detailed configuration of the LUIS application, including endpoint details and other settings. Optional prediction options and a deprecated flag for API results are also supported. ```typescript new LuisRecognizer(luisApplicationConfig, options?, includeApiResults?) ``` -------------------------------- ### Install Bot Builder Application Insights Package Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-applicationinsights/README.md Installs the latest version of the botbuilder-applicationinsights package using npm. This is the primary method for adding the package to your bot project. ```bash npm install --save botbuilder-applicationinsights ``` -------------------------------- ### LuisApplication Interface Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/interfaces/botbuilder_ai.luisapplication.md Defines the structure for configuring a LUIS application, including its ID, endpoint, and endpoint key. ```APIDOC ## LuisApplication Interface ### Description Represents the configuration for a LUIS application, used to initialize a LuisRecognizer. ### Properties #### applicationId - **applicationId** (string) - Required - Your model's application ID from LUIS. #### endpoint - **endpoint** (string) - Optional - The LUIS endpoint. Defaults to https://westus.api.cognitive.microsoft.com. #### endpointKey - **endpointKey** (string) - Required - The endpoint key for communicating with LUIS. ### Example ```json { "applicationId": "YOUR_LUIS_APP_ID", "endpoint": "https://your-region.api.cognitive.microsoft.com", "endpointKey": "YOUR_LUIS_ENDPOINT_KEY" } ``` ``` -------------------------------- ### GetConversationReference Dialog Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-dialogs-adaptive/etc/botbuilder-dialogs-adaptive.api.md Gets a reference to the current conversation. ```APIDOC ## GetConversationReference Dialog ### Description Gets a reference to the current conversation. This can be useful for sending proactive messages or managing conversation state. ### Method Not applicable (This is a class definition, not an endpoint). ### Endpoint Not applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Configure deployment settings Source: https://github.com/microsoft/botbuilder-js/blob/main/docs/functional-tests/functional_tests_on_bots_from_scratch_to_ci.md Defines the .deployment configuration file to enable automated builds during Azure deployment. ```text [config] SCM_DO_BUILD_DURING_DEPLOYMENT=true ``` -------------------------------- ### Range Class for Text Spans Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-lg/etc/botbuilder-lg.api.md The Range class defines a span of text within a file, using start and end Position objects. It can be instantiated with two Position objects or with line and character numbers for both start and end points. A static DefaultRange is also provided. This class is crucial for highlighting or selecting text segments. ```typescript class Range_2 { constructor(start: Position, end: Position); constructor(startLine: number, startChar: number, endLine: number, endChar: number); // (undocumented) static readonly DefaultRange: Range_2; // (undocumented) end: Position; // (undocumented) start: Position; // (undocumented) toString: () => string; } export { Range_2 as Range } ``` -------------------------------- ### QnAMakerDialog Constructor Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/classes/botbuilder_ai.qnamakerdialog.md Initializes a new instance of the QnAMakerDialog class. ```APIDOC ## QnAMakerDialog Constructor ### Description Initializes a new instance of the QnAMakerDialog class. ### Method CONSTRUCTOR ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body for constructor" } ``` ### Response #### Success Response (200) - **QnAMakerDialog** (object) - An instance of the QnAMakerDialog class. #### Response Example ```json { "example": "Instance of QnAMakerDialog" } ``` ``` -------------------------------- ### Generate web.config for Bot Deployment (Azure CLI) Source: https://github.com/microsoft/botbuilder-js/blob/main/docs/functional-tests/functional_tests_on_bots_from_scratch_to_ci.md This Azure CLI command prepares the bot source code for deployment to Azure by generating the necessary web.config file. It specifies the code directory and the programming language used for the bot. ```powershell call az bot prepare-deploy --code-dir "$(System.DefaultWorkingDirectory)/test-bot" --lang Javascript ``` -------------------------------- ### GET /recognizer/multi-language Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-dialogs-adaptive/etc/botbuilder-dialogs-adaptive.api.md Retrieves recognition results based on the current locale using the MultiLanguageRecognizer. ```APIDOC ## GET /recognizer/multi-language ### Description Processes user input using a language-specific recognizer based on the provided locale and dialog context. ### Method GET ### Endpoint /recognizer/multi-language ### Parameters #### Query Parameters - **locale** (string) - Required - The language code to select the appropriate recognizer. #### Request Body - **activity** (Activity) - Required - The user activity to be recognized. ### Request Example { "locale": "en-US", "activity": { "text": "Hello" } } ### Response #### Success Response (200) - **result** (RecognizerResult) - The structured recognition result. #### Response Example { "text": "Hello", "intents": { "Greeting": { "score": 0.99 } } } ``` -------------------------------- ### GET /teams/members Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder/etc/botbuilder.api.md Retrieves a paginated list of members from a specific team or the current context. ```APIDOC ## GET /teams/members ### Description Retrieves a paginated list of members within a team context. ### Method GET ### Endpoint /teams/members ### Parameters #### Query Parameters - **teamId** (string) - Optional - The ID of the team to fetch members from. - **pageSize** (number) - Optional - Number of members to return per page. - **continuationToken** (string) - Optional - Token for pagination. ### Response #### Success Response (200) - **TeamsPagedMembersResult** (object) - The paginated list of team members. ### Response Example { "members": [], "continuationToken": "token_abc" } ``` -------------------------------- ### Basic Bot Implementation (JavaScript) Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder/README.md Sets up a basic Echo Bot using Bot Builder and Restify. It creates an adapter, an HTTP server, and defines a message handler to echo user input back to them. Requires MicrosoftAppId and MicrosoftAppPassword environment variables. ```javascript const restify = require('restify'); const botbuilder = require('botbuilder'); // Create bot adapter, which defines how the bot sends and receives messages. var adapter = new botbuilder.BotFrameworkAdapter({ appId: process.env.MicrosoftAppId, appPassword: process.env.MicrosoftAppPassword }); // Create HTTP server. let server = restify.createServer(); server.listen(process.env.port || process.env.PORT || 3978, function () { console.log(` ${server.name} listening to ${server.url}`); console.log(` Get Bot Framework Emulator: https://aka.ms/botframework-emulator`); }); // Listen for incoming requests at /api/messages. server.post('/api/messages', (req, res) => { // Use the adapter to process the incoming web request into a TurnContext object. adapter.processActivity(req, res, async (turnContext) => { // Do something with this incoming activity! if (turnContext.activity.type === 'message') { // Get the user's text const utterance = turnContext.activity.text; // send a reply await turnContext.sendActivity(`I heard you say ${ utterance }`); } }); }); ``` -------------------------------- ### HashtagEntityRecognizer Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-dialogs-adaptive/etc/botbuilder-dialogs-adaptive.api.md A text entity recognizer for identifying hashtag patterns (e.g., #example) within a given text. ```typescript export class HashtagEntityRecognizer extends TextEntityRecognizer { // (undocumented) static $kind: string; protected _recognize(text: string, culture: string): ModelResult[]; } ``` -------------------------------- ### Initialize QnAMakerDialog Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/classes/botbuilder_ai.qnamakerdialog.md Initializes a new instance of the QnAMakerDialog class. This dialog is used to query a QnA Maker knowledge base and return answers. It accepts various parameters to configure the connection to the knowledge base, how answers are presented, and filtering options. ```typescript new QnAMakerDialog( knowledgeBaseId: string, endpointKey: string, hostname: string, noAnswer?: Activity, threshold?: number, suggestionsActivityFactory?: QnASuggestionsActivityFactory, cardNoMatchText?: string, top?: number, cardNoMatchResponse?: Activity, rankerType?: RankerTypes, strictFilters?: QnAMakerMetadata[], dialogId?: string, strictFiltersJoinOperator?: JoinOperator, enablePreciseAnswer?: boolean, displayPreciseAnswerOnly?: boolean, qnaServiceType?: ServiceType, useTeamsAdaptiveCard?: boolean ) ``` -------------------------------- ### QnA Maker Integration with Bot Builder JS Source: https://context7.com/microsoft/botbuilder-js/llms.txt Shows how to integrate Azure QnA Maker for natural language question answering. It includes direct usage of the QnAMaker class and implementation using QnAMakerDialog within a component dialog. Requires 'botbuilder-ai' and 'botbuilder-dialogs' packages. ```javascript const { QnAMaker, QnAMakerDialog } = require('botbuilder-ai'); const { ComponentDialog, DialogSet, WaterfallDialog } = require('botbuilder-dialogs'); // Direct QnA Maker usage class QnABot extends ActivityHandler { constructor() { super(); this.qnaMaker = new QnAMaker({ knowledgeBaseId: process.env.QnAKnowledgebaseId, endpointKey: process.env.QnAEndpointKey, host: process.env.QnAEndpointHostName }); this.onMessage(async (context, next) => { const response = await this.qnaMaker.getAnswers(context); if (response.length > 0) { await context.sendActivity(response[0].answer); } else { await context.sendActivity("I couldn't find an answer to your question."); } await next(); }); } } // Using QnAMakerDialog in a component dialog class QnADialog extends ComponentDialog { constructor() { super('qnaDialog'); this.addDialog(new QnAMakerDialog( process.env.QnAKnowledgebaseId, process.env.QnAEndpointKey, process.env.QnAEndpointHostName, undefined, // No fallback answer 0.3, // Score threshold undefined, // Default activity to send undefined, // No metadata undefined, // No source filter { activeLearningCardTitle: 'Did you mean:', cardNoMatchText: 'None of the above', cardNoMatchResponse: 'Thanks for the feedback.' } )); this.initialDialogId = 'qnaMakerDialog'; } } ``` -------------------------------- ### GET /error-models Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botframework-schema/etc/botframework-schema.api.md Defines the structure for error responses returned by the bot service when an operation fails. ```APIDOC ## GET /error-models ### Description Describes the standard error response format used across the Bot Builder API. ### Method GET ### Endpoint /error ### Response #### Success Response (200) - **error** (ErrorModel) - The error object containing code and message details. #### Response Example { "error": { "code": "ServiceError", "message": "An unexpected error occurred.", "innerHttpError": {} } } ``` -------------------------------- ### Define Basic Language Generation Templates Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-lg/README.MD Demonstrates the syntax for creating .lg files, including template definitions and variable interpolation using the ${} syntax. ```markdown # greetingTemplate - Hello ${user.name}, how are you? - Good morning ${user.name}. It's nice to see you again. - Good day ${user.name}. What can I do for you today? ``` -------------------------------- ### ConfirmInput Class Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-dialogs-adaptive/etc/botbuilder-dialogs-adaptive.api.md A dialog for getting confirmation from the user. It supports custom choices, output formats, and styling for prompts. ```typescript export class ConfirmInput extends InputDialog implements ConfirmInputConfiguration { // (undocumented) static $kind: string; choiceOptions?: ObjectExpression; confirmChoices?: ObjectExpression; defaultLocale?: StringExpression; // (undocumented) getConverter(property: keyof ConfirmInputConfiguration): Converter | ConverterFactory; // (undocumented) protected onComputeId(): string; protected onRecognizeInput(dc: DialogContext): Promise; protected onRenderPrompt(dc: DialogContext, state: InputState): Promise>; outputFormat: StringExpression; style: EnumExpression; } ``` -------------------------------- ### GuidEntityRecognizer Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-dialogs-adaptive/etc/botbuilder-dialogs-adaptive.api.md A text entity recognizer specifically designed to identify GUID (Globally Unique Identifier) patterns within text. ```typescript export class GuidEntityRecognizer extends TextEntityRecognizer { // (undocumented) static $kind: string; protected _recognize(text: string, culture: string): ModelResult[]; } ``` -------------------------------- ### Submit Feedback to Knowledge Base Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/classes/botbuilder_ai.qnamaker.md Illustrates how to send feedback records to the QnA Maker service to assist in training and improving the knowledge base. ```typescript const feedback = { feedbackRecords: [...] }; await qnaMaker.callTrain(feedback); ``` -------------------------------- ### QnACardBuilder - getSuggestionsCard Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/classes/botbuilder_ai.qnacardbuilder.md Returns an activity with a hero card attachment, containing buttons for active learning suggestions. ```APIDOC ## getSuggestionsCard ### Description Returns an activity with a hero card attachment, containing buttons for active learning suggestions. ### Method Static ### Endpoint N/A (This is a static method within a class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **suggestionsList** (string[]) - Required - List of suggestions to be displayed on hero card. * **cardTitle** (string) - Required - Title of the hero card. * **cardNoMatchText** (string) - Required - Text for button to be added to card to allow user to select 'no match'. * **useTeamsAdaptiveCard?** (boolean) - Optional - whether to use a Microsoft Teams formatted adaptive card instead of a hero card. Defaults to false. Card width is limited by Teams and long CQA responses should be formatted in the Language Studio to add line breaks. Card payload is specific to MS Teams. ### Response #### Success Response (Partial) * **Partial** - Activity representing the suggestions as a card ### Request Example ```json { "suggestionsList": ["Suggestion 1", "Suggestion 2"], "cardTitle": "Did you mean?", "cardNoMatchText": "No, that's not what I meant.", "useTeamsAdaptiveCard": false } ``` ### Response Example ```json { "type": "message", "attachments": [ { "contentType": "application/vnd.microsoft.card.hero", "content": { "title": "Did you mean?", "buttons": [ { "type": "imBack", "title": "Suggestion 1", "value": "Suggestion 1" }, { "type": "imBack", "title": "Suggestion 2", "value": "Suggestion 2" }, { "type": "imBack", "title": "No, that's not what I meant.", "value": "No, that's not what I meant." } ] } } ] } ``` ``` -------------------------------- ### Unlink Local Generator Package Source: https://github.com/microsoft/botbuilder-js/blob/main/generators/generator-botbuilder/README.md Deletes the symbolic link created for the local generator package. This should be done after development is complete to revert to the globally installed version. ```bash npm unlink ``` -------------------------------- ### Define Bot Components Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-core/etc/botbuilder-core.api.md Shows the implementation of a BotComponent to configure services and dependencies. This is used for modular bot architecture and dependency injection setup. ```typescript export class MyBotComponent extends BotComponent { configureServices(services: ServiceCollection, configuration: Configuration): void { // Register services here } } ``` -------------------------------- ### Get Bot Builder Conversation Reference Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botframework-schema/etc/botframework-schema.api.md Extracts a conversation reference from an activity. This reference can be used to initiate or continue conversations with users. ```typescript export function getConversationReference(source: Partial): ConversationReference; ``` -------------------------------- ### Initialize and Use BotFrameworkAdapter Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder/etc/botbuilder.api.md Demonstrates how to instantiate the BotFrameworkAdapter and utilize its methods for managing conversations and retrieving user tokens. This adapter acts as the bridge between the bot logic and the Bot Framework connector service. ```typescript import { BotFrameworkAdapter } from 'botbuilder'; const adapter = new BotFrameworkAdapter({ appId: process.env.MicrosoftAppId, appPassword: process.env.MicrosoftAppPassword }); // Example of continuing a conversation await adapter.continueConversation(reference, async (context) => { await context.sendActivity('Hello from the adapter!'); }); // Example of retrieving a user token const tokenResponse = await adapter.getUserToken(context, 'connectionName', 'magicCode'); ``` -------------------------------- ### Get Bot Builder Continuation Activity Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botframework-schema/etc/botframework-schema.api.md Retrieves a continuation activity from a conversation reference. This is useful for resuming conversations or re-engaging users. ```typescript export function getContinuationActivity(reference: Partial): Partial; ``` -------------------------------- ### Clone BotBuilder-JS Repository Source: https://github.com/microsoft/botbuilder-js/blob/main/generators/generator-botbuilder/README.md Clones the BotBuilder-JS repository from GitHub to your local machine. This is the first step in setting up the local development environment. ```bash git clone https://github.com/microsoft/BotBuilder-JS.git ``` -------------------------------- ### Get Next Reply from DialogTestClient Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-testing/README.md Illustrates how to retrieve the next reply from the DialogTestClient. This is useful for testing scenarios where a dialog might send multiple responses. ```javascript let reply = client.getNextReply(); ``` -------------------------------- ### QnACardBuilder - getQnAAnswerCard Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/classes/botbuilder_ai.qnacardbuilder.md Returns an activity with answer text and a card attachment, containing buttons for multi turn prompts. ```APIDOC ## getQnAAnswerCard ### Description Returns an activity with answer text and a card attachment, containing buttons for multi turn prompts. ### Method Static ### Endpoint N/A (This is a static method within a class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **result** (QnAMakerResult) - Required - QnAMaker result containing the answer text and multi turn prompts to be displayed. * **displayPreciseAnswerOnly** (boolean) - Required - whether to display PreciseAnswer Only or along with source Answer text. * **useTeamsAdaptiveCard?** (boolean) - Optional - whether to use a Microsoft Teams formatted adaptive card instead of a hero card. Defaults to false. Card width is limited by Teams and long CQA responses should be formatted in the Language Studio to add line breaks. Card payload is specific to MS Teams. ### Response #### Success Response (Partial) * **Partial** - Activity representing the prompts as a card ### Request Example ```json { "result": { "answers": [ { "score": 0.9, "questions": ["What is QnA Maker?"], "answer": "QnA Maker is a cloud-based AI service that makes it easy for you to create a sophisticated question and answer base from your existing content.", "source": "knowledgebase.pdf" } ], "questions": [], "detectedQuestions": [] }, "displayPreciseAnswerOnly": false, "useTeamsAdaptiveCard": false } ``` ### Response Example ```json { "type": "message", "text": "QnA Maker is a cloud-based AI service that makes it easy for you to create a sophisticated question and answer base from your existing content.", "attachments": [ { "contentType": "application/vnd.microsoft.card.hero", "content": { "text": "QnA Maker is a cloud-based AI service that makes it easy for you to create a sophisticated question and answer base from your existing content.", "buttons": [ { "type": "imBack", "title": "What is QnA Maker?", "value": "What is QnA Maker?" } ] } } ] } ``` ``` -------------------------------- ### Get Bot Builder Mentions from Activity Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botframework-schema/etc/botframework-schema.api.md Extracts mentions from an activity, such as user tags or @mentions. This can be used to identify specific users or entities mentioned in a message. ```typescript export function getMentions(source: Partial): Mention[]; ``` -------------------------------- ### LuisRecognizerOptionsV3 Configuration Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/interfaces/botbuilder_ai.luisrecognizeroptionsv3.md Configuration object structure for initializing a LUIS recognizer using the v3 API. ```APIDOC ## Configuration: LuisRecognizerOptionsV3 ### Description Defines the configuration parameters for the LUIS recognizer when using the v3 API endpoint. This object is used to customize how LUIS processes queries and returns intent/entity data. ### Parameters #### Request Body - **apiVersion** (string) - Required - Must be set to "v3". - **datetimeReference** (string) - Optional - Timezone applied to datetimeV2 entities. - **dynamicLists** (Array) - Optional - Dynamic lists of items to recognize at query time. - **externalEntities** (Array) - Optional - List of external entities to be recognized. - **externalEntityRecognizer** (Recognizer) - Optional - External recognizer to identify entities before LUIS processing. - **includeAPIResults** (boolean) - Optional - Whether to include raw LUIS API results in the response. - **includeAllIntents** (boolean) - Optional - Whether to return all intents or only the top scoring intent. - **includeInstanceData** (boolean) - Optional - Whether to include instance data in the response. - **log** (boolean) - Optional - Whether to log queries in LUIS. - **logPersonalInformation** (boolean) - Optional - Whether to log personal information in telemetry. - **preferExternalEntities** (boolean) - Optional - Whether to prioritize external entities over LUIS model results. - **slot** (string) - Optional - The LUIS slot to use ("production" or "staging"). - **telemetryClient** (BotTelemetryClient) - Optional - Custom telemetry client for tracking. - **version** (string) - Optional - Specific version of the LUIS application to use. ### Request Example { "apiVersion": "v3", "slot": "production", "includeAllIntents": true, "log": false } ``` -------------------------------- ### Inspection State Management Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder/etc/botbuilder.api.md A deprecated class for managing inspection state, extending BotState. It requires a Storage dependency in its constructor and defines a method for getting the storage key. ```typescript // @public @deprecated export class InspectionState extends BotState { constructor(storage: Storage_2); protected getStorageKey(_turnContext: TurnContext): string; } ``` -------------------------------- ### Abstract Resource Provider Class Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-dialogs-declarative/etc/botbuilder-dialogs-declarative.api.md Abstract base class for resource providers. Subclasses must implement methods to get individual resources or all resources with a specific extension, and to refresh their content. ```typescript import { ResourceExplorer } from './resourceExplorer'; // Assuming ResourceExplorer is in the same directory or imported correctly import { Resource } from './resource'; // Assuming Resource is in the same directory or imported correctly import { ResourceChangeEvent } from './resourceChangeEvent'; // Assuming ResourceChangeEvent is in the same directory or imported correctly // @public export abstract class ResourceProvider { constructor(resourceExplorer: ResourceExplorer); // Warning: (ae-missing-getter) The property "changed" has a setter but no getter. set changed(callback: (event: ResourceChangeEvent, resources: Resource[]) => void); abstract getResource(id: string): Resource; abstract getResources(extension: string): Resource[]; get id(): string; // (undocumented) protected _id: string; protected onChanged(event: ResourceChangeEvent, resources: Resource[]): void; abstract refresh(): void; get resourceExplorer(): ResourceExplorer; } ``` -------------------------------- ### Get Converter for Recognizer Configuration Property (TypeScript) Source: https://github.com/microsoft/botbuilder-js/blob/main/doc/botbuilder-ai/classes/botbuilder_ai.luisadaptiverecognizer.md Retrieves an expression converter for a given property of the LuisAdaptiveRecognizerConfiguration. This method is used to handle property conversions within the recognizer's configuration. ```typescript getConverter(property: keyof LuisAdaptiveRecognizerConfiguration): Converter | ConverterFactory ``` -------------------------------- ### Configure Node.js Project for Functional Tests Source: https://github.com/microsoft/botbuilder-js/blob/main/docs/functional-tests/functional_tests_on_bots_from_scratch_to_ci.md Sets up a Node.js project for functional testing by defining dependencies such as mocha and swagger-client, and specifying a script to run the tests. This configuration is essential for executing the bot's functional tests. ```json { "name": "functional-tests", "version": "1.0.0", "description": "Test that hits services", "main": "", "dependencies": { "mocha": "^7.0.0", "swagger-client": "^2.1.18" }, "directories": { "test-bot": "test-bot" }, "scripts": { "functional-test":"mocha functional.test.js" }, "keywords": [], "author": "", "license": "MIT" } ``` -------------------------------- ### State Property Accessor - TypeScript Source: https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-core/etc/botbuilder-core.api.md Defines an interface for accessing and managing state properties within a bot's turn context. It allows for getting, setting, and deleting properties with optional default values. ```typescript export interface StatePropertyAccessor { delete(context: TurnContext): Promise; get(context: TurnContext): Promise; get(context: TurnContext, defaultValue: T): Promise; set(context: TurnContext, value: T): Promise; } ```