Compartilhar via


@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

CertificateAuthProvider

Provider that handles Certificate authentication

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.

MessageBuilder

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

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);
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();
         }
     }
]));
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

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.

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

NotificationTarget

Represent a notification target.

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.

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.

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"));
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.

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.

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

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

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.

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.