botkit
- Version 4.15.0
- Published
- 368 kB
- 10 dependencies
- MIT license
Install
npm i botkit
yarn add botkit
pnpm add botkit
Overview
Building Blocks for Building Bots
Index
Classes
Interfaces
Classes
class Botkit
class Botkit {}
Create a new instance of Botkit to define the controller for a conversational app. To connect Botkit to a chat platform, pass in a fully configured
adapter
. If one is not specified, Botkit will expose an adapter for the Microsoft Bot Framework.
constructor
constructor(config: BotkitConfiguration);
Create a new Botkit instance and optionally specify a platform-specific adapter. By default, Botkit will create a [BotFrameworkAdapter](https://docs.microsoft.com/en-us/javascript/api/botbuilder/botframeworkadapter?view=botbuilder-ts-latest).
const controller = new Botkit({adapter: some_adapter,webhook_uri: '/api/messages',});controller.on('message', async(bot, message) => {// do something!});Parameter config
Configuration for this instance of Botkit
property adapter
adapter: any;
Any BotBuilder-compatible adapter - defaults to a [BotFrameworkAdapter](https://docs.microsoft.com/en-us/javascript/api/botbuilder/botframeworkadapter?view=botbuilder-ts-latest)
property dialogSet
dialogSet: DialogSet;
A BotBuilder DialogSet that serves as the top level dialog container for the Botkit app
property http
http: any;
A direct reference to the underlying HTTP server object
property middleware
middleware: { spawn: any; ingest: any; send: any; receive: any; interpret: any };
Middleware endpoints available for plugins and features to extend Botkit. Endpoints available are: spawn, ingest, receive, send.
To bind a middleware function to Botkit:
controller.middleware.receive.use(function(bot, message, next) {// do something with bot or message// always call next, or your bot will freeze!next();});
property PATH
PATH: string;
The path of the main Botkit SDK, used to generate relative paths
property plugins
readonly plugins: { [key: string]: any };
Access plugin extension methods. After a plugin calls
controller.addPluginExtension('foo', extension_methods)
, the extension will then be available atcontroller.plugins.foo
property storage
storage: Storage;
a BotBuilder storage driver - defaults to MemoryStorage
property version
version: string;
The current version of Botkit Core
property webserver
webserver: any;
An Express webserver
method addDep
addDep: (name: string) => void;
(For use by Botkit plugins only) - Add a dependency to Botkit's bootup process that must be marked as completed using
completeDep()
. Botkit'scontroller.ready()
function will not fire until all dependencies have been marked complete.For example, a plugin that needs to do an asynchronous task before Botkit proceeds might do:
controller.addDep('my_async_plugin');somethingAsync().then(function() {controller.completeDep('my_async_plugin');});Parameter name
The name of the dependency that is being loaded.
method addDialog
addDialog: (dialog: Dialog) => void;
Add a dialog to the bot, making it accessible via
bot.beginDialog(dialog_id)
// Create a dialog -- `BotkitConversation` is just one way to create a dialogconst my_dialog = new BotkitConversation('my_dialog', controller);my_dialog.say('Hello');// Add the dialog to the Botkit controllercontroller.addDialog(my_dialog);// Later on, trigger the dialog into action!controller.on('message', async(bot, message) => {await bot.beginDialog('my_dialog');});Parameter dialog
A dialog to be added to the bot's dialog set
method addPluginExtension
addPluginExtension: (name: string, extension: any) => void;
(Plugins only) Extend Botkit's controller with new functionality and make it available globally via the controller object.
// define the extension interfacelet extension = {stuff: () => { return 'stuff' }}// register the extensioncontroller.addPluginExtension('foo', extension);// call extensioncontroller.plugins.foo.stuff();Parameter name
name of plugin
Parameter extension
an object containing methods
method afterDialog
afterDialog: (dialog: Dialog | string, handler: BotkitHandler) => void;
Bind a handler to the end of a dialog. NOTE: bot worker cannot use bot.reply(), must use bot.send()
[Learn more about handling end-of-conversation](../docs/conversations.md#handling-end-of-conversation)
Parameter dialog
the dialog object or the id of the dialog
Parameter handler
a handler function in the form
async(bot, dialog_results) => {}
method completeDep
completeDep: (name: string) => boolean;
(For use by plugins only) - Mark a bootup dependency as loaded and ready to use Botkit's
controller.ready()
function will not fire until all dependencies have been marked complete.Parameter name
The name of the dependency that has completed loading.
method getConfig
getConfig: (key?: string) => any;
Get a value from the configuration.
For example:
// get entire config objectlet config = controller.getConfig();// get a specific value from the configlet webhook_uri = controller.getConfig('webhook_uri');Parameter key
The name of a value stored in the configuration
Returns
{any} The value stored in the configuration (or null if absent)
method getLocalView
getLocalView: (path_to_view: any) => string;
Convert a local path from a plugin folder to a full path relative to the webserver's main views folder. Allows a plugin to bundle views/layouts and make them available to the webserver's renderer.
Parameter path_to_view
something like path.join(__dirname,'views')
method handleTurn
handleTurn: (turnContext: TurnContext) => Promise<any>;
Accepts the result of a BotBuilder adapter's
processActivity()
method and processes it into a Botkit-style message and BotWorker instance which is then used to test for triggers and emit events. NOTE: This method should only be used in custom adapters that receive messages through mechanisms other than the main webhook endpoint (such as those received via websocket, for example)Parameter turnContext
a TurnContext representing an incoming message, typically created by an adapter's
processActivity()
method.
method hears
hears: ( patterns: | string | RegExp | (string | RegExp | ((message: BotkitMessage) => Promise<boolean>))[] | ((message: BotkitMessage) => Promise<boolean>), events: string | string[], handler: BotkitHandler) => void;
Instruct your bot to listen for a pattern, and do something when that pattern is heard. Patterns will be "heard" only if the message is not already handled by an in-progress dialog. To "hear" patterns _before_ dialogs are processed, use
controller.interrupts()
instead.For example:
// listen for a simple keywordcontroller.hears('hello','message', async(bot, message) => {await bot.reply(message,'I heard you say hello.');});// listen for a regular expressioncontroller.hears(new RegExp(/^[A-Z\s]+$/), 'message', async(bot, message) => {await bot.reply(message,'I heard a message IN ALL CAPS.');});// listen using a functioncontroller.hears(async (message) => { return (message.intent === 'hello') }, 'message', async(bot, message) => {await bot.reply(message,'This message matches the hello intent.');});Parameter patterns
One or more string, regular expression, or test function
Parameter events
A list of event types that should be evaluated for the given patterns
Parameter handler
a function that will be called should the pattern be matched
method interrupts
interrupts: ( patterns: | string | RegExp | (string | RegExp | ((message: BotkitMessage) => Promise<boolean>))[] | RegExp[] | ((message: BotkitMessage) => Promise<boolean>), events: string | string[], handler: BotkitHandler) => void;
Instruct your bot to listen for a pattern, and do something when that pattern is heard. Interruptions work just like "hears" triggers, but fire _before_ the dialog system is engaged, and thus handlers will interrupt the normal flow of messages through the processing pipeline.
controller.interrupts('help','message', async(bot, message) => {await bot.reply(message,'Before anything else, you need some help!')});Parameter patterns
One or more string, regular expression, or test function
Parameter events
A list of event types that should be evaluated for the given patterns
Parameter handler
a function that will be called should the pattern be matched
method loadModule
loadModule: (p: string) => void;
Load a Botkit feature module
Parameter p
path to module file
method loadModules
loadModules: (p: string, exts?: string[]) => void;
Load all Botkit feature modules located in a given folder.
controller.ready(() => {// load all modules from sub-folder features/controller.loadModules('./features');});Parameter p
path to a folder of module files
Parameter exts
the extensions that you would like to load (default: ['.js'])
method on
on: (events: string | string[], handler: BotkitHandler) => void;
Bind a handler function to one or more events.
controller.on('conversationUpdate', async(bot, message) => {await bot.reply(message,'I received a conversationUpdate event.');});Parameter events
One or more event names
Parameter handler
a handler function that will fire whenever one of the named events is received.
method publicFolder
publicFolder: (alias: any, path: any) => void;
Expose a folder to the web as a set of static files. Useful for plugins that need to bundle additional assets!
// make content of the local public folder available at http://MYBOTURL/public/myplugincontroller.publicFolder('/public/myplugin', __dirname + '/public);Parameter alias
the public alias ie /myfiles
Parameter path
the actual path something like
__dirname + '/public'
method ready
ready: (handler: () => any) => void;
Use
controller.ready()
to wrap any calls that require components loaded during the bootup process. This will ensure that the calls will not be made until all of the components have successfully been initialized.For example:
controller.ready(() => {controller.loadModules(__dirname + '/features');});Parameter handler
A function to run when Botkit is booted and ready to run.
method saveState
saveState: (bot: BotWorker) => Promise<void>;
Save the current conversation state pertaining to a given BotWorker's activities. Note: this is normally called internally and is only required when state changes happen outside of the normal processing flow.
Parameter bot
a BotWorker instance created using
controller.spawn()
method shutdown
shutdown: () => Promise<void>;
Shutdown the webserver and prepare to terminate the app. Causes Botkit to first emit a special
shutdown
event, process any bound handlers, and then finally terminate the webserver. Bind any necessary cleanup helpers to the shutdown event - for example, close the connection to mongo.await controller.shutdown();controller.on('shutdown', async() => {console.log('Bot is shutting down!');});
method spawn
spawn: (config?: any, custom_adapter?: BotAdapter) => Promise<BotWorker>;
Create a platform-specific BotWorker instance that can be used to respond to messages or generate new outbound messages. The spawned
bot
contains all information required to process outbound messages and handle dialog state, and may also contain extensions for handling platform-specific events or activities.Parameter config
Preferably receives a DialogContext, though can also receive a TurnContext. If excluded, must call
bot.changeContext(reference)
before calling any other method.Parameter adapter
An optional reference to a specific adapter from which the bot will be spawned. If not specified, will use the adapter from which the configuration object originates. Required for spawning proactive bots in a multi-adapter scenario.
method trigger
trigger: ( event: string, bot?: BotWorker, message?: BotkitMessage) => Promise<any>;
Trigger an event to be fired. This will cause any bound handlers to be executed. Note: This is normally used internally, but can be used to emit custom events.
// fire a custom eventcontroller.trigger('my_custom_event', bot, message);// handle the custom eventcontroller.on('my_custom_event', async(bot, message) => {//... do something});Parameter event
the name of the event
Parameter bot
a BotWorker instance created using
controller.spawn()
Parameter message
An incoming message or event
method usePlugin
usePlugin: ( plugin_or_function: ((botkit: Botkit) => BotkitPlugin) | BotkitPlugin) => void;
Load a plugin module and bind all included middlewares to their respective endpoints.
Parameter plugin_or_function
A plugin module in the form of function(botkit) {...} that returns {name, middlewares, init} or an object in the same form.
class BotkitConversation
class BotkitConversation<O extends object = {}> extends Dialog<O> {}
An extension on the [BotBuilder Dialog Class](https://docs.microsoft.com/en-us/javascript/api/botbuilder-dialogs/dialog?view=botbuilder-ts-latest) that provides a Botkit-friendly interface for defining and interacting with multi-message dialogs. Dialogs can be constructed using
say()
,ask()
and other helper methods.// define the structure of your dialog...const convo = new BotkitConversation('foo', controller);convo.say('Hello!');convo.ask('What is your name?', async(answer, convo, bot) => {await bot.say('Your name is ' + answer);});controller.dialogSet.add(convo);// later on, trigger this dialog by its idcontroller.on('event', async(bot, message) => {await bot.beginDialog('foo');})
constructor
constructor(dialogId: string, controller: Botkit);
Create a new BotkitConversation object
Parameter dialogId
A unique identifier for this dialog, used to later trigger this dialog
Parameter controller
A pointer to the main Botkit controller
property script
script: any;
A map of every message in the dialog, broken into threads
method addAction
addAction: (action: string, thread_name?: string) => BotkitConversation;
An an action to the conversation timeline. This can be used to go to switch threads or end the dialog.
When provided the name of another thread in the conversation, this will cause the bot to go immediately to that thread.
Otherwise, use one of the following keywords: *
stop
*repeat
*complete
*timeout
[Learn more about building conversations →](../conversations.md#build-a-conversation)
// go to a thread called "next_thread"convo.addAction('next_thread');// end the conversation and mark as successfulconvo.addAction('complete');Parameter action
An action or thread name
Parameter thread_name
The name of the thread to which this action is added. Defaults to
default
method addChildDialog
addChildDialog: ( dialog_id: string, key_name?: string, thread_name?: string) => BotkitConversation;
Cause the dialog to call a child dialog, wait for it to complete, then store the results in a variable and resume the parent dialog. Use this to [combine multiple dialogs into bigger interactions.](../conversations.md#composing-dialogs)
[Learn more about building conversations →](../conversations.md#build-a-conversation)
// define a profile collection dialoglet profileDialog = new BotkitConversation('PROFILE_DIALOG', controller);profileDialog.ask('What is your name?', async(res, convo, bot) => {}, {key: 'name'});profileDialog.ask('What is your age?', async(res, convo, bot) => {}, {key: 'age'});profileDialog.ask('What is your location?', async(res, convo, bot) => {}, {key: 'location'});controller.addDialog(profileDialog);let onboard = new BotkitConversation('ONBOARDING', controller);onboard.say('Hello! It is time to collect your profile data.');onboard.addChildDialog('PROFILE_DIALOG', 'profile');onboard.say('Hello, {{vars.profile.name}}! Onboarding is complete.');Parameter dialog_id
the id of another dialog
Parameter key_name
the variable name in which to store the results of the child dialog. if not provided, defaults to dialog_id.
Parameter thread_name
the name of a thread to which this call should be added. defaults to 'default'
method addGotoDialog
addGotoDialog: (dialog_id: string, thread_name?: string) => BotkitConversation;
Cause the current dialog to handoff to another dialog. The parent dialog will not resume when the child dialog completes. However, the afterDialog event will not fire for the parent dialog until all child dialogs complete. Use this to [combine multiple dialogs into bigger interactions.](../conversations.md#composing-dialogs)
[Learn more about building conversations →](../conversations.md#build-a-conversation)
let parent = new BotkitConversation('parent', controller);let child = new BotkitConversation('child', controller);parent.say('Moving on....');parent.addGotoDialog('child');Parameter dialog_id
the id of another dialog
Parameter thread_name
the name of a thread to which this call should be added. defaults to 'default'
method addMessage
addMessage: ( message: Partial<BotkitMessageTemplate> | string, thread_name: string) => BotkitConversation;
Add a message template to a specific thread. Messages added with
say()
andaddMessage()
will be sent one after another without a pause.[Learn more about building conversations →](../conversations.md#build-a-conversation)
let conversation = new BotkitConversation('welcome', controller);conversation.say('Hello! Welcome to my app.');conversation.say('Let us get started...');// pass in a message with an action that will cause gotoThread to be called...conversation.addAction('continuation');conversation.addMessage('This is a different thread completely', 'continuation');Parameter message
Message template to be sent
Parameter thread_name
Name of thread to which message will be added
method addQuestion
addQuestion: ( message: Partial<BotkitMessageTemplate> | string, handlers: BotkitConvoHandler | BotkitConvoTrigger[], key: { key: string } | string | null, thread_name: string) => BotkitConversation;
Identical to [ask()](#ask), but accepts the name of a thread to which the question is added.
[Learn more about building conversations →](../conversations.md#build-a-conversation)
Parameter message
A message that will be used as the prompt
Parameter handlers
One or more handler functions defining possible conditional actions based on the response to the question
Parameter key
Name of variable to store response in.
Parameter thread_name
Name of thread to which message will be added
method after
after: (handler: (results: any, bot: BotWorker) => void) => void;
Bind a function to run after the dialog has completed. The first parameter to the handler will include a hash of all variables set and values collected from the user during the conversation. The second parameter to the handler is a BotWorker object that can be used to start new dialogs or take other actions.
[Learn more about handling end of conversation](../conversations.md#handling-end-of-conversation)
let convo = new BotkitConversation(MY_CONVO, controller);convo.ask('What is your name?', [], 'name');convo.ask('What is your age?', [], 'age');convo.ask('What is your favorite color?', [], 'color');convo.after(async(results, bot) => {// handle results.name, results.age, results.color});controller.addDialog(convo);Parameter handler
in the form async(results, bot) { ... }
method ask
ask: ( message: Partial<BotkitMessageTemplate> | string, handlers: BotkitConvoHandler | BotkitConvoTrigger[], key: { key: string } | string | null) => BotkitConversation;
Add a question to the default thread. In addition to a message template, receives either a single handler function to call when an answer is provided, or an array of handlers paired with trigger patterns. When providing multiple conditions to test, developers may also provide a handler marked as the default choice.
[Learn more about building conversations →](../conversations.md#build-a-conversation)
// ask a question, handle the response with a functionconvo.ask('What is your name?', async(response, convo, bot, full_message) => {await bot.say('Oh your name is ' + response);}, {key: 'name'});// ask a question, evaluate answer, take conditional action based on responseconvo.ask('Do you want to eat a taco?', [{pattern: 'yes',type: 'string',handler: async(response_text, convo, bot, full_message) => {return await convo.gotoThread('yes_taco');}},{pattern: 'no',type: 'string',handler: async(response_text, convo, bot, full_message) => {return await convo.gotoThread('no_taco');}},{default: true,handler: async(response_text, convo, bot, full_message) => {await bot.say('I do not understand your response!');// start over!return await convo.repeat();}}], {key: 'tacos'});Parameter message
a message that will be used as the prompt
Parameter handlers
one or more handler functions defining possible conditional actions based on the response to the question.
Parameter key
name of variable to store response in.
method before
before: ( thread_name: string, handler: (convo: BotkitDialogWrapper, bot: BotWorker) => Promise<any>) => void;
Register a handler function that will fire before a given thread begins. Use this hook to set variables, call APIs, or change the flow of the conversation using
convo.gotoThread
convo.addMessage('This is the foo thread: var == {{vars.foo}}', 'foo');convo.before('foo', async(convo, bot) => {// set a variable here that can be used in the message templateconvo.setVar('foo','THIS IS FOO');});Parameter thread_name
A valid thread defined in this conversation
Parameter handler
A handler function in the form async(convo, bot) => { ... }
method beginDialog
beginDialog: (dc: DialogContext, options: any) => Promise<any>;
Called automatically when a dialog begins. Do not call this directly!
Parameter dc
the current DialogContext
Parameter options
an object containing initialization parameters passed to the dialog. may include
thread
which will cause the dialog to begin with that thread instead of thedefault
thread.
method continueDialog
continueDialog: (dc: DialogContext) => Promise<any>;
Called automatically when an already active dialog is continued. Do not call this directly!
Parameter dc
the current DialogContext
method end
end: (dc: DialogContext) => Promise<DialogTurnStatus>;
Automatically called when the the dialog ends and causes any handlers bound using
after()
to fire. Do not call this directly!Parameter dc
The current DialogContext
Parameter value
The final value collected by the dialog.
method onChange
onChange: ( variable: string, handler: (response: any, convo: any, bot: any) => Promise<any>) => void;
Bind a function to run whenever a user answers a specific question. Can be used to validate input and take conditional actions.
convo.ask('What is your name?', [], 'name');convo.onChange('name', async(response, convo, bot) => {// user changed their name!// do something...});Parameter variable
name of the variable to watch for changes
Parameter handler
a handler function that will fire whenever a user's response is used to change the value of the watched variable
method resumeDialog
resumeDialog: (dc: any, reason: any, result: any) => Promise<any>;
Called automatically when a dialog moves forward a step. Do not call this directly!
Parameter dc
The current DialogContext
Parameter reason
Reason for resuming the dialog
Parameter result
Result of previous step
method say
say: (message: Partial<BotkitMessageTemplate> | string) => BotkitConversation;
Add a non-interactive message to the default thread. Messages added with
say()
andaddMessage()
will _not_ wait for a response, will be sent one after another without a pause.[Learn more about building conversations →](../conversations.md#build-a-conversation)
let conversation = new BotkitConversation('welcome', controller);conversation.say('Hello! Welcome to my app.');conversation.say('Let us get started...');Parameter message
Message template to be sent
class BotkitDialogWrapper
class BotkitDialogWrapper {}
This class is used to provide easy access to common actions taken on active BotkitConversation instances. These objects are passed into handlers bound to BotkitConversations using .before .onChange and conditional handler functions passed to .ask and .addQuestion Grants access to convo.vars convo.gotoThread() convo.setVar() and convo.repeat().
constructor
constructor(dc: DialogContext, step: BotkitConversationStep);
property vars
vars: { [key: string]: any };
An object containing variables and user responses from this conversation.
method gotoThread
gotoThread: (thread: string) => Promise<void>;
Jump immediately to the first message in a different thread.
Parameter thread
Name of a thread
method repeat
repeat: () => Promise<void>;
Repeat the last message sent on the next turn.
method setVar
setVar: (key: any, val: any) => void;
Set the value of a variable that will be available to messages in the conversation. Equivalent to convo.vars.key = val; Results in {{vars.key}} being replaced with the value in val.
Parameter key
the name of the variable
Parameter val
the value for the variable
method stop
stop: () => Promise<void>;
Stop the dialog.
class BotkitTestClient
class BotkitTestClient {}
A client for testing dialogs in isolation.
constructor
constructor( channelId: string, bot: Botkit, dialogToTest: string | string[], initialDialogOptions?: any, middlewares?: Middleware[], conversationState?: ConversationState);
Create a BotkitTestClient to test a dialog without having to create a full-fledged adapter.
let client = new BotkitTestClient('test', bot, MY_DIALOG, MY_OPTIONS);let reply = await client.sendActivity('first message');assert.strictEqual(reply.text, 'first reply', 'reply failed');Parameter channelId
The channelId to be used for the test. Use 'emulator' or 'test' if you are uncertain of the channel you are targeting. Otherwise, it is recommended that you use the id for the channel(s) your bot will be using and write a test case for each channel.
Parameter bot
(Required) The Botkit bot that has the skill to test.
Parameter dialogToTest
(Required) The identifier of the skill to test in the bot.
Parameter initialDialogOptions
(Optional) additional argument(s) to pass to the dialog being started.
Parameter middlewares
(Optional) a stack of middleware to be run when testing
Parameter conversationState
(Optional) A ConversationState instance to use in the test client
constructor
constructor( testAdapter: TestAdapter, bot: Botkit, dialogToTest: string | string[], initialDialogOptions?: any, middlewares?: Middleware[], conversationState?: ConversationState);
property conversationState
conversationState: ConversationState;
property dialogTurnResult
dialogTurnResult: DialogTurnResult;
method getNextReply
getNextReply: () => Activity;
Get the next reply waiting to be delivered (if one exists)
method sendActivity
sendActivity: (activity: Partial<Activity> | string) => Promise<any>;
Send an activity into the dialog.
Parameter activity
an activity potentially with text
DialogTest.send('hello').assertReply('hello yourself').then(done);Returns
a TestFlow that can be used to assert replies etc
class BotWorker
class BotWorker {}
A base class for a
bot
instance, an object that contains the information and functionality for taking action in response to an incoming message. Note that adapters are likely to extend this class with additional platform-specific methods - refer to the adapter documentation for these extensions.
constructor
constructor(controller: Botkit, config: any);
Create a new BotWorker instance. Do not call this directly - instead, use [controller.spawn()](#spawn).
Parameter controller
A pointer to the main Botkit controller
Parameter config
An object typically containing { dialogContext, reference, context, activity }
property controller
readonly controller: Botkit;
Get a reference to the main Botkit controller.
method beginDialog
beginDialog: (id: string, options?: any) => Promise<void>;
Begin a pre-defined dialog by specifying its id. The dialog will be started in the same context (same user, same channel) in which the original incoming message was received. [See "Using Dialogs" in the core documentation.](../index.md#using-dialogs)
controller.hears('hello', 'message', async(bot, message) => {await bot.beginDialog(GREETINGS_DIALOG);});Parameter id
id of dialog
Parameter options
object containing options to be passed into the dialog
method cancelAllDialogs
cancelAllDialogs: () => Promise<DialogTurnResult>;
Cancel any and all active dialogs for the current user/context.
method changeContext
changeContext: (reference: ConversationReference) => Promise<BotWorker>;
Alter the context in which a bot instance will send messages. Use this method to create or adjust a bot instance so that it can send messages to a predefined user/channel combination.
// get the reference field and store it.const saved_reference = message.reference;// later on...let bot = await controller.spawn();bot.changeContext(saved_reference);bot.say('Hello!');Parameter reference
A [ConversationReference](https://docs.microsoft.com/en-us/javascript/api/botframework-schema/conversationreference?view=botbuilder-ts-latest), most likely captured from an incoming message and stored for use in proactive messaging scenarios.
method ensureMessageFormat
ensureMessageFormat: (message: Partial<BotkitMessage> | string) => Activity;
Take a crudely-formed Botkit message with any sort of field (may just be a string, may be a partial message object) and map it into a beautiful BotFramework Activity. Any fields not found in the Activity definition will be moved to activity.channelData. message a string or partial outgoing message object
Returns
a properly formed Activity object
method getActiveDialog
getActiveDialog: () => Dialog | undefined;
Get a reference to the active dialog
Returns
a reference to the active dialog or undefined if no dialog is active
method getConfig
getConfig: (key?: string) => any;
Get a value from the BotWorker's configuration.
let original_context = bot.getConfig('context');await original_context.sendActivity('send directly using the adapter instead of Botkit');Parameter key
The name of a value stored in the configuration
Returns
{any} The value stored in the configuration (or null if absent)
method hasActiveDialog
hasActiveDialog: () => boolean;
Check if any dialog is active or not
Returns
true if there is an active dialog, otherwise false
method httpBody
httpBody: (body: any) => void;
Set the http response body for this turn. Use this to define the response value when the platform requires a synchronous response to the incoming webhook.
Example handling of a /slash command from Slack:
controller.on('slash_command', async(bot, message) => {bot.httpBody('This is a reply to the slash command.');})Parameter body
(any) a value that will be returned as the http response body
method httpStatus
httpStatus: (status: number) => void;
Set the http response status code for this turn
controller.on('event', async(bot, message) => {// respond with a 500 error code for some reason!bot.httpStatus(500);});Parameter status
a valid http status code like 200 202 301 500 etc
method isDialogActive
isDialogActive: (id: string) => boolean;
Check to see if a given dialog is currently active in the stack
Parameter id
The id of a dialog to look for in the dialog stack
Returns
true if dialog with id is located anywhere in the dialog stack
method replaceDialog
replaceDialog: (id: string, options?: any) => Promise<void>;
Replace any active dialogs with a new a pre-defined dialog by specifying its id. The dialog will be started in the same context (same user, same channel) in which the original incoming message was received. [See "Using Dialogs" in the core documentation.](../index.md#using-dialogs)
controller.hears('hello', 'message', async(bot, message) => {await bot.replaceDialog(GREETINGS_DIALOG);});Parameter id
id of dialog
Parameter options
object containing options to be passed into the dialog
method reply
reply: ( src: Partial<BotkitMessage>, resp: Partial<BotkitMessage> | string) => Promise<any>;
Reply to an incoming message. Message will be sent using the context of the source message, which may in some cases be different than the context used to spawn the bot.
Note that like [bot.say()](#say),
reply()
can take a string or a message object.controller.on('event', async(bot, message) => {await bot.reply(message, 'I received an event and am replying to it.');});Parameter src
An incoming message, usually passed in to a handler function
Parameter resp
A string containing the text of a reply, or more fully formed message object
Returns
Return value will contain the results of the send action, typically
{id: <id of message>}
method say
say: (message: Partial<BotkitMessage> | string) => Promise<any>;
Send a message using whatever context the
bot
was spawned in or set using [changeContext()](#changecontext) -- or more likely, one of the platform-specific helpers like [startPrivateConversation()](../reference/slack.md#startprivateconversation) (Slack), [startConversationWithUser()](../reference/twilio-sms.md#startconversationwithuser) (Twilio SMS), and [startConversationWithUser()](../reference/facebook.md#startconversationwithuser) (Facebook Messenger). Be sure to check the platform documentation for others - most adapters include at least one.Simple use in event handler (acts the same as bot.reply)
controller.on('event', async(bot, message) => {await bot.say('I received an event!');});Use with a freshly spawned bot and bot.changeContext:
let bot = controller.spawn(OPTIONS);bot.changeContext(REFERENCE);bot.say('ALERT! I have some news.');Use with multi-field message object:
controller.on('event', async(bot, message) => {bot.say({text: 'I heard an event',attachments: [title: message.type,text: `The message was of type ${ message.type }`,// ...]});});Parameter message
A string containing the text of a reply, or more fully formed message object
Returns
Return value will contain the results of the send action, typically
{id: <id of message>}
method startConversationWithUser
startConversationWithUser: (reference: any) => Promise<void>;
class TeamsBotWorker
class TeamsBotWorker extends BotWorker {}
This is a specialized version of [Botkit's core BotWorker class](core.md#BotWorker) that includes additional methods for interacting with Microsoft Teams. It includes all functionality from the base class, as well as the extension methods below. This BotWorker is used with the built-in Bot Framework adapter.
property teams
teams: TeamsInfo;
Grants access to the TeamsInfo helper class See: https://docs.microsoft.com/en-us/javascript/api/botbuilder/teamsinfo?view=botbuilder-ts-latest
method replyWithTaskInfo
replyWithTaskInfo: (message: BotkitMessage, taskInfo: any) => Promise<any>;
Reply to a Teams task module task/fetch or task/submit with a task module response. See https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/task-modules/task-modules-bots
Parameter message
Parameter taskInfo
an object in the form {type, value}
class TeamsInvokeMiddleware
class TeamsInvokeMiddleware extends MiddlewareSet {}
When used, causes Botkit to emit special events for teams "invokes" Based on https://github.com/microsoft/botbuilder-js/blob/master/libraries/botbuilder/src/teamsActivityHandler.ts This allows Botkit bots to respond directly to task/fetch or task/submit events, as an example. To use this, bind it to the adapter before creating the Botkit controller:
const Botkit = new Botkit({...});botkit.adapter.use(new TeamsInvokeMiddleware());// can bind directly to task/fetch, task/submit and other invoke types used by teamscontroller.on('task/fetch', async(bot, message) => {await bot.replyWithTaskInfo(message, taskInfo);});
method onTurn
onTurn: (context: TurnContext, next: () => Promise<any>) => Promise<void>;
Not for direct use - implements the MiddlewareSet's required onTurn function used to process the event
Parameter context
Parameter next
Interfaces
interface BotkitConfiguration
interface BotkitConfiguration {}
Defines the options used when instantiating Botkit to create the main app controller with
new Botkit(options)
property adapter
adapter?: any;
A fully configured BotBuilder Adapter, such as
botbuilder-adapter-slack
orbotbuilder-adapter-web
The adapter is responsible for translating platform-specific messages into the format understood by Botkit and BotBuilder.
property adapterConfig
adapterConfig?: { [key: string]: any;};
If using the BotFramework service, options included in
adapterConfig
will be passed to the new Adapter when created internally. See [BotFrameworkAdapterSettings](https://docs.microsoft.com/en-us/javascript/api/botbuilder/botframeworkadaptersettings?view=azure-node-latest&viewFallbackFrom=botbuilder-ts-latest).
property dialogStateProperty
dialogStateProperty?: string;
Name of the dialogState property in the ConversationState that will be used to automatically track the dialog state. Defaults to
dialogState
.
property disable_console
disable_console?: boolean;
Disable messages normally sent to the console during startup.
property disable_webserver
disable_webserver?: boolean;
Disable webserver. If true, Botkit will not create a webserver or expose any webhook endpoints automatically. Defaults to false.
property jsonLimit
jsonLimit?: string;
Limit of the size of incoming JSON payloads parsed by the Express bodyParser. Defaults to '100kb'
property storage
storage?: Storage;
A Storage interface compatible with [this specification](https://docs.microsoft.com/en-us/javascript/api/botbuilder-core/storage?view=botbuilder-ts-latest) Defaults to the ephemeral [MemoryStorage](https://docs.microsoft.com/en-us/javascript/api/botbuilder-core/memorystorage?view=botbuilder-ts-latest) implementation.
property urlEncodedLimit
urlEncodedLimit?: string;
Limit of the size of incoming URL encoded payloads parsed by the Express bodyParser. Defaults to '100kb'
property webhook_uri
webhook_uri?: string;
Path used to create incoming webhook URI. Defaults to
/api/messages
property webserver
webserver?: any;
An instance of Express used to define web endpoints. If not specified, one will be created internally. Note: only use your own Express if you absolutely must for some reason. Otherwise, use
controller.webserver
property webserver_middlewares
webserver_middlewares?: any[];
An array of middlewares that will be automatically bound to the webserver. Should be in the form (req, res, next) => {}
interface BotkitConversationStep
interface BotkitConversationStep {}
property index
index: number;
The number pointing to the current message in the current thread in this dialog's script
property next
next: (stepResult: any) => Promise<any>;
A function to call when the step is completed.
property options
options: any;
A pointer to any options passed into the dialog when it began
property reason
reason: DialogReason;
The reason for this step being called
property result
result: any;
The results of the previous turn
property state
state: any;
A pointer to the current dialog state
property thread
thread: string;
The name of the current thread
property threadLength
threadLength: number;
The length of the current thread
property values
values: any;
A pointer directly to state.values
interface BotkitHandler
interface BotkitHandler {}
A handler function passed into
hears()
oron()
that receives a [BotWorker](#botworker) instance and a [BotkitMessage](#botkitmessage). Should be defined as an async function and/or return a Promise.The form of these handlers should be:
async (bot, message) => {// stuff.}For example:
controller.on('event', async(bot, message) => {// do somethign using bot and message like...await bot.reply(message,'Received an event.');});
call signature
(bot: BotWorker, message: BotkitMessage): Promise<any>;
interface BotkitMessage
interface BotkitMessage {}
Defines the expected form of a message or event object being handled by Botkit. Will also contain any additional fields including in the incoming payload.
property channel
channel: string;
Unique identifier of the room/channel/space in which the message was sent. Typically contains the platform specific designator for that channel.
property incoming_message
incoming_message: Activity;
The original incoming [BotBuilder Activity](https://docs.microsoft.com/en-us/javascript/api/botframework-schema/activity?view=botbuilder-ts-latest) object as created by the adapter.
property reference
reference: ConversationReference;
A full [ConversationReference](https://docs.microsoft.com/en-us/javascript/api/botframework-schema/conversationreference?view=botbuilder-ts-latest) object that defines the address of the message and all information necessary to send messages back to the originating location. Can be stored for later use, and used with [bot.changeContext()](#changeContext) to send proactive messages.
property text
text?: string;
Text of the message sent by the user (or primary value in case of button click)
property type
type: string;
The type of event, in most cases defined by the messaging channel or adapter
property user
user: string;
Unique identifier of user who sent the message. Typically contains the platform specific user id.
property value
value?: string;
Any value field received from the platform
index signature
[key: string]: any;
Any additional fields found in the incoming payload from the messaging platform.
interface BotkitPlugin
interface BotkitPlugin {}
An interface for plugins that can contain multiple middlewares as well as an init function.
property init
init?: (botkit: Botkit) => void;
property middlewares
middlewares?: { [key: string]: any[];};
property name
name: string;
index signature
[key: string]: any;
Package Files (7)
Dependencies (10)
Dev Dependencies (9)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/botkit
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/botkit)
- HTML<a href="https://www.jsdocs.io/package/botkit"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 6588 ms. - Missing or incorrect documentation? Open an issue for this package.