TurnContext class

Provides context for a turn of a bot.

Remarks

Context provides information needed to process an incoming activity. The context object is created by a BotAdapter and persists for the length of the turn.

Constructors

TurnContext(BotAdapter, Partial<Activity>)

Creates an new instance of the TurnContext class.

TurnContext(TurnContext)

Creates an new instance of the TurnContext class.

Properties

activity

Gets the activity associated with this turn.

adapter

Gets the bot adapter that created this context object.

bufferedReplyActivities

List of activities to send when context.activity.deliveryMode == 'expectReplies'.

locale

Gets the locale stored in the turnState. Sets the locale stored in the turnState.

responded

Indicates whether the bot has replied to the user this turn. Sets the response flag on the current turn context.

turnState

Gets the services registered on this context object.

Methods

applyConversationReference(Partial<Activity>, Partial<ConversationReference>, boolean)

Updates an activity with the delivery information from an existing conversation reference.

deleteActivity(string | Partial<ConversationReference>)

Asynchronously deletes a previously sent activity.

getConversationReference(Partial<Activity>)

Copies conversation reference information from an activity.

getMentions(Partial<Activity>)

Gets all at-mention entities included in an activity.

getReplyConversationReference(Partial<Activity>, ResourceResponse)

Copies conversation reference information from a resource response for a sent activity.

onDeleteActivity(DeleteActivityHandler)

Adds a response handler for delete activity operations.

onSendActivities(SendActivitiesHandler)

Adds a response handler for send activity operations.

onUpdateActivity(UpdateActivityHandler)

Adds a response handler for update activity operations.

removeMentionText(Partial<Activity>, string)

Removes at mentions for a given ID from the text of an activity and returns the updated text. Use with caution; this function alters the activity's text property.

removeRecipientMention(Partial<Activity>)

Removes at mentions for the activity's recipient from the text of an activity and returns the updated text. Use with caution; this function alters the activity's text property.

sendActivities(Partial<Activity>[])

Asynchronously sends a set of activities to the sender of the incoming activity.

sendActivity(string | Partial<Activity>, string, string)

Asynchronously sends an activity to the sender of the incoming activity.

sendTraceActivity(string, any, string, string)

Asynchronously sends an activity to the sender of the incoming activity.

updateActivity(Partial<Activity>)

Asynchronously updates a previously sent activity.

Constructor Details

TurnContext(BotAdapter, Partial<Activity>)

Creates an new instance of the TurnContext class.

new TurnContext(adapterOrContext: BotAdapter, request: Partial<Activity>)

Parameters

adapterOrContext
BotAdapter

The adapter creating the context.

request

Partial<Activity>

The incoming activity for the turn.

TurnContext(TurnContext)

Creates an new instance of the TurnContext class.

new TurnContext(adapterOrContext: TurnContext)

Parameters

adapterOrContext
TurnContext

The adapter creating the context.

Property Details

activity

Gets the activity associated with this turn.

Activity activity

Property Value

Activity

The activity associated with this turn.

Remarks

This example shows how to get the users trimmed utterance from the activity:

const utterance = (context.activity.text || '').trim();

adapter

Gets the bot adapter that created this context object.

BotAdapter adapter

Property Value

The bot adapter that created this context object.

bufferedReplyActivities

List of activities to send when context.activity.deliveryMode == 'expectReplies'.

bufferedReplyActivities: Partial<Activity>[]

Property Value

Partial<Activity>[]

locale

Gets the locale stored in the turnState. Sets the locale stored in the turnState.

string | undefined locale

Property Value

string | undefined

The locale stored in the turnState.

responded

Indicates whether the bot has replied to the user this turn. Sets the response flag on the current turn context.

boolean responded

Property Value

boolean

True if at least one response was sent for the current turn; otherwise, false.

Remarks

true if at least one response was sent for the current turn; otherwise, false. Use this to determine if your bot needs to run fallback logic after other normal processing.

Trace activities do not set this flag.

for example:

await routeActivity(context);
if (!context.responded) {
   await context.sendActivity(`I'm sorry. I didn't understand.`);
}

turnState

Gets the services registered on this context object.

TurnContextStateCollection turnState

Property Value

The services registered on this context object.

Remarks

Middleware, other components, and services will typically use this to cache information that could be asked for by a bot multiple times during a turn. You can use this cache to pass information between components of your bot.

For example:

const cartKey = Symbol();
const cart = await loadUsersShoppingCart(context);
context.turnState.set(cartKey, cart);

Tip

When creating middleware or a third-party component, use a unique symbol for your cache key to avoid state naming collisions with the bot or other middleware or components.

Method Details

applyConversationReference(Partial<Activity>, Partial<ConversationReference>, boolean)

Updates an activity with the delivery information from an existing conversation reference.

static function applyConversationReference(activity: Partial<Activity>, reference: Partial<ConversationReference>, isIncoming?: boolean): Partial<Activity>

Parameters

activity

Partial<Activity>

The activity to update.

reference

Partial<ConversationReference>

The conversation reference to copy delivery information from.

isIncoming

boolean

Optional. true to treat the activity as an incoming activity, where the bot is the recipient; otherwise, false. Default is false, and the activity will show the bot as the sender.

Returns

Partial<Activity>

This activity, updated with the delivery information.

Remarks

Call the getConversationReference method on an incoming activity to get a conversation reference that you can then use to update an outgoing activity with the correct delivery information.

deleteActivity(string | Partial<ConversationReference>)

Asynchronously deletes a previously sent activity.

function deleteActivity(idOrReference: string | Partial<ConversationReference>): Promise<void>

Parameters

idOrReference

string | Partial<ConversationReference>

ID or conversation reference for the activity to delete.

Returns

Promise<void>

A promise representing the async operation.

Remarks

If an ID is specified, the conversation reference for the current request is used to get the rest of the information needed.

For example:

const matched = /approve (.*)/i.exec(context.activity.text);
if (matched) {
   const savedId = await approveExpenseReport(matched[1]);
   await context.deleteActivity(savedId);
}

See also

getConversationReference(Partial<Activity>)

Copies conversation reference information from an activity.

static function getConversationReference(activity: Partial<Activity>): Partial<ConversationReference>

Parameters

activity

Partial<Activity>

The activity to get the information from.

Returns

Partial<ConversationReference>

A conversation reference for the conversation that contains this activity.

Remarks

You can save the conversation reference as a JSON object and use it later to proactively message the user.

For example:

const reference = TurnContext.getConversationReference(context.request);

See also

getMentions(Partial<Activity>)

Gets all at-mention entities included in an activity.

static function getMentions(activity: Partial<Activity>): Mention[]

Parameters

activity

Partial<Activity>

The activity.

Returns

Mention[]

All the at-mention entities included in an activity.

Remarks

The activity's entities property contains a flat list of metadata objects pertaining to this activity and can contain mention entities. This method returns all such entities for a given activity.

For example:

const mentions = TurnContext.getMentions(turnContext.request);

getReplyConversationReference(Partial<Activity>, ResourceResponse)

Copies conversation reference information from a resource response for a sent activity.

static function getReplyConversationReference(activity: Partial<Activity>, reply: ResourceResponse): Partial<ConversationReference>

Parameters

activity

Partial<Activity>

The sent activity.

reply

ResourceResponse

The resource response for the activity, returned by the sendActivity or sendActivities method.

Returns

Partial<ConversationReference>

A ConversationReference that can be stored and used later to delete or update the activity.

Remarks

You can save the conversation reference as a JSON object and use it later to update or delete the message.

For example:

var reply = await context.sendActivity('Hi');
var reference = TurnContext.getReplyConversationReference(context.activity, reply);

See also

onDeleteActivity(DeleteActivityHandler)

Adds a response handler for delete activity operations.

function onDeleteActivity(handler: DeleteActivityHandler): this

Parameters

handler
DeleteActivityHandler

The handler to add to the context object.

Returns

this

The updated context object.

Remarks

This method returns a reference to the turn context object.

When the deleteActivity method is called, the registered handlers are called in the order in which they were added to the context object before the activity is deleted.

This example shows how to listen for and log activity deletions.

context.onDeleteActivity(async (ctx, reference, next) => {
   // Delete activity
   await next();

   // Log delete
   logDelete(activity);
});

onSendActivities(SendActivitiesHandler)

Adds a response handler for send activity operations.

function onSendActivities(handler: SendActivitiesHandler): this

Parameters

handler
SendActivitiesHandler

The handler to add to the context object.

Returns

this

The updated context object.

Remarks

This method returns a reference to the turn context object.

When the sendActivity or sendActivities method is called, the registered handlers are called in the order in which they were added to the context object before the activities are sent.

This example shows how to listen for and log outgoing message activities.

context.onSendActivities(async (ctx, activities, next) => {
   // Log activities before sending them.
   activities.filter(a => a.type === 'message').forEach(a => logSend(a));

   // Allow the send process to continue.
   next();
});

onUpdateActivity(UpdateActivityHandler)

Adds a response handler for update activity operations.

function onUpdateActivity(handler: UpdateActivityHandler): this

Parameters

handler
UpdateActivityHandler

The handler to add to the context object.

Returns

this

The updated context object.

Remarks

This method returns a reference to the turn context object.

When the updateActivity method is called, the registered handlers are called in the order in which they were added to the context object before the activity is updated.

This example shows how to listen for and log activity updates.

context.onUpdateActivity(async (ctx, activity, next) => {
   // Replace activity
   await next();

   // Log update
   logUpdate(activity);
});

removeMentionText(Partial<Activity>, string)

Removes at mentions for a given ID from the text of an activity and returns the updated text. Use with caution; this function alters the activity's text property.

static function removeMentionText(activity: Partial<Activity>, id: string): string

Parameters

activity

Partial<Activity>

The activity to remove at mentions from.

id

string

The ID of the user or bot to remove at mentions for.

Returns

string

The updated activity's text.

Remarks

Some channels, for example Microsoft Teams, add at mentions to the text of a message activity.

Use this helper method to modify the activity's text property. It removes all at mentions for the given bot or user ID and then returns the updated property value.

For example, when you remove mentions of echoBot from an activity containing the text "@echoBot Hi Bot", the activity text is updated, and the method returns "Hi Bot".

The format of a mention entity is channel-dependent. However, the mention's text property should contain the exact text for the user as it appears in the activity text.

For example, whether the channel uses "username" or "@username", this string is in the activity's text, and this method will remove all occurrences of that string from the text.

For example:

const updatedText = TurnContext.removeMentionText(activity, activity.recipient.id);

See also

removeRecipientMention(Partial<Activity>)

Removes at mentions for the activity's recipient from the text of an activity and returns the updated text. Use with caution; this function alters the activity's text property.

static function removeRecipientMention(activity: Partial<Activity>): string

Parameters

activity

Partial<Activity>

The activity to remove at mentions from.

Returns

string

The updated activity's text.

Remarks

Some channels, for example Microsoft Teams, add at-mention details to the text of a message activity.

Use this helper method to modify the activity's text property. It removes all at mentions of the activity's recipient and then returns the updated property value.

For example:

const updatedText = TurnContext.removeRecipientMention(turnContext.request);

See also

sendActivities(Partial<Activity>[])

Asynchronously sends a set of activities to the sender of the incoming activity.

function sendActivities(activities: Partial<Activity>[]): Promise<ResourceResponse[]>

Parameters

activities

Partial<Activity>[]

The activities to send.

Returns

Promise<ResourceResponse[]>

A promise with a ResourceResponse.

Remarks

If the activities are successfully sent, results in an array of ResourceResponse objects containing the IDs that the receiving channel assigned to the activities.

Before they are sent, the delivery information of each outbound activity is updated based on the delivery information of the inbound inbound activity.

For example:

await context.sendActivities([
   { type: 'typing' },
   { type: 'delay', value: 2000 },
   { type: 'message', text: 'Hello... How are you?' }
]);

See also

sendActivity(string | Partial<Activity>, string, string)

Asynchronously sends an activity to the sender of the incoming activity.

function sendActivity(activityOrText: string | Partial<Activity>, speak?: string, inputHint?: string): Promise<ResourceResponse | undefined>

Parameters

activityOrText

string | Partial<Activity>

The activity or text to send.

speak

string

Optional. The text to be spoken by your bot on a speech-enabled channel.

inputHint

string

Optional. Indicates whether your bot is accepting, expecting, or ignoring user input after the message is delivered to the client. One of: 'acceptingInput', 'ignoringInput', or 'expectingInput'. Default is 'acceptingInput'.

Returns

Promise<ResourceResponse | undefined>

A promise with a ResourceResponse.

Remarks

If the activity is successfully sent, results in a ResourceResponse object containing the ID that the receiving channel assigned to the activity.

See the channel's documentation for limits imposed upon the contents of the activityOrText parameter.

To control various characteristics of your bot's speech such as voice, rate, volume, pronunciation, and pitch, specify speak in Speech Synthesis Markup Language (SSML) format.

For example:

await context.sendActivity(`Hello World`);

See also

sendTraceActivity(string, any, string, string)

Asynchronously sends an activity to the sender of the incoming activity.

function sendTraceActivity(name: string, value?: any, valueType?: string, label?: string): Promise<ResourceResponse | undefined>

Parameters

name

string

The activity or text to send.

value

any

Optional. The text to be spoken by your bot on a speech-enabled channel.

valueType

string

Optional. Indicates whether your bot is accepting, expecting, or ignoring user

label

string

Optional. Indicates whether your bot is accepting, expecting, or ignoring user

Returns

Promise<ResourceResponse | undefined>

A promise with a ResourceResponse.

Remarks

Creates and sends a Trace activity. Trace activities are only sent when the channel is the emulator.

For example:

await context.sendTraceActivity(`The following exception was thrown ${msg}`);

See also

updateActivity(Partial<Activity>)

Asynchronously updates a previously sent activity.

function updateActivity(activity: Partial<Activity>): Promise<ResourceResponse | void>

Parameters

activity

Partial<Activity>

The replacement for the original activity.

Returns

Promise<ResourceResponse | void>

A promise with a ResourceResponse.

Remarks

The id of the replacement activity indicates the activity in the conversation to replace.

For example:

const matched = /approve (.*)/i.exec(context.activity.text);
if (matched) {
   const update = await approveExpenseReport(matched[1]);
   await context.updateActivity(update);
}

See also