DocumentationBlogSupport
Log inSign up
Log inSign up
BlogSupport
Build
Getting StartedPlatform Introduction
Embedded Apps
What's NewOverviewDeveloper GuideSidebar API Quick StartSubmission Checklist for Embedded Apps
Design Guidelines
MessagingMeetingsDevicesSidebarSidebar on Mobile
API Reference
BotsButtons and CardsIntegrationsBYODSService AppsService App GuestsService Apps G2GGuest IssuerWidgetsWebex ConnectLogin with WebexInstant ConnectInstant Connect Meeting LinksDeveloper SandboxBeta ProgramSubmit Your AppSupport PolicyFAQs
APIs
API Behavior ChangesPartners API GuideXML API DeprecationAccess the APIREST API BasicsCompliance
Webex APIs
Reference
Data Sources
Admin
OverviewAdmin APIsHybrid ServicesAuthentication
Guides
Hybrid ServicesWebhooksReal-time File DLP BasicsProvisioning APIsBackground ImagesAudit Events Error Reference
Reference
Admin Audit EventsAuthorizationsEventsGroupsHistorical AnalyticsHybrid ClustersHybrid ConnectorsLicensesMeeting QualitiesOrganization ContactsOrganizationsPartner ManagementPartner Reports/TemplatesPartner TagsPeopleRecording ReportRecordingsReport TemplatesReportsResource Group MembershipsResource GroupsRolesSecurity Audit EventsSession TypesSettingsSpace ClassificationsTracking CodesWorkspace LocationsWorkspace Metrics
Webex Calling Beta
Overview
Guides
Integrations and AuthorizationMetadata and Samples
Webex Calling
OverviewSDKs and ToolsWhat's New
Guides
Integrations and AuthorizationProvisioning APIsMetadata and SamplesBackground Images
Reference
Call ControlsCall RoutingCall Settings For MeCalling Service SettingsClient Call SettingsConference ControlsConverged RecordingsDECT Devices SettingsDevice Call SettingsDevicesEmergency Services SettingsFeatures: Announcement PlaylistFeatures: Announcement RepositoryFeatures: Auto AttendantFeatures: Call ParkFeatures: Call PickupFeatures: Call QueueFeatures: Call RecordingFeatures: Customer Experience EssentialsFeatures: Hunt GroupFeatures: Operating ModesFeatures: Paging GroupFeatures: Single Number ReachLocation Call SettingsLocation Call Settings: Call HandlingLocation Call Settings: SchedulesLocation Call Settings: VoicemailLocationsNumbersPSTNPartner Reports/TemplatesPeopleRecording ReportReportsReports: Detailed Call HistorySend Activation EmailUser Call SettingsVirtual Line Call SettingsWorkspace Call SettingsWorkspaces
Webex for Broadworks
Overview
Guides
Integrations and AuthorizationDeveloper's Guide
Reference
BroadWorks Billing ReportsBroadWorks EnterprisesBroadWorks SubscribersBroadWorks Workspaces
Webex for Wholesale
Overview
Guides
Developer's Guide
Reference
Wholesale Billing ReportsWholesale Provisioning
Webex for UCM
Guides
Integrations and Authorization
Reference
UCM Profile
Contact Center
Overview
Reference
Data Sources
Customer Journey Data
Overview
Guides
Getting StartedFAQ
Devices
Overview
Guides
Devices
Reference
Device Call SettingsDevice ConfigurationsDevicesWorkspace LocationsWorkspace MetricsWorkspace PersonalizationWorkspacesxAPI
Directory Services
Reference
Domain ManagementIdentity Organization
Meetings
Overview
Guides
Integrations and AuthorizationWebhooksWebinar GuideMeeting Resource Guide
Reference
Meeting ChatsMeeting Closed CaptionsMeeting InviteesMeeting MessagesMeeting ParticipantsMeeting PollsMeeting PreferencesMeeting Q and AMeeting QualitiesMeeting TranscriptsMeetingsMeetings Summary ReportPeopleRecording ReportRecordingsSession TypesTracking CodesVideo MeshWebhooks
Messaging
Overview
Guides
BotsIntegrations and AuthorizationWebhooksButtons and Cards
Reference
Attachment ActionsEventsMembershipsMessagesPeopleRoom TabsRoomsTeam MembershipsTeamsWebhooks
SCIM 2
Overview
Reference
SCIM 2 BulkSCIM 2 GroupsSCIM 2 Users
Workspace Integrations
OverviewTechnical DetailsControl Hub Features
Webex Status API
Full API Reference
Admin Audit EventsAttachment ActionsAuthorizationsBroadWorks Billing ReportsBroadWorks EnterprisesBroadWorks SubscribersBroadWorks WorkspacesCall ControlsCall RoutingCall Settings For MeCalling Service SettingsClient Call SettingsConference ControlsConverged RecordingsDECT Devices SettingsData SourcesDevice Call SettingsDevice ConfigurationsDevicesDomain ManagementEmergency Services SettingsEventsFeatures: Announcement PlaylistFeatures: Announcement RepositoryFeatures: Auto AttendantFeatures: Call ParkFeatures: Call PickupFeatures: Call QueueFeatures: Call RecordingFeatures: Customer Experience EssentialsFeatures: Hunt GroupFeatures: Operating ModesFeatures: Paging GroupFeatures: Single Number ReachGroupsGuests ManagementHistorical AnalyticsHybrid ClustersHybrid ConnectorsIdentity OrganizationIssuesLicensesLocation Call SettingsLocation Call Settings: Call HandlingLocation Call Settings: SchedulesLocation Call Settings: VoicemailLocationsMeeting ChatsMeeting Closed CaptionsMeeting InviteesMeeting MessagesMeeting ParticipantsMeeting PollsMeeting PreferencesMeeting Q and AMeeting QualitiesMeeting TranscriptsMeetingsMeetings Summary ReportMembershipsMessagesNumbersOrganization ContactsOrganizationsPSTNPartner ManagementPartner Reports/TemplatesPartner TagsPeopleRecording ReportRecordingsReport TemplatesReportsReports: Detailed Call HistoryResource Group MembershipsResource GroupsRolesRoom TabsRoomsSCIM 2 BulkSCIM 2 GroupsSCIM 2 UsersSecurity Audit EventsSend Activation EmailSession TypesSettingsSiteSpace ClassificationsTeam MembershipsTeamsTracking CodesUCM ProfileUser Call SettingsVideo MeshVirtual Line Call SettingsWebhooksWholesale Billing ReportsWholesale ProvisioningWorkspace Call SettingsWorkspace LocationsWorkspace MetricsWorkspace PersonalizationWorkspacesxAPI
API Changelog
SDKs
Space Meetings Migration
Calling
Introduction
Platform
Web
IntroductionQuickstart
Basics
AuthorizationCore ConceptsCalls
Advanced Features
Call SettingsContactsSupplementary ServicesVoicemailBackground Noise Reduction
Kitchen Sink
Meetings
Introduction
Platform
Web
IntroductionQuickstart
Basics
AuthorizationJoin a MeetingMigration To Improved MeetingsPasswords & CaptchasUnified Space Meetings
Advanced Features
Advanced ControlsDialing In and OutStreams & EffectsVideo Resolution
Multistream
Multistream Comprehensive GuideMultistream Quickstart
Migrating SDK V2 to V3
iOSAndroidBrowserNode.jsClick to Call
Developer CommunityCertifications

SDKs

Creating a Chat Bot with the Node Bot Framework

Learn how to create a chat bot using the Node Bot Framework.

anchorIntroduction

anchor

In this tutorial you'll create a Webex Bot using the Webex Node Bot Framework and the Webex Bot Starter kit. The Node Bot Framework lets developers focus primarily on how the bot will interact with users in Webex, by writing "handlers" for various message or membership events in spaces where the bot has been added. The Webex Bot Starter is an example app that demonstrates use of the Bot Framework.

anchorPrerequisites

anchor

To install or run the chat bot server locally or on a remote host you will need:

  • A GitHub account
  • Git (https://git-scm.com/downloads)
  • Node.js (https://nodejs.org/en/download/)

Alternatively, you can remix and configure an existing Glitch project to quickly spin up a new server. See Deploy the Server using Webhooks for details.

anchorProvision a Bot

anchor

To get started you first need to provision a Bot in the Developer Portal. This involves providing a name, icon and description for your bot. In return you are provided with a bot access token that the Node Bot Framework server uses to make API calls on the bot's behalf.

To provision a bot:

  1. Open the New Bot form on the Developer Portal.

  2. Enter a name, username, and description for your bot, and select a bot icon.

    New bot form

  3. Click Add Bot.

    A bot access token is generated. Copy and save this token for later use.

    Bot access token generated

anchorRun the Starter App Using Websockets

anchor

You can run the Node Bot server in "websocket" mode on your local system, without having to deploy a public service (or configure reverse proxies required for webhooks running on your local system). If the configuration object you pass to the Framework constructor function doesn't contain a webhookUrl field, the framework falls back automatically to websockets. Even if you don't intend to use websockets in your production bot service, it provides a quick way to start creating and testing.

You will need the bot access token generated previously to complete this section.

To run the starter app in websocket mode:

  1. Clone the Webex Bot Starter repository.

    git clone https://github.com/WebexSamples/webex-bot-starter.git
    
  2. Rename config-template.json to config.json. This file contains configuration options for the Node Bot Framework.

  3. Replace the contents of config.json with the following, replacing <BOT_ACCESS_TOKEN> with your bot's access token.

    {
      "token": "<BOT_ACCESS_TOKEN>"
    }
    
  4. Start the server (also installs packages):

    npm start
    ...
    Starting framework, please wait...
    Listening for webex teams events...
    framework is all fired up! [Press CTRL-C to quit]
    

anchorAdd the Bot to a Space

anchor

Of course, to use the bot you created you need to add it to a space. You add a bot to a space just as you would add a person. You can lookup the bot by its "friendly" name or username (bot@)

Adding a bot to a space.

Notice that when the bot is added to the space it introduces itself and provides some hints for how to use it, including a help command.

Bot introducing itself

To get a list of commands supported by the starter bot, send it a message by mentioning it by name (@botname) followed by "help".

Bot help command

If your bot name contains multiple words ("Simple Chat Bot", for example) only the first word in the name is used to tag it (@Simple, for example).

anchorProcess Incoming Messages

anchor

Most of the Node Bot Framework's functionality is based on the framework.hears( ) function. This function lets you define phrases or patterns the bot should respond to, and what actions to take in response. The code below shows the basic pattern for setting up a framework.hears() function.

framework.hears(<phrase>, function(bot, trigger) {
  bot.<command>
    .then(function(returnedValue) {
      // do something with returned value
    })
    .catch(function(err) {
      // handle errors
    });
});
  • <phrase> — A string or regex pattern. If a string, the string is matched against the first word in the room message. message. If a regex pattern is used, it is matched against the entire message text.
  • bot — An instance of the Bot class associated with the Webex space that triggered the framework.hears() call. You use this object to send messages to a room, reply in-line to a message, send direct messages and more.
  • trigger — Provides details about the person, room, and message that caused the function to trigger.
  • bot.<command> — The bot method to execute.
  • then — (Optional) Invoked once the previous command is executed successfully.
  • catch — (Optional) Invoked if any errors occur, either when executing the original command or in any of the chained 'then' functions.

For example, the following example listens for the phrase "hello". In response the bot sends "Hello ". The user's name is provided by the trigger.person.displayName property.

framework.hears("hello", function(bot, trigger) {
  bot.reply(`Hello ${trigger.person.displayName}.`)
});

You can use a regular expression to match multiple phrases.

framework.hears(/hello|hi|hey/i, function(bot, trigger) {
  bot.say(`Hello ${trigger.person.displayName}.`)
});

If multiple hears() handlers matches a given phrase or regex pattern, each handler is invoked in the order that it's defined in the source. This is useful for handling unexpected input.

anchorHandling Unexpected Input

anchor

If the user sends your bot a command that isn't programmed to respond to, it's good practice to provide a "catch all" hears() function. To do this you define a hears() function after all other hears() functions that matches any string (/.*/gim), and a state variable that indicates if the a phrase has already been handled. This works because if multiple hears() handlers match the same phrase or expression then the framework calls them in the order they are defined.

For example, the following shows the basic logic and structure to provide catch all message handler.

// Initialize state variable
var responded = false;
framework.hears('hello', function(bot, trigger) {
  bot.say(`Hi ${trigger.person.displayName}`)
  // Set state variable to true
  responded = true;
});

// This will always match
framework.hears(/.*/gim, function(bot, trigger) {
  // Respond with a 'sorry' message if there wasn't a match
  if (!responded) {
    bot.say('Sorry, I don\'t know how to respond to "%s"', trigger.message.text);
  }
  // Set state variable to false
  responded = false;
});

The catch-all handler must be the last handler defined in the source file or you will get unexpected results.

anchorMake a Webex API Call

anchor

Each bot instance provides a reference to a Webex JavaScript SDK instance that your app can use to make calls against that SDK. For instance, you could use memberships.list() to get a list of members in a space so you can send each a direct message using the bot.dm() method, as shown below.

To send a DM to each user in a space:

  1. Open index.js in the starter bot project.

  2. Add the following code that listens for a poke command.

    framework.hears("poke", function (bot, trigger) {
      responded = true;
      // Use the webex SDK to get the list of users in this space
      bot.webex.memberships.list({roomId: bot.room.id})
        .then((memberships) => {
          for (const member of memberships.items) {
            if (member.personId === bot.person.id) {
              // Skip myself!
              continue;
            }
            // Get name of poker
            let pokerName = (member.personDisplayName) ? member.personDisplayName : member.personEmail;
            bot.dm(member.personId, `You got poked by ${pokerName}`);
          }
        })
        .catch((e) => {
          console.error(`Call to sdk.memberships.get() failed: ${e.messages}`);
        });
    });
    
  3. Save your changes and restart the Node server (npm start).

Once the server indicates it's listening for Webex events, send a "poke" message to the space and tag the bot by name. The bot will send a DM to each member in the space.

anchorDeploy the Bot using Webhooks (Optional)

anchor

You've already seen it's easy to deploy a bot using websockets with the Bot Framework. Alternatively, the framework can also receive events using webhooks. Webhooks must reachable on an open port of a publicly accessible URL (note that websockets do not have this requirement). The Bot Framework makes it easy to switch between webhooks or websockets with a simple configuration change. To initiate the framework using webhooks, add a webhookUrl field to the framework configuration object.

// framework options
var config = {
  webhookUrl: 'https://www.example.com/bothook',
  token: 'Tm90aGluZyB0byBzZWUgaGVyZS4uLiBNb3ZlIGFsb25nLi4u'
};

A slightly modified version of the Node Starter Bot is available on Glitch that you can remix as your own. You just need to assign values to environment variables for your bot access token and webhook URL. See the project's README for setup instructions. The bot will behave identically to when it's using websockets.

Remix on Glitch

To use webhooks with the Node Bot Server running locally, you need to install HTTP tunneling software such as NGrok to forward webhook requests to the locally running instance. For instructions on setting up NGrok see Setting up a Local Web Server from the Blog From Zero to Webex Chatbot in 15 Minutes.

In This Article
  • Introduction
  • Prerequisites
  • Provision a Bot
  • Run the Starter App Using Websockets
  • Add the Bot to a Space
  • Process Incoming Messages
  • Handling Unexpected Input
  • Make a Webex API Call
  • Deploy the Bot using Webhooks (Optional)

Connect

Support

Developer Community

Developer Events

Contact Sales

Handy Links

Webex Ambassadors

Webex App Hub

Resources

Open Source Bot Starter Kits

Download Webex

DevNet Learning Labs

Terms of Service

Privacy Policy

Cookie Policy

Trademarks

© 2025 Cisco and/or its affiliates. All rights reserved.