BotFrameworkAdapter class

A BotAdapter class that connects your bot to Bot Framework channels and the Emulator.

Extends
BotAdapter

Remarks

Use this adapter to connect your bot to the Bot Framework service, through which your bot can reach many chat channels like Skype, Slack, and Teams. This adapter also allows your bot to work with the Bot Framework Emulator, which simulates the Bot Framework service and provides a chat interface for testing and debugging.

The following example shows the typical adapter setup:

const { BotFrameworkAdapter } = require('botbuilder');

const adapter = new BotFrameworkAdapter({
   appId: process.env.MICROSOFT_APP_ID,
   appPassword: process.env.MICROSOFT_APP_PASSWORD
});

Constructors

BotFrameworkAdapter(Partial<BotFrameworkAdapterSettings>)

Creates a new BotFrameworkAdapter instance.

Properties

onTurnError

Gets/sets a error handler that will be called anytime an uncaught exception is raised during a turn.

Methods

continueConversation(Partial<ConversationReference>, (context: TurnContext) => Promise)

Resume a conversation with a user, possibly after some time has gone by.

createConversation(Partial<ConversationReference>, (context: TurnContext) => Promise)

Starts a new conversation with a user. This is typically used to Direct Message (DM) a member of a group.

deleteActivity(TurnContext, Partial<ConversationReference>)

Deletes an activity that was previously sent to a channel.

deleteConversationMember(TurnContext, string)

Deletes a member from the current conversation.

emulateOAuthCards(TurnContext | string, boolean)

Tells the token service to emulate the sending of OAuthCards for a channel.

getAadTokens(TurnContext, string, string[])

Signs the user out with the token server.

getActivityMembers(TurnContext, string)

Lists the members of a given activity as specified in a TurnContext.

getConversationMembers(TurnContext)

Lists the members of the current conversation as specified in a TurnContext.

getConversations(TurnContext | string, string)

Lists the Conversations in which this bot has participated for a given channel server.

getSignInLink(TurnContext, string)

Gets a signin link from the token server that can be sent as part of a SigninCard.

getTokenStatus(TurnContext, string, string)

Retrieves the token status for each configured connection for the given user.

getUserToken(TurnContext, string, string)

Retrieves the OAuth token for a user that is in a sign-in flow.

processActivity(WebRequest, WebResponse, (context: TurnContext) => Promise<any>)

Processes an incoming request received by the bots web server into a TurnContext.

sendActivities(TurnContext, Partial<Activity>[])

Sends a set of outgoing activities to the appropriate channel server.

signOutUser(TurnContext, string, string)

Signs the user out with the token server.

updateActivity(TurnContext, Partial<Activity>)

Replaces an activity that was previously sent to a channel with an updated version.

use((context: TurnContext, next: () => Promise<void>) => Promise | Middleware[])

Registers middleware handlers(s) with the adapter.

Constructor Details

BotFrameworkAdapter(Partial<BotFrameworkAdapterSettings>)

Creates a new BotFrameworkAdapter instance.

new BotFrameworkAdapter(settings?: Partial<BotFrameworkAdapterSettings>)

Parameters

settings
Partial<BotFrameworkAdapterSettings>

(optional) configuration settings for the adapter.

Remarks

Settings for this adapter include:

{
     "appId": "ID assigned to your bot in the [Bot Framework Portal](https://dev.botframework.com/).",
     "appPassword": "Password assigned to your bot in the [Bot Framework Portal](https://dev.botframework.com/).",
     "openIdMetadata": "The Open ID Metadata Endpoint for your bot to use.",
     "oAuthEndpoint": "The OAuth API Endpoint for your bot to use.",
     "channelService": "(Optional) The channel service option for this bot to validate connections from Azure or other channel locations"
 }

Property Details

onTurnError

Gets/sets a error handler that will be called anytime an uncaught exception is raised during a turn.

onTurnError: (context: TurnContext, error: Error) => Promise<void>

Property Value

(context: TurnContext, error: Error) => Promise<void>

Method Details

continueConversation(Partial<ConversationReference>, (context: TurnContext) => Promise)

Resume a conversation with a user, possibly after some time has gone by.

function continueConversation(reference: Partial<ConversationReference>, logic: (context: TurnContext) => Promise<void>)

Parameters

reference
Partial<ConversationReference>

A ConversationReference saved during a previous incoming activity.

logic
(context: TurnContext) => Promise<void>

A function handler that will be called to perform the bots logic after the the adapters middleware has been run.

Returns

Promise<void>

Remarks

This is often referred to as the bot's "Proactive Messaging" flow as it lets the bot proactively send messages to a conversation or user without having to reply directly to an incoming message. Scenarios like sending notifications or coupons to a user are enabled by this method.

In order to use this method, a ConversationReference must first be extracted from an incoming activity. This reference can be stored in a database and used to resume the conversation at a later time. The reference can be created from any incoming activity using TurnContext.getConversationReference(context.activity).

The processing steps for this method are very similar to processActivity() in that a TurnContext will be created which is then routed through the adapters middleware before calling the passed in logic handler. The key difference is that since an activity wasn't actually received from outside, it has to be created by the bot. The created activity will have its address related fields populated but will have a context.activity.type === undefined.

server.post('/api/notifyUser', async (req, res) => {
   // Lookup previously saved conversation reference
   const reference = await findReference(req.body.refId);

   // Proactively notify the user
   if (reference) {
      await adapter.continueConversation(reference, async (context) => {
         await context.sendActivity(req.body.message);
      });
      res.send(200);
   } else {
      res.send(404);
   }
});

createConversation(Partial<ConversationReference>, (context: TurnContext) => Promise)

Starts a new conversation with a user. This is typically used to Direct Message (DM) a member of a group.

function createConversation(reference: Partial<ConversationReference>, logic?: (context: TurnContext) => Promise<void>)

Parameters

reference
Partial<ConversationReference>

A ConversationReference of the user to start a new conversation with.

logic
(context: TurnContext) => Promise<void>

A function handler that will be called to perform the bot's logic after the the adapters middleware has been run.

Returns

Promise<void>

Remarks

This function creates a new conversation between the bot and a single user, as specified by the ConversationReference passed in. In multi-user chat environments, this typically means starting a 1:1 direct message conversation with a single user. If called on a reference already representing a 1:1 conversation, the new conversation will continue to be 1:1.

  • In order to use this method, a ConversationReference must first be extracted from an incoming activity. This reference can be stored in a database and used to resume the conversation at a later time. The reference can be created from any incoming activity using TurnContext.getConversationReference(context.activity).

The processing steps for this method are very similar to processActivity() in that a TurnContext will be created which is then routed through the adapters middleware before calling the passed in logic handler. The key difference is that since an activity wasn't actually received from outside, it has to be created by the bot. The created activity will have its address related fields populated but will have a context.activity.type === undefined..

// Get group members conversation reference
const reference = TurnContext.getConversationReference(context.activity);

// Start a new conversation with the user
await adapter.createConversation(reference, async (ctx) => {
   await ctx.sendActivity(`Hi (in private)`);
});

deleteActivity(TurnContext, Partial<ConversationReference>)

Deletes an activity that was previously sent to a channel.

function deleteActivity(context: TurnContext, reference: Partial<ConversationReference>)

Parameters

context
TurnContext

Context for the current turn of conversation with the user.

reference
Partial<ConversationReference>

Conversation reference information for the activity being deleted.

Returns

Promise<void>

Remarks

Calling TurnContext.deleteActivity() is the preferred way of deleting activities (rather than calling it directly from the adapter), as that will ensure that any interested middleware will be notified.

Tip

Note: Not all chat channels support this method. Calling it on an unsupported channel may result in an error.

deleteConversationMember(TurnContext, string)

Deletes a member from the current conversation.

function deleteConversationMember(context: TurnContext, memberId: string)

Parameters

context
TurnContext

Context for the current turn of conversation with the user.

memberId
string

ID of the member to delete from the conversation.

Returns

Promise<void>

Remarks

Remove a member's identity information from the conversation.

Note that this method does not apply to all channels.

emulateOAuthCards(TurnContext | string, boolean)

Tells the token service to emulate the sending of OAuthCards for a channel.

function emulateOAuthCards(contextOrServiceUrl: TurnContext | string, emulate: boolean)

Parameters

contextOrServiceUrl
TurnContext | string

The URL of the emulator.

emulate
boolean

If true the emulator will emulate the sending of OAuthCards.

Returns

Promise<void>

getAadTokens(TurnContext, string, string[])

Signs the user out with the token server.

function getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[])

Parameters

context
TurnContext

Context for the current turn of conversation with the user.

connectionName
string

Name of the auth connection to use.

resourceUrls
string[]

Returns

Promise<[key: string]: TokenResponse>

getActivityMembers(TurnContext, string)

Lists the members of a given activity as specified in a TurnContext.

function getActivityMembers(context: TurnContext, activityId?: string)

Parameters

context
TurnContext

Context for the current turn of conversation with the user.

activityId
string

(Optional) activity ID to enumerate. If not specified the current activities ID will be used.

Returns

Promise<ChannelAccount[]>

Remarks

Returns an array of ChannelAccount objects representing the users involved in a given activity.

This is different from getConversationMembers() in that it will return only those users directly involved in the activity, not all members of the conversation.

getConversationMembers(TurnContext)

Lists the members of the current conversation as specified in a TurnContext.

function getConversationMembers(context: TurnContext)

Parameters

context
TurnContext

Context for the current turn of conversation with the user.

Returns

Promise<ChannelAccount[]>

Remarks

Returns an array of ChannelAccount objects representing the users currently involved in the conversation in which an activity occured.

This is different from getActivityMembers() in that it will return all members of the conversation, not just those directly involved in the activity.

getConversations(TurnContext | string, string)

Lists the Conversations in which this bot has participated for a given channel server.

function getConversations(contextOrServiceUrl: TurnContext | string, continuationToken?: string)

Parameters

contextOrServiceUrl
TurnContext | string

The URL of the channel server to query or a TurnContext. This can be retrieved from context.activity.serviceUrl.

continuationToken
string

(Optional) token used to fetch the next page of results from the channel server. This should be left as undefined to retrieve the first page of results.

Returns

Promise<ConversationsResult>

Remarks

The channel server returns results in pages and each page will include a continuationToken that can be used to fetch the next page of results from the server.

Gets a signin link from the token server that can be sent as part of a SigninCard.

function getSignInLink(context: TurnContext, connectionName: string)

Parameters

context
TurnContext

Context for the current turn of conversation with the user.

connectionName
string

Name of the auth connection to use.

Returns

Promise<string>

getTokenStatus(TurnContext, string, string)

Retrieves the token status for each configured connection for the given user.

function getTokenStatus(context: TurnContext, userId?: string, includeFilter?: string)

Parameters

context
TurnContext

Context for the current turn of conversation with the user.

userId
string

The user Id for which token status is retrieved.

includeFilter
string

Optional comma seperated list of connection's to include. Blank will return token status for all configured connections.

Returns

Promise<TokenStatus[]>

getUserToken(TurnContext, string, string)

Retrieves the OAuth token for a user that is in a sign-in flow.

function getUserToken(context: TurnContext, connectionName: string, magicCode?: string)

Parameters

context
TurnContext

Context for the current turn of conversation with the user.

connectionName
string

Name of the auth connection to use.

magicCode
string

(Optional) Optional user entered code to validate.

Returns

Promise<TokenResponse>

processActivity(WebRequest, WebResponse, (context: TurnContext) => Promise<any>)

Processes an incoming request received by the bots web server into a TurnContext.

function processActivity(req: WebRequest, res: WebResponse, logic: (context: TurnContext) => Promise<any>)

Parameters

req
WebRequest

An Express or Restify style Request object.

res
WebResponse

An Express or Restify style Response object.

logic
(context: TurnContext) => Promise<any>

A function handler that will be called to perform the bots logic after the received activity has been pre-processed by the adapter and routed through any middleware for processing.

Returns

Promise<void>

Remarks

This method is the main way a bot receives incoming messages.

This method takes a raw incoming request object from a webserver and processes it into a normalized TurnContext that can be used by the bot. This includes any messages sent from a user and is the method that drives what is often referred to as the bot's "Reactive Messaging" flow.

The following steps will be taken to process the activity:

  • The identity of the sender will be verified to be either the Emulator or a valid Microsoft server. The bots appId and appPassword will be used during this process and the request will be rejected if the senders identity can't be verified.
  • The activity will be parsed from the body of the incoming request. An error will be returned if the activity can't be parsed.
  • A TurnContext instance will be created for the received activity and wrapped with a Revocable Proxy.
  • The context will be routed through any middleware registered with the adapter using use(). Middleware is executed in the order in which it's added and any middleware can intercept or prevent further routing of the context by simply not calling the passed in next() function. This is called the "Leading Edge" of the request; middleware will get a second chance to run on the "Trailing Edge" of the request after the bots logic has run.
  • Assuming the context hasn't been intercepted by a piece of middleware, the context will be passed to the logic handler passed in. The bot may perform additional routing or processing at this time. Returning a promise (or providing an async handler) will cause the adapter to wait for any asynchronous operations to complete.
  • Once the bot's logic completes, the promise chain set up by the middleware stack will be resolved, giving middleware a second chance to run on the "Trailing Edge" of the request.
  • After the middleware stack's promise chain has been fully resolved the context object will be revoked() and any future calls to the context will result in a TypeError: Cannot perform 'set' on a proxy that has been revoked being thrown.

Tip

Note: If you see the error TypeError: Cannot perform 'set' on a proxy that has been revoked appearing in your bot's console output, the likely cause is that an async function was used without using the await keyword. Make sure all async functions use await!

server.post('/api/messages', (req, res) => {
   // Route received request to adapter for processing
   adapter.processActivity(req, res, async (context) => {
       // Process any messages received
       if (context.activity.type === ActivityTypes.Message) {
           await context.sendActivity(`Hello World`);
       }
   });
});

sendActivities(TurnContext, Partial<Activity>[])

Sends a set of outgoing activities to the appropriate channel server.

function sendActivities(context: TurnContext, activities: Partial<Activity>[])

Parameters

context
TurnContext

Context for the current turn of conversation with the user.

activities
Partial<Activity>[]

List of activities to send.

Returns

Promise<ResourceResponse[]>

Remarks

The activities will be sent one after another in the order in which they're received. A response object will be returned for each sent activity. For message activities this will contain the id of the delivered message.

Instead of calling these methods directly on the adapter, calling TurnContext.sendActivities() or TurnContext.sendActivity() is the preferred way of sending activities as that will ensure that outgoing activities have been properly addressed and that any interested middleware has been notified.

The primary scenario for calling this method directly is when you want to explicitly bypass going through any middleware. For instance, sending the typing activity might be a good reason to call this method directly as those activities are unlikely to require handling by middleware.

signOutUser(TurnContext, string, string)

Signs the user out with the token server.

function signOutUser(context: TurnContext, connectionName?: string, userId?: string)

Parameters

context
TurnContext

Context for the current turn of conversation with the user.

connectionName
string

Name of the auth connection to use.

userId
string

id of user to sign out.

Returns

Promise<void>

updateActivity(TurnContext, Partial<Activity>)

Replaces an activity that was previously sent to a channel with an updated version.

function updateActivity(context: TurnContext, activity: Partial<Activity>)

Parameters

context
TurnContext

Context for the current turn of conversation with the user.

activity
Partial<Activity>

New activity to replace a current activity with.

Returns

Promise<void>

Remarks

Calling TurnContext.updateActivity() is the preferred way of updating activities (rather than calling it directly from the adapter) as that will ensure that any interested middleware has been notified.

It should be noted that not all channels support this feature.

use((context: TurnContext, next: () => Promise<void>) => Promise | Middleware[])

Registers middleware handlers(s) with the adapter.

function use(middleware: (context: TurnContext, next: () => Promise<void>) => Promise<void> | Middleware[])

Parameters

middleware
(context: TurnContext, next: () => Promise<void>) => Promise<void> | Middleware[]

One or more middleware handlers(s) to register.

Returns

this