UniversalBot class
Manages your bots conversations with users across multiple channels.
- Extends
Constructors
Universal |
Creates a new instance of the UniversalBot. |
Universal |
Creates a new instance of the UniversalBot. |
Universal |
Creates a new instance of the UniversalBot. |
Properties
name | The libraries unique namespace. This is used to issolate the libraries dialogs and localized prompts. |
Route |
Supported routeType values returned by default from findRoutes(). |
Methods
add |
Helper method called from the various route finding methods to manage adding a candidate route to the result set.
|
begin |
Proactively starts a new dialog with the user. Any current conversation between the bot and user will be replaced with a new dialog stack. |
begin |
Registers a global action that will start another dialog anytime it's triggered. The new dialog will be pushed onto the stack so it does not automatically end any current task. The current task will be continued once the new dialog ends. The built-in prompts will automatically re-prompt the user once this happens but that behaviour can be disabled by setting the promptAfterAction flag when calling a built-in prompt. |
best |
Finds the best route to use within a result set containing multiple ambiguous routes. The following disambigution strategy will be used:
|
clone(Universal |
Returns a clone of an existing bot. |
connector(string, IConnector) | Registers or returns a connector for a specific channel. |
custom |
Registers a custom global action that will call the passed in onSelectAction handler when triggered. |
dialog(string, Dialog | IDialog |
Registers or returns a dialog from the library. |
end |
Registers a global action that will end the conversation with the user when triggered. |
find |
Gets the active dialogs confidence that it understands the current message. The dialog must be a member of the current library, otherwise a score of 0.0 will be returned. |
find |
Searches the library and all of its dependencies for a specific dialog. Returns the dialog if found, otherwise null. |
find |
Searches the library to see if any global actions have been triggered. |
find |
Searches for candidate routes to handle the current message. To actually initiate the
handling of the message you should call selectRoute() with one of the
returned results.
The default search logic can be overriden using onFindRoute() and only the
current library is searched so you should call |
find |
Searches the sessions dialog stack to see if any actions have been triggered. |
for |
Enumerates all of the libraries dialogs. |
for |
Enumerates all of the libraries child libraries. The caller should take appropriate steps to avoid circular references when enumerating the hierarchy. In most cases calling libraryList() is a better choice as it already contains logic to avoid cycles. |
get(string) | Returns the current value of a setting. |
is |
Returns information about when the last turn between the user and a bot occured. This can be called before beginDialog to determine if the user is currently in a conversation with the bot. |
library(Library | string) | Registers or returns a library dependency. |
library |
Returns a list of unique libraries within the hierarchy. Should be called on the root of the library hierarchy and avoids cycles created when two child libraries reference the same dependent library. |
load |
Loads a session object for an arbitrary address. |
locale |
Gets or sets the path to the libraries "/locale/" folder containing its localized prompts. The prompts for the library should be stored in a "/locale/<IETF_TAG>/.json" file under this path where "<IETF_TAG>" representes the 2-3 digit language tage for the locale and "" is a filename matching the libraries namespace. |
on(string, (data: any) => void) | Registers an event listener. The bot will emit its own events as it processes incoming and outgoing messages. It will also forward activity related events emitted from the connector, giving you one place to listen for all activity from your bot. The flow of events from the bot is as follows: Message ReceivedWhen the bot receives a new message it will emit the following events in order:
Any receive middleware that's been installed will be executed between the 'receive' and 'incoming' events. After the 'routing' event is emitted any botbuilder middleware will be executed prior to dispatching the message to the bots active dialog. Connector Activity ReceivedConnectors can emit activity events to signal things like a user is typing or that they friended a bot. These activities get routed through middleware like messages but they are not routed through the bots dialog system. They are only ever emitted as events. The flow of connector events is:
Message sentBots can send multiple messages so the session will batch up all outgoing message and then save the bots current state before delivering the sent messages. You'll see a single 'saveStorageData' event emitted and then for every outgoing message in the batch you'll see the following sequence of events:
Any send middleware that's been installed will be executed between the 'send' and 'outgoing' events. |
on |
Replaces the bots default route disambiguation logic with a custom implementation. |
on |
Replaces findRoutes() default route searching logic with a custom implementation. |
on |
Replaces the default logic for selectRoute() with a custom implementation. |
receive(IEvent | IEvent[], (err: Error) => void) | Called when a new event is received. This can be called manually to mimic the bot receiving a message from the user. |
recognize(IRecognize |
Attempts to match a users text utterance to an intent using the libraries recognizers. See IIntentRecognizer.recognize() for details. |
recognizer(IIntent |
Adds a new recognizer plugin to the library. |
select |
Routes the current message to the active dialog. |
select |
Routes the current message to a triggered global action. |
select |
Triggers the handling of the current message using the selected route. The default logic can be overriden using onSelectRoute(). |
select |
Routes the current message to a triggered stack action. |
send(IIs |
Sends a message to the user without disrupting the current conversations dialog stack. |
set(string, any) | Sets a setting on the bot. |
use(IMiddleware |
Installs middleware for the bot. Middleware lets you intercept incoming and outgoing events/messages. |
Constructor Details
UniversalBot(IConnector, any, string)
Creates a new instance of the UniversalBot.
new UniversalBot(connector?: IConnector, defaultDialog?: any, libraryName?: string)
Parameters
- connector
- IConnector
(Optional) the default connector to use for requests. If there's not a more specific connector registered for a channel then this connector will be used./**
- defaultDialog
-
any
(Optional) default handler of received messages. This can either be an individual function or a waterfall sequence.
- libraryName
-
string
(Optional) library namespace for the bot. The default value is '*'.
UniversalBot(IConnector, IDialogWaterfallStep | IDialogWaterfallStep[], string)
Creates a new instance of the UniversalBot.
new UniversalBot(connector: IConnector, defaultDialog?: IDialogWaterfallStep | IDialogWaterfallStep[], libraryName?: string)
Parameters
- connector
- IConnector
(Optional) the default connector to use for requests. If there's not a more specific connector registered for a channel then this connector will be used./**
- defaultDialog
(Optional) default handler of received messages. This can either be an individual function or a waterfall sequence.
- libraryName
-
string
(Optional) library namespace for the bot. The default value is '*'.
UniversalBot(IConnector, IUniversalBotSettings)
Creates a new instance of the UniversalBot.
new UniversalBot(connector: IConnector, settings?: IUniversalBotSettings)
Parameters
- connector
- IConnector
(Optional) the default connector to use for requests. If there's not a more specific connector registered for a channel then this connector will be used./**
- settings
- IUniversalBotSettings
Property Details
name
The libraries unique namespace. This is used to issolate the libraries dialogs and localized prompts.
name: string
Property Value
string
RouteTypes
Supported routeType values returned by default from findRoutes().
static RouteTypes: Object
Property Value
Object
Method Details
addRouteResult(IRouteResult, IRouteResult[])
Helper method called from the various route finding methods to manage adding a candidate route to the result set.
- If the score is greater then the current best match in the set a new result set will be returned containing just the new match.
- If the score is equal to the current best match it will be added to the existing set.
- If the score is less than the current best match it will be ignored.
static function addRouteResult(route: IRouteResult, current?: IRouteResult[])
Parameters
- route
- IRouteResult
The candidate route to add to the set.
- current
(Optional) result set to add the route too. If missing then a new set with just the route will be returned.
Returns
beginDialog(IAddress, string, any, (err: Error) => void)
Proactively starts a new dialog with the user. Any current conversation between the bot and user will be replaced with a new dialog stack.
function beginDialog(address: IAddress, dialogId: string, dialogArgs?: any, done?: (err: Error) => void)
Parameters
- address
- IAddress
Address of the user to start a new conversation with. This should be saved during a previous conversation with the user. Any existing conversation or dialog will be immediately terminated.
- dialogId
-
string
ID of the dialog to begin.
- dialogArgs
-
any
(Optional) arguments to pass to dialog.
- done
-
(err: Error) => void
(Optional) function to invoke once the operation is completed.
beginDialogAction(string, string, IDialogActionOptions)
Registers a global action that will start another dialog anytime it's triggered. The new dialog will be pushed onto the stack so it does not automatically end any current task. The current task will be continued once the new dialog ends. The built-in prompts will automatically re-prompt the user once this happens but that behaviour can be disabled by setting the promptAfterAction flag when calling a built-in prompt.
function beginDialogAction(name: string, id: string, options?: IDialogActionOptions)
Parameters
- name
-
string
Unique name to assign the action.
- id
-
string
ID of the dialog to start.
- options
- IDialogActionOptions
(Optional) options used to configure the action. If matches is specified the action will listen for the user to say a word or phrase that triggers the action, otherwise the action needs to be bound to a button using CardAction.dialogAction() to trigger the action. You can also use dialogArgs to pass additional params to the dialog being started.
Returns
bestRouteResult(IRouteResult[], IDialogState[], string)
Finds the best route to use within a result set containing multiple ambiguous routes. The following disambigution strategy will be used:
- : Custom route types are the highest priority and will alwsays be preferred. This lets the developer override routing within a bot in very powerful way.
- ActiveDialog: The active dialog is the next highest priority.
- StackAction: Stack actions are the next highest priority and the action with the deepest stack position will be returned.
- GlobalAction: Global actions are the lowest priority. If a
dialogStack
is past in the actions from the library deepest on the stack will be favored. Otherwise the first one will be returned.
static function bestRouteResult(routes: IRouteResult[], dialogStack?: IDialogState[], rootLibraryName?: string)
Parameters
- routes
Array of candidate routes to filter.
- dialogStack
(Optional) dialog stack used to determine which libraries global actions to favor.
- rootLibraryName
-
string
(Optional) library namespace to prefer when disambiguating global actions and there's no dialogs on the stack.
Returns
clone(UniversalBot, string)
Returns a clone of an existing bot.
function clone(copyTo?: UniversalBot, newName?: string)
Parameters
- copyTo
- UniversalBot
(Optional) instance to copy the current object to. If missing a new instance will be created.
- newName
-
string
(Optional) if specified the returned copy will be renamed to a new name.
Returns
connector(string, IConnector)
Registers or returns a connector for a specific channel.
function connector(channelId: string, connector?: IConnector)
Parameters
- channelId
-
string
Unique ID of the channel. Use a channelId of '*' to reference the default connector.
- connector
- IConnector
(Optional) connector to register. If ommited the connector for channelId will be returned.
Returns
customAction(IDialogActionOptions)
Registers a custom global action that will call the passed in onSelectAction handler when triggered.
function customAction(options: IDialogActionOptions)
Parameters
- options
- IDialogActionOptions
The options used to configure the action. If matches is specified the action will listen for the user to say a word or phrase that triggers the action. Custom matching logic can be provided using onFindAction.
Returns
dialog(string, Dialog | IDialogWaterfallStep[] | IDialogWaterfallStep, boolean)
Registers or returns a dialog from the library.
function dialog(id: string, dialog?: Dialog | IDialogWaterfallStep[] | IDialogWaterfallStep, replace?: boolean)
Parameters
- id
-
string
Unique ID of the dialog being regsitered or retrieved.
- dialog
(Optional) dialog or waterfall to register.
- dialog: {Dialog} - Dialog to add.
- dialog: {IDialogWaterfallStep[]} - Waterfall of steps to execute. See IDialogWaterfallStep for details.
- dialog: {IDialogWaterfallStep} - Single step waterfall. Calling a built-in prompt or starting a new dialog will result in the current dialog ending upon completion of the child prompt/dialog.
- replace
-
boolean
(Optional) if true, the dialog should replace the existing dialog if already registered.
Returns
endConversationAction(string, TextOrMessageType, ICancelActionOptions)
Registers a global action that will end the conversation with the user when triggered.
function endConversationAction(name: string, msg?: TextOrMessageType, options?: ICancelActionOptions)
Parameters
- name
-
string
Unique name to assign the action.
(Optional) message to send the user prior to ending the conversation.
- options
- ICancelActionOptions
(Optional) options used to configure the action. If matches is specified the action will listen for the user to say a word or phrase that triggers the action, otherwise the action needs to be bound to a button using CardAction.dialogAction() to trigger the action.
Returns
findActiveDialogRoutes(IRecognizeContext, (err: Error, routes: IRouteResult[]) => void, IDialogState[])
Gets the active dialogs confidence that it understands the current message. The dialog must be a member of the current library, otherwise a score of 0.0 will be returned.
function findActiveDialogRoutes(context: IRecognizeContext, callback: (err: Error, routes: IRouteResult[]) => void, dialogStack?: IDialogState[])
Parameters
- context
- IRecognizeContext
Read-only recognizer context for the current conversation.
- callback
-
(err: Error, routes: IRouteResult[]) => void
Function that should be invoked with the found routes.
- dialogStack
(Optional) dialog stack to search over. The default behaviour is to search over the sessions current dialog stack.
findDialog(string, string)
Searches the library and all of its dependencies for a specific dialog. Returns the dialog if found, otherwise null.
function findDialog(libName: string, dialogId: string)
Parameters
- libName
-
string
Name of the library containing the dialog.
- dialogId
-
string
Unique ID of the dialog within the library.
Returns
findGlobalActionRoutes(IRecognizeContext, (err: Error, routes: IRouteResult[]) => void)
Searches the library to see if any global actions have been triggered.
function findGlobalActionRoutes(context: IRecognizeContext, callback: (err: Error, routes: IRouteResult[]) => void)
Parameters
- context
- IRecognizeContext
Read-only recognizer context for the current conversation.
- callback
-
(err: Error, routes: IRouteResult[]) => void
Function that should be invoked with the found routes.
findRoutes(IRecognizeContext, (err: Error, routes: IRouteResult[]) => void)
Searches for candidate routes to handle the current message. To actually initiate the
handling of the message you should call selectRoute() with one of the
returned results.
The default search logic can be overriden using onFindRoute() and only the
current library is searched so you should call findRoutes()
seperately for each library
within the hierarchy.
function findRoutes(context: IRecognizeContext, callback: (err: Error, routes: IRouteResult[]) => void)
Parameters
- context
- IRecognizeContext
Read-only recognizer context for the current conversation.
- callback
-
(err: Error, routes: IRouteResult[]) => void
Function that should be invoked with the found routes.
findStackActionRoutes(IRecognizeContext, (err: Error, routes: IRouteResult[]) => void, IDialogState[])
Searches the sessions dialog stack to see if any actions have been triggered.
function findStackActionRoutes(context: IRecognizeContext, callback: (err: Error, routes: IRouteResult[]) => void, dialogStack?: IDialogState[])
Parameters
- context
- IRecognizeContext
Read-only recognizer context for the current conversation.
- callback
-
(err: Error, routes: IRouteResult[]) => void
Function that should be invoked with the found routes.
- dialogStack
(Optional) dialog stack to search over. The default behaviour is to search over the sessions current dialog stack.
forEachDialog((dialog: Dialog, id: string) => void)
Enumerates all of the libraries dialogs.
function forEachDialog(callback: (dialog: Dialog, id: string) => void)
Parameters
- callback
-
(dialog: Dialog, id: string) => void
Iterator function to call with each dialog.
forEachLibrary((library: Library) => void)
Enumerates all of the libraries child libraries. The caller should take appropriate steps to avoid circular references when enumerating the hierarchy. In most cases calling libraryList() is a better choice as it already contains logic to avoid cycles.
function forEachLibrary(callback: (library: Library) => void)
Parameters
- callback
-
(library: Library) => void
Iterator function to call with each child libray.
get(string)
Returns the current value of a setting.
function get(name: string)
Parameters
- name
-
string
Name of the property to return. Valid names are properties on IUniversalBotSettings.
Returns
any
isInConversation(IAddress, (err: Error, lastAccess: Date) => void)
Returns information about when the last turn between the user and a bot occured. This can be called before beginDialog to determine if the user is currently in a conversation with the bot.
function isInConversation(address: IAddress, callback: (err: Error, lastAccess: Date) => void)
Parameters
- address
- IAddress
Address of the user to lookup. This should be saved during a previous conversation with the user.
- callback
-
(err: Error, lastAccess: Date) => void
Function to invoke with the results of the query.
library(Library | string)
Registers or returns a library dependency.
function library(lib: Library | string)
Parameters
- lib
-
Library | string
- lib: {Library} - Library to register as a dependency.
- lib: {string} - Unique name of the library to lookup. All dependencies will be searched as well.
Returns
libraryList(boolean)
Returns a list of unique libraries within the hierarchy. Should be called on the root of the library hierarchy and avoids cycles created when two child libraries reference the same dependent library.
function libraryList(reverse?: boolean)
Parameters
- reverse
-
boolean
(Optional) If true list will be generated from the leaves up meaning the root library will be listed last. The default value is false which means it will be generated from the roots down and the root library will be listed first.
Returns
Library[]
loadSession(IAddress, (err: Error, session: Session) => void)
Loads a session object for an arbitrary address.
function loadSession(address: IAddress, callback: (err: Error, session: Session) => void)
Parameters
- address
- IAddress
Address of the user/session to load. This should be saved during a previous conversation with the user.
- callback
-
(err: Error, session: Session) => void
Function to invoke with the loaded session.
localePath(string)
Gets or sets the path to the libraries "/locale/" folder containing its localized prompts. The prompts for the library should be stored in a "/locale/<IETF_TAG>/.json" file under this path where "<IETF_TAG>" representes the 2-3 digit language tage for the locale and "" is a filename matching the libraries namespace.
function localePath(path?: string)
Parameters
- path
-
string
(Optional) path to the libraries "/locale/" folder. If specified this will update the libraries path.
Returns
string
on(string, (data: any) => void)
Registers an event listener. The bot will emit its own events as it processes incoming and outgoing messages. It will also forward activity related events emitted from the connector, giving you one place to listen for all activity from your bot. The flow of events from the bot is as follows:
Message Received
When the bot receives a new message it will emit the following events in order:
lookupUser -> receive -> incoming -> getStorageData -> routing
Any receive middleware that's been installed will be executed between the 'receive' and 'incoming' events. After the 'routing' event is emitted any botbuilder middleware will be executed prior to dispatching the message to the bots active dialog.
Connector Activity Received
Connectors can emit activity events to signal things like a user is typing or that they friended a bot. These activities get routed through middleware like messages but they are not routed through the bots dialog system. They are only ever emitted as events.
The flow of connector events is:
lookupUser -> receive -> (activity)
Message sent
Bots can send multiple messages so the session will batch up all outgoing message and then save the bots current state before delivering the sent messages. You'll see a single 'saveStorageData' event emitted and then for every outgoing message in the batch you'll see the following sequence of events:
send -> outgoing
Any send middleware that's been installed will be executed between the 'send' and 'outgoing' events.
function on(event: string, listener: (data: any) => void)
Parameters
- event
-
string
Name of the event. Bot and connector specific event types:
Bot Events
- error: An error occured. Passed a JavaScript
Error
object. - lookupUser: The user is for an address is about to be looked up. Passed an IAddress object.
- receive: An incoming message has been received. Passed an IEvent object.
- incoming: An incoming message has been received and processed by middleware. Passed an IMessage object.
- routing: An incoming message has been bound to a session and is about to be routed through any session middleware and then dispatched to the active dialog for processing. Passed a Session object.
- send: An outgoing message is about to be sent to middleware for processing. Passed an IMessage object.
- outgoing: An outgoing message has just been sent through middleware and is about to be delivered to the users chat client.
- getStorageData: The sessions persisted state data is being loaded from storage. Passed an IBotStorageContext object.
- saveStorageData: The sessions persisted state data is being written to storage. Passed an IBotStorageContext object.
ChatConnector Events
- conversationUpdate: Your bot was added to a conversation or other conversation metadata changed. Passed an IConversationUpdate object.
- contactRelationUpdate: The bot was added to or removed from a user's contact list. Passed an IContactRelationUpdate object.
- typing: The user or bot on the other end of the conversation is typing. Passed an IEvent object.
- listener
-
(data: any) => void
Function to invoke.
onDisambiguateRoute(IDisambiguateRouteHandler)
Replaces the bots default route disambiguation logic with a custom implementation.
function onDisambiguateRoute(handler: IDisambiguateRouteHandler)
Parameters
- handler
- IDisambiguateRouteHandler
Function that will be invoked with the candidate routes to dispatch an incoming message to.
onFindRoutes(IFindRoutesHandler)
Replaces findRoutes() default route searching logic with a custom implementation.
function onFindRoutes(handler: IFindRoutesHandler)
Parameters
- handler
- IFindRoutesHandler
Function that will be invoked anytime findRoutes()
is called for the library.
onSelectRoute(ISelectRouteHandler)
Replaces the default logic for selectRoute() with a custom implementation.
function onSelectRoute(handler: ISelectRouteHandler)
Parameters
- handler
- ISelectRouteHandler
Function that will be invoked anytime selectRoute()
is called.
receive(IEvent | IEvent[], (err: Error) => void)
Called when a new event is received. This can be called manually to mimic the bot receiving a message from the user.
function receive(events: IEvent | IEvent[], done?: (err: Error) => void)
Parameters
- done
-
(err: Error) => void
(Optional) function to invoke once the operation is completed.
recognize(IRecognizeContext, (err: Error, result: IIntentRecognizerResult) => void)
Attempts to match a users text utterance to an intent using the libraries recognizers. See IIntentRecognizer.recognize() for details.
function recognize(context: IRecognizeContext, callback: (err: Error, result: IIntentRecognizerResult) => void)
Parameters
- context
- IRecognizeContext
Read-only recognizer context for the current conversation.
- callback
-
(err: Error, result: IIntentRecognizerResult) => void
Function that should be invoked upon completion of the recognition.
recognizer(IIntentRecognizer)
Adds a new recognizer plugin to the library.
function recognizer(plugin: IIntentRecognizer)
Parameters
- plugin
- IIntentRecognizer
The recognizer to add.
Returns
selectActiveDialogRoute(Session, IRouteResult, IDialogState[])
Routes the current message to the active dialog.
function selectActiveDialogRoute(session: Session, route: IRouteResult, newStack?: IDialogState[])
Parameters
- session
- Session
Session object for the current conversation.
- route
- IRouteResult
Route result returned from a previous call to findRoutes() or findActiveDialogRoutes().
- newStack
selectGlobalActionRoute(Session, IRouteResult, IDialogState[])
Routes the current message to a triggered global action.
function selectGlobalActionRoute(session: Session, route: IRouteResult, newStack?: IDialogState[])
Parameters
- session
- Session
Session object for the current conversation.
- route
- IRouteResult
Route result returned from a previous call to findRoutes() or findGlobalActionRoutes().
- newStack
selectRoute(Session, IRouteResult)
Triggers the handling of the current message using the selected route. The default logic can be overriden using onSelectRoute().
function selectRoute(session: Session, route: IRouteResult)
Parameters
- session
- Session
Session object for the current conversation.
- route
- IRouteResult
Route result returned from a previous call to findRoutes().
selectStackActionRoute(Session, IRouteResult, IDialogState[])
Routes the current message to a triggered stack action.
function selectStackActionRoute(session: Session, route: IRouteResult, newStack?: IDialogState[])
Parameters
- session
- Session
Session object for the current conversation.
- route
- IRouteResult
Route result returned from a previous call to findRoutes() or findStackActionRoutes().
- newStack
send(IIsMessage | IMessage | IMessage[], (err: Error, addresses?: IAddress[]) => void)
Sends a message to the user without disrupting the current conversations dialog stack.
function send(messages: IIsMessage | IMessage | IMessage[], done?: (err: Error, addresses?: IAddress[]) => void)
Parameters
- messages
-
IIsMessage | IMessage | IMessage[]
The message (or array of messages) to send the user.
- done
-
(err: Error, addresses?: IAddress[]) => void
(Optional) function to invoke once the operation is completed.
set(string, any)
Sets a setting on the bot.
function set(name: string, value: any)
Parameters
- name
-
string
Name of the property to set. Valid names are properties on IUniversalBotSettings.
- value
-
any
The value to assign to the setting.
Returns
use(IMiddlewareMap[])
Installs middleware for the bot. Middleware lets you intercept incoming and outgoing events/messages.
function use(args: IMiddlewareMap[])
Parameters
- args
One or more sets of middleware hooks to install.