Freigeben über


@microsoft/teamsfx package

Classes

BotSsoExecutionDialog

Sso execution dialog, use to handle sso command

CardActionBot

A card action bot to respond to adaptive card universal actions.

Channel

A NotificationTarget that represents a team channel.

CommandBot

A command bot for receiving commands and sending responses in Teams.

ConversationBot

Provide utilities for bot conversation, including:

  • handle command and response.
  • send notification to varies targets (e.g., member, group, channel).

Example

For command and response, you can register your commands through the constructor, or use the registerCommand and registerCommands API to add commands later.

import { BotBuilderCloudAdapter } from "@microsoft/teamsfx";
import ConversationBot = BotBuilderCloudAdapter.ConversationBot;

// register through constructor
const conversationBot = new ConversationBot({
  command: {
    enabled: true,
    commands: [ new HelloWorldCommandHandler() ],
  },
});

// register through `register*` API
conversationBot.command.registerCommand(new HelpCommandHandler());

For notification, you can enable notification at initialization, then send notifications at any time.

import { BotBuilderCloudAdapter } from "@microsoft/teamsfx";
import ConversationBot = BotBuilderCloudAdapter.ConversationBot;

// enable through constructor
const conversationBot = new ConversationBot({
  notification: {
    enabled: true,
  },
});

// get all bot installations and send message
for (const target of await conversationBot.notification.installations()) {
  await target.sendMessage("Hello Notification");
}

// alternative - send message to all members
for (const target of await conversationBot.notification.installations()) {
  for (const member of await target.members()) {
    await member.sendMessage("Hello Notification");
  }
}
Member

A NotificationTarget that represents a team member.

NotificationBot

Provide utilities to send notification to varies targets (e.g., member, group, channel).

TeamsBotInstallation

A NotificationTarget that represents a bot installation. Teams Bot could be installed into

  • Personal chat
  • Group chat
  • Team (by default the General channel)
ApiKeyProvider

Provider that handles API Key authentication

AppCredential

Represent Microsoft 365 tenant identity, and it is usually used when user is not involved like time-triggered automation job.

Example

loadConfiguration(); // load configuration from environment variables
const credential = new AppCredential();
BasicAuthProvider

Provider that handles Basic authentication

BearerTokenAuthProvider

Provider that handles Bearer Token authentication

BotSsoExecutionDialog

Sso execution dialog, use to handle sso command

CardActionBot
CertificateAuthProvider

Provider that handles Certificate authentication

Channel

A NotificationTarget that represents a team channel.

CommandBot
ConversationBot
ErrorWithCode

Error class with code and message thrown by the SDK.

InvokeResponseFactory

Provides methods for formatting various invoke responses a bot can send to respond to an invoke request.

Member

A NotificationTarget that represents a team member.

MessageBuilder

Provides utility method to build bot message with cards that supported in Teams.

MsGraphAuthProvider

Microsoft Graph auth provider for Teams Framework

NotificationBot
OnBehalfOfUserCredential

Represent on-behalf-of flow to get user identity, and it is designed to be used in server side.

Example

const credential = new OnBehalfOfUserCredential(ssoToken);
TeamsBotInstallation
TeamsBotSsoPrompt

Creates a new prompt that leverage Teams Single Sign On (SSO) support for bot to automatically sign in user and help receive oauth token, asks the user to consent if needed.

Example

When used with your bots DialogSet you can simply add a new instance of the prompt as a named dialog using DialogSet.add(). You can then start the prompt from a waterfall step using either DialogContext.beginDialog() or DialogContext.prompt(). The user will be prompted to sign in as needed and their access token will be passed as an argument to the callers next waterfall step:

const { ConversationState, MemoryStorage } = require('botbuilder');
const { DialogSet, WaterfallDialog } = require('botbuilder-dialogs');
const { TeamsBotSsoPrompt } = require('@microsoft/teamsfx');

const convoState = new ConversationState(new MemoryStorage());
const dialogState = convoState.createProperty('dialogState');
const dialogs = new DialogSet(dialogState);

dialogs.add(new TeamsBotSsoPrompt('TeamsBotSsoPrompt', {
   scopes: ["User.Read"],
}));

dialogs.add(new WaterfallDialog('taskNeedingLogin', [
     async (step) => {
         return await step.beginDialog('TeamsBotSsoPrompt');
     },
     async (step) => {
         const token = step.result;
         if (token) {

             // ... continue with task needing access token ...

         } else {
             await step.context.sendActivity(`Sorry... We couldn't log you in. Try again later.`);
             return await step.endDialog();
         }
     }
]));
TeamsFx

A class providing credential and configuration.

TeamsUserCredential

Represent Teams current user's identity, and it is used within Teams client applications.

Interfaces

ConversationOptions

Options to initialize ConversationBot

NotificationOptions

Options to initialize NotificationBot.

AuthProvider

Defines method that injects authentication info to http requests

AuthenticationConfiguration

Authentication related configuration.

AxiosInstance
BotSsoConfig

Interface for SSO configuration for Bot SSO

BotSsoExecutionActivityHandler

Interface for user to customize SSO execution activity handler

CardActionOptions

Options to initialize CardActionBot.

CommandMessage

Interface for a command message that can handled in a command handler.

CommandOptions

Options to initialize CommandBot.

ConversationOptions

Options to initialize ConversationBot

ConversationReferenceStore

A store to persist notification target references.

ConversationReferenceStoreAddOptions

Options to add a conversation reference to the store.

GetTeamsUserTokenOptions
Logger

Interface for customized logger.

MessageExtensionTokenResponse

Token response provided by Teams Bot SSO prompt

NotificationOptions

Options to initialize NotificationBot.

NotificationTarget

Represent a notification target.

NotificationTargetStorage

Interface for a storage provider that stores and retrieves notification target references.

PagedData

Represents a page of data.

TeamsBotSsoPromptSettings

Settings used to configure an TeamsBotSsoPrompt instance.

TeamsBotSsoPromptTokenResponse

Token response provided by Teams Bot SSO prompt

TeamsFxAdaptiveCardActionHandler

Interface for adaptive card action handler that can process card action invoke and return a response.

TeamsFxBotCommandHandler

Interface for a command handler that can process command to a TeamsFx bot and return a response.

TeamsFxBotSsoCommandHandler

Interface for a command handler that can process sso command to a TeamsFx bot and return a response.

UserInfo

UserInfo with user displayName, objectId and preferredUserName.

Type Aliases

AppCredentialAuthConfig

Authentication configuration for AppCredential used in node environment

BotSsoExecutionDialogHandler
LogFunction

Log function for customized logging.

OnBehalfOfCredentialAuthConfig

Authentication configuration for OnBehalfOfCredential used in node environment

TeamsUserCredentialAuthConfig

Authentication configuration for TeamsUserCredential used in browser environment

TriggerPatterns

The trigger pattern used to trigger a TeamsFxBotCommandHandler instance.

Enums

SearchScope

The search scope when calling findMember and findAllMembers. The search scope is a flagged enum and it can be combined with |. For example, to search from personal chat and group chat, use SearchScope.Person | SearchScope.Group.

AdaptiveCardResponse

Options used to control how the response card will be sent to users.

ApiKeyLocation

Define available location for API Key location

ErrorCode

Error code to trace the error types.

IdentityType

Identity type to use in authentication.

InvokeResponseErrorCode

Status code for an application/vnd.microsoft.error invoke response.

LogLevel

Log level.

NotificationTargetType

The target type where the notification will be sent to.

SearchScope

The search scope when calling findMember and findAllMembers. The search scope is a flagged enum and it can be combined with |. For example, to search from personal chat and group chat, use SearchScope.Person | SearchScope.Group.

Functions

createApiClient(string, AuthProvider)

Initializes new Axios instance with specific auth provider

Example

const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
createMicrosoftGraphClient(TeamsFxConfiguration, string | string[])

Get Microsoft graph client.

Example

Get Microsoft graph client by TokenCredential

// Sso token example (Azure Function)
const ssoToken = "YOUR_TOKEN_STRING";
const options = {"AAD_APP_ID", "AAD_APP_SECRET"};
const credential = new OnBehalfOfAADUserCredential(ssoToken, options);
const graphClient = await createMicrosoftGraphClient(credential);
const profile = await graphClient.api("/me").get();

// TeamsBotSsoPrompt example (Bot Application)
const requiredScopes = ["User.Read"];
const config: Configuration = {
   loginUrl: loginUrl,
   clientId: clientId,
   clientSecret: clientSecret,
   tenantId: tenantId
};
const prompt = new TeamsBotSsoPrompt(dialogId, {
   config: config
   scopes: ["User.Read"],
});
this.addDialog(prompt);

const oboCredential = new OnBehalfOfAADUserCredential(
 getUserId(dialogContext),
 {
   clientId: "AAD_APP_ID",
   clientSecret: "AAD_APP_SECRET"
 });
try {
   const graphClient = await createMicrosoftGraphClient(credential);
   const profile = await graphClient.api("/me").get();
} catch (e) {
   dialogContext.beginDialog(dialogId);
   return Dialog.endOfTurn();
}
createMicrosoftGraphClientWithCredential(TokenCredential, string | string[])

Get Microsoft graph client.

Example

Get Microsoft graph client by TokenCredential

// In browser: TeamsUserCredential
const authConfig: TeamsUserCredentialAuthConfig = {
  clientId: "xxx",
initiateLoginEndpoint: "https://xxx/auth-start.html",
};

const credential = new TeamsUserCredential(authConfig);

const scope = "User.Read";
await credential.login(scope);

const client = createMicrosoftGraphClientWithCredential(credential, scope);

// In node: OnBehalfOfUserCredential
const oboAuthConfig: OnBehalfOfCredentialAuthConfig = {
  authorityHost: "xxx",
  clientId: "xxx",
  tenantId: "xxx",
  clientSecret: "xxx",
};

const oboCredential = new OnBehalfOfUserCredential(ssoToken, oboAuthConfig);
const scope = "User.Read";
const client = createMicrosoftGraphClientWithCredential(oboCredential, scope);

// In node: AppCredential
const appAuthConfig: AppCredentialAuthConfig = {
  authorityHost: "xxx",
  clientId: "xxx",
  tenantId: "xxx",
  clientSecret: "xxx",
};
const appCredential = new AppCredential(appAuthConfig);
const scope = "User.Read";
const client = createMicrosoftGraphClientWithCredential(appCredential, scope);

const profile = await client.api("/me").get();
createPemCertOption(string | Buffer, string | Buffer, { ca?: string | Buffer, passphrase?: string })

Helper to create SecureContextOptions from PEM format cert

createPfxCertOption(string | Buffer, { passphrase?: string })

Helper to create SecureContextOptions from PFX format cert

getLogLevel()

Get log level.

getTediousConnectionConfig(TeamsFx, string)

Generate connection configuration consumed by tedious.

handleMessageExtensionLinkQueryWithSSO(TurnContext, OnBehalfOfCredentialAuthConfig, string, string | string[], (token: MessageExtensionTokenResponse) => Promise<any>)

Users execute link query in message extension with SSO or access token.

handleMessageExtensionQueryWithSSO(TurnContext, OnBehalfOfCredentialAuthConfig, string, string | string[], (token: MessageExtensionTokenResponse) => Promise<any>)

Users execute query in message extension with SSO or access token.

handleMessageExtensionQueryWithToken(TurnContext, null | AuthenticationConfiguration, string | string[], (token: MessageExtensionTokenResponse) => Promise<any>)

Users execute query in message extension with SSO or access token.

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

Send an adaptive card message to a notification target.

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

Send a plain text message to a notification target.

setLogFunction(LogFunction)

Set custom log function. Use the function if it's set. Priority is lower than setLogger.

Example

setLogFunction((level: LogLevel, message: string) => {
  if (level === LogLevel.Error) {
    console.log(message);
  }
});
setLogLevel(LogLevel)

Update log level helper.

setLogger(Logger)

Set custom logger. Use the output functions if it's set. Priority is higher than setLogFunction.

Example

setLogger({
  verbose: console.debug,
  info: console.info,
  warn: console.warn,
  error: console.error,
});

Function Details

createApiClient(string, AuthProvider)

Initializes new Axios instance with specific auth provider

Example

const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
function createApiClient(apiEndpoint: string, authProvider: AuthProvider): AxiosInstance

Parameters

apiEndpoint

string

Base url of the API

authProvider
AuthProvider

Auth provider that injects authentication info to each request

Returns

axios instance configured with specfic auth provider

createMicrosoftGraphClient(TeamsFxConfiguration, string | string[])

Warning

This API is now deprecated.

Use TokenCredentialAuthenticationProvider and Client.initWithMiddleware instead.

const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: scope });
const graph = Client.initWithMiddleware({
  authProvider: authProvider,
});

Get Microsoft graph client.

Example

Get Microsoft graph client by TokenCredential

// Sso token example (Azure Function)
const ssoToken = "YOUR_TOKEN_STRING";
const options = {"AAD_APP_ID", "AAD_APP_SECRET"};
const credential = new OnBehalfOfAADUserCredential(ssoToken, options);
const graphClient = await createMicrosoftGraphClient(credential);
const profile = await graphClient.api("/me").get();

// TeamsBotSsoPrompt example (Bot Application)
const requiredScopes = ["User.Read"];
const config: Configuration = {
   loginUrl: loginUrl,
   clientId: clientId,
   clientSecret: clientSecret,
   tenantId: tenantId
};
const prompt = new TeamsBotSsoPrompt(dialogId, {
   config: config
   scopes: ["User.Read"],
});
this.addDialog(prompt);

const oboCredential = new OnBehalfOfAADUserCredential(
 getUserId(dialogContext),
 {
   clientId: "AAD_APP_ID",
   clientSecret: "AAD_APP_SECRET"
 });
try {
   const graphClient = await createMicrosoftGraphClient(credential);
   const profile = await graphClient.api("/me").get();
} catch (e) {
   dialogContext.beginDialog(dialogId);
   return Dialog.endOfTurn();
}
function createMicrosoftGraphClient(teamsfx: TeamsFxConfiguration, scopes?: string | string[]): Client

Parameters

teamsfx

TeamsFxConfiguration

Used to provide configuration and auth.

scopes

string | string[]

The array of Microsoft Token scope of access. Default value is [.default].

Returns

Client

Graph client with specified scopes.

createMicrosoftGraphClientWithCredential(TokenCredential, string | string[])

Warning

This API is now deprecated.

Use TokenCredentialAuthenticationProvider and Client.initWithMiddleware instead.

const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: scope });
const graph = Client.initWithMiddleware({
  authProvider: authProvider,
});

Get Microsoft graph client.

Example

Get Microsoft graph client by TokenCredential

// In browser: TeamsUserCredential
const authConfig: TeamsUserCredentialAuthConfig = {
  clientId: "xxx",
initiateLoginEndpoint: "https://xxx/auth-start.html",
};

const credential = new TeamsUserCredential(authConfig);

const scope = "User.Read";
await credential.login(scope);

const client = createMicrosoftGraphClientWithCredential(credential, scope);

// In node: OnBehalfOfUserCredential
const oboAuthConfig: OnBehalfOfCredentialAuthConfig = {
  authorityHost: "xxx",
  clientId: "xxx",
  tenantId: "xxx",
  clientSecret: "xxx",
};

const oboCredential = new OnBehalfOfUserCredential(ssoToken, oboAuthConfig);
const scope = "User.Read";
const client = createMicrosoftGraphClientWithCredential(oboCredential, scope);

// In node: AppCredential
const appAuthConfig: AppCredentialAuthConfig = {
  authorityHost: "xxx",
  clientId: "xxx",
  tenantId: "xxx",
  clientSecret: "xxx",
};
const appCredential = new AppCredential(appAuthConfig);
const scope = "User.Read";
const client = createMicrosoftGraphClientWithCredential(appCredential, scope);

const profile = await client.api("/me").get();
function createMicrosoftGraphClientWithCredential(credential: TokenCredential, scopes?: string | string[]): Client

Parameters

credential
TokenCredential

Used to provide configuration and auth.

scopes

string | string[]

The array of Microsoft Token scope of access. Default value is [.default].

Returns

Client

Graph client with specified scopes.

createPemCertOption(string | Buffer, string | Buffer, { ca?: string | Buffer, passphrase?: string })

Helper to create SecureContextOptions from PEM format cert

function createPemCertOption(cert: string | Buffer, key: string | Buffer, options?: { ca?: string | Buffer, passphrase?: string }): SecureContextOptions

Parameters

cert

string | Buffer

The cert chain in PEM format

key

string | Buffer

The private key for the cert chain

options

{ ca?: string | Buffer, passphrase?: string }

Optional settings when create the cert options.

Returns

SecureContextOptions

Instance of SecureContextOptions

createPfxCertOption(string | Buffer, { passphrase?: string })

Helper to create SecureContextOptions from PFX format cert

function createPfxCertOption(pfx: string | Buffer, options?: { passphrase?: string }): SecureContextOptions

Parameters

pfx

string | Buffer

The content of .pfx file

options

{ passphrase?: string }

Optional settings when create the cert options.

Returns

SecureContextOptions

Instance of SecureContextOptions

getLogLevel()

Get log level.

function getLogLevel(): LogLevel | undefined

Returns

LogLevel | undefined

Log level

getTediousConnectionConfig(TeamsFx, string)

Warning

This API is now deprecated.

we recommend you compose your own Tedious configuration for better flexibility.

Generate connection configuration consumed by tedious.

function getTediousConnectionConfig(teamsfx: TeamsFx, databaseName?: string): Promise<ConnectionConfig>

Parameters

teamsfx
TeamsFx

Used to provide configuration and auth

databaseName

string

specify database name to override default one if there are multiple databases.

Returns

Promise<ConnectionConfig>

Connection configuration of tedious for the SQL.

handleMessageExtensionLinkQueryWithSSO(TurnContext, OnBehalfOfCredentialAuthConfig, string, string | string[], (token: MessageExtensionTokenResponse) => Promise<any>)

Users execute link query in message extension with SSO or access token.

function handleMessageExtensionLinkQueryWithSSO(context: TurnContext, config: OnBehalfOfCredentialAuthConfig, initiateLoginEndpoint: string, scopes: string | string[], logic: (token: MessageExtensionTokenResponse) => Promise<any>): Promise<void | MessagingExtensionResponse>

Parameters

context

TurnContext

The context object for the current turn.

config
OnBehalfOfCredentialAuthConfig

User custom the message extension authentication configuration.

initiateLoginEndpoint

string

Login page for Teams to redirect to.

scopes

string | string[]

The list of scopes for which the token will have access.

logic

(token: MessageExtensionTokenResponse) => Promise<any>

Business logic when executing the link query in message extension with SSO or access token.

Returns

Promise<void | MessagingExtensionResponse>

A MessageExtension Response for the activity. If the logic not return any, return void instead.

handleMessageExtensionQueryWithSSO(TurnContext, OnBehalfOfCredentialAuthConfig, string, string | string[], (token: MessageExtensionTokenResponse) => Promise<any>)

Users execute query in message extension with SSO or access token.

function handleMessageExtensionQueryWithSSO(context: TurnContext, config: OnBehalfOfCredentialAuthConfig, initiateLoginEndpoint: string, scopes: string | string[], logic: (token: MessageExtensionTokenResponse) => Promise<any>): Promise<void | MessagingExtensionResponse>

Parameters

context

TurnContext

The context object for the current turn.

config
OnBehalfOfCredentialAuthConfig

User custom the message extension authentication configuration.

initiateLoginEndpoint

string

Login page for Teams to redirect to.

scopes

string | string[]

The list of scopes for which the token will have access.

logic

(token: MessageExtensionTokenResponse) => Promise<any>

Business logic when executing the query in message extension with SSO or access token.

Returns

Promise<void | MessagingExtensionResponse>

A MessageExtension Response for the activity. If the logic not return any, return void instead.

handleMessageExtensionQueryWithToken(TurnContext, null | AuthenticationConfiguration, string | string[], (token: MessageExtensionTokenResponse) => Promise<any>)

Warning

This API is now deprecated.

Use handleMessageExtensionQueryWithSSO instead.

Users execute query in message extension with SSO or access token.

function handleMessageExtensionQueryWithToken(context: TurnContext, config: null | AuthenticationConfiguration, scopes: string | string[], logic: (token: MessageExtensionTokenResponse) => Promise<any>): Promise<MessagingExtensionResponse | void>

Parameters

context

TurnContext

The context object for the current turn.

config

null | AuthenticationConfiguration

User custom the message extension authentication configuration.

scopes

string | string[]

The list of scopes for which the token will have access.

logic

(token: MessageExtensionTokenResponse) => Promise<any>

Business logic when executing the query in message extension with SSO or access token.

Returns

Promise<MessagingExtensionResponse | void>

A MessageExtension Response for the activity. If the logic not return any, return void instead.

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

Send an adaptive card message to a notification target.

function sendAdaptiveCard(target: NotificationTarget, card: unknown, onError?: (context: TurnContext, error: Error) => Promise<void>): Promise<MessageResponse>

Parameters

target
NotificationTarget

the notification target.

card

unknown

the adaptive card raw JSON.

onError

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

an optional error handler that can catch exceptions during adaptive card sending. If not defined, error will be handled by BotAdapter.onTurnError.

Returns

Promise<MessageResponse>

the response of sending adaptive card message.

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

Send a plain text message to a notification target.

function sendMessage(target: NotificationTarget, text: string, onError?: (context: TurnContext, error: Error) => Promise<void>): Promise<MessageResponse>

Parameters

target
NotificationTarget

the notification target.

text

string

the plain text message.

onError

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

an optional error handler that can catch exceptions during message sending. If not defined, error will be handled by BotAdapter.onTurnError.

Returns

Promise<MessageResponse>

the response of sending message.

setLogFunction(LogFunction)

Set custom log function. Use the function if it's set. Priority is lower than setLogger.

Example

setLogFunction((level: LogLevel, message: string) => {
  if (level === LogLevel.Error) {
    console.log(message);
  }
});
function setLogFunction(logFunction?: LogFunction)

Parameters

logFunction
LogFunction

custom log function. If it's undefined, custom log function will be cleared.

setLogLevel(LogLevel)

Update log level helper.

function setLogLevel(level: LogLevel)

Parameters

level
LogLevel

log level in configuration

setLogger(Logger)

Set custom logger. Use the output functions if it's set. Priority is higher than setLogFunction.

Example

setLogger({
  verbose: console.debug,
  info: console.info,
  warn: console.warn,
  error: console.error,
});
function setLogger(logger?: Logger)

Parameters

logger
Logger

custom logger. If it's undefined, custom logger will be cleared.