├── .gitignore ├── docs ├── img │ ├── bot-roomId.png │ ├── bot-helloworld.png │ ├── bot-room-stats.png │ ├── bot-inspect-welcome.png │ ├── cloud9-npm-install.png │ ├── bot-ciscodevnet-next.png │ ├── cloud9-create-webhook.png │ ├── cloud9-env-variables.png │ ├── cloud9-create-workspace.png │ ├── bot-ciscodevnet-now-and-next.png │ ├── postman-create-webhook-all-all.png │ ├── bot-ciscodevnet-now-and-next-BIG.png │ └── spark4devs-create-webhook-all-all.png └── README.md ├── .dockerignore ├── quickstart ├── onEvent-all-all.js ├── onEvent-check-secret.js ├── onMessage-asCommand.js ├── onEvent-messages-created.js ├── README.md ├── onCardSubmission-webhook.js ├── express-webhook.js └── onCommand-webhook.js ├── Makefile ├── package.json ├── Dockerfile ├── LICENSE ├── examples ├── devnet │ ├── README.md │ ├── events.js │ └── bot.js ├── helloworld.js ├── roomid-phantom.js ├── inspector.js └── room-stats.js └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # node artefacts 2 | node_modules/ 3 | npm-debug.log 4 | 5 | # IDE 6 | .idea/ 7 | .vscode/ 8 | -------------------------------------------------------------------------------- /docs/img/bot-roomId.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/bot-roomId.png -------------------------------------------------------------------------------- /docs/img/bot-helloworld.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/bot-helloworld.png -------------------------------------------------------------------------------- /docs/img/bot-room-stats.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/bot-room-stats.png -------------------------------------------------------------------------------- /docs/img/bot-inspect-welcome.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/bot-inspect-welcome.png -------------------------------------------------------------------------------- /docs/img/cloud9-npm-install.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/cloud9-npm-install.png -------------------------------------------------------------------------------- /docs/img/bot-ciscodevnet-next.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/bot-ciscodevnet-next.png -------------------------------------------------------------------------------- /docs/img/cloud9-create-webhook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/cloud9-create-webhook.png -------------------------------------------------------------------------------- /docs/img/cloud9-env-variables.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/cloud9-env-variables.png -------------------------------------------------------------------------------- /docs/img/cloud9-create-workspace.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/cloud9-create-workspace.png -------------------------------------------------------------------------------- /docs/img/bot-ciscodevnet-now-and-next.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/bot-ciscodevnet-now-and-next.png -------------------------------------------------------------------------------- /docs/img/postman-create-webhook-all-all.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/postman-create-webhook-all-all.png -------------------------------------------------------------------------------- /docs/img/bot-ciscodevnet-now-and-next-BIG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/bot-ciscodevnet-now-and-next-BIG.png -------------------------------------------------------------------------------- /docs/img/spark4devs-create-webhook-all-all.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CiscoDevNet/node-sparkbot-samples/HEAD/docs/img/spark4devs-create-webhook-all-all.png -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | .gitignore 3 | .dockerignore 4 | Dockerfile 5 | 6 | docs/ 7 | 8 | Makefile 9 | package.json 10 | node_modules/ 11 | 12 | *.md 13 | *.log 14 | -------------------------------------------------------------------------------- /quickstart/onEvent-all-all.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016-2019 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a bot that listens to all Webex Teams Webhook events 8 | * 9 | */ 10 | 11 | // Starts your Webhook with default configuration 12 | const SparkBot = require("node-sparkbot"); 13 | const bot = new SparkBot(); 14 | 15 | bot.onEvent("all", "all", function(trigger) { 16 | 17 | // 18 | // YOUR CODE HERE 19 | // 20 | console.log("New event (" + trigger.resource + "/" + trigger.event + "), with data id: " + trigger.data.id + ", triggered by person id:" + trigger.actorId); 21 | console.log("Learn more about Webhooks: at https://developer.webex.com/webhooks-explained.html"); 22 | }); 23 | 24 | -------------------------------------------------------------------------------- /quickstart/onEvent-check-secret.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016-2019 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a Webex Teams webhook that leverages a simple library (batteries included) 8 | * 9 | */ 10 | 11 | // Starts your Webhook with default configuration 12 | const SparkBot = require("node-sparkbot"); 13 | const bot = new SparkBot(); 14 | 15 | // Specify the secret to check against incoming payloads 16 | bot.secret = "not THAT secret" 17 | 18 | bot.onEvent("all", "all", function(trigger) { 19 | 20 | // 21 | // YOUR CODE HERE 22 | // 23 | console.log("EVENT: " + trigger.resource + "/" + trigger.event + ", with data id: " + trigger.data.id + ", triggered by person id:" + trigger.actorId); 24 | 25 | }); 26 | 27 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | # Leave as if if you 're just using, customizing or extending the machine 3 | # Change ip to your docker account if you plan to package and release your own docker image 4 | DOCKER_ACCOUNT=objectisadvantag 5 | 6 | # Set this the your Host interface if you use DockerToolbox, otherwise leave it to 127.0.01 7 | DOCKER_HOST_IPADDRESS=192.168.99.100 8 | 9 | 10 | default: dev 11 | 12 | dev: 13 | DEBUG=samples*,sparkbot* node templates/on-event-all-all.js 14 | 15 | run: 16 | (lt -s sparkbot -p 8080 &) 17 | node templates/on-event-all-all.js 18 | 19 | dimage: 20 | docker build -t $(DOCKER_ACCOUNT)/node-sparkbot-samples . 21 | 22 | ddev: 23 | docker run -it -p 8080:8080 $(DOCKER_ACCOUNT)/node-sparkbot-samples 24 | 25 | drun: 26 | (lt -s sparkbot -l $(DOCKER_HOST_IPADDRESS) -p 8080 &) 27 | docker run -it -p 8080:8080 $(DOCKER_ACCOUNT)/node-sparkbot-samples 28 | 29 | 30 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-sparbot-samples", 3 | "version": "v2.1.0", 4 | "description": "Examples of Webex Teams bots in Node.js", 5 | "keywords": [ 6 | "SparkBot", 7 | "Webex Teams", 8 | "Webhook", 9 | "NodeJS", 10 | "Express" 11 | ], 12 | "scripts": { 13 | "start": "node examples/devnet/bot.js" 14 | }, 15 | "homepage": "https://github.com/CiscoDevNet/node-sparkbot-samples#readme", 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/CiscoDevNet/node-sparkbot-samples.git" 19 | }, 20 | "author": "Stève Sfartz (Cisco DevNet)", 21 | "license": "MIT", 22 | "dependencies": { 23 | "body-parser": "^1.19.0", 24 | "debug": "^4.1.1", 25 | "express": "^4.17.1", 26 | "node-sparkbot": "^2.0.0", 27 | "node-sparkclient": "^0.1.4", 28 | "node-sparky": "^4.6.0", 29 | "request": "^2.88.0" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /quickstart/onMessage-asCommand.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016-2019 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a Webex Teams webhook that leverages a simple library (batteries included) 8 | * 9 | * note : this example requires that you've set an ACCESS_TOKEN env variable 10 | * 11 | */ 12 | 13 | // Starts your Webhook with default configuration where the Webex Teams API access token is read from the ACCESS_TOKEN env variable 14 | const SparkBot = require("node-sparkbot"); 15 | const bot = new SparkBot(); 16 | 17 | bot.onMessage(function (trigger, message) { 18 | 19 | // 20 | // ADD YOUR CUSTOM CODE HERE 21 | // 22 | console.log("new message from: " + trigger.data.personEmail + ", text: " + message.text); 23 | 24 | let command = bot.asCommand(message); 25 | if (command) { 26 | console.log("detected command: " + command.keyword + ", with args: " + JSON.stringify(command.args)); 27 | } 28 | }); 29 | 30 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Start from argon (latest long term supported version of node) 2 | # - argon : Full node dev env (640 MB) : python inside 3 | # - argon-slim : Light node env (200 MB) : no python, can be an issue for npm installs / builds 4 | FROM node:argon-slim 5 | 6 | MAINTAINER Stève Sfartz 7 | 8 | EXPOSE 8080 9 | 10 | # create 'not priviledged' user 11 | RUN useradd -c 'Node.js user' -m -d /home/node -s /bin/bash node 12 | 13 | # isolate code distribution 14 | RUN mkdir -p /home/node/sparkbot 15 | WORKDIR /home/node/sparkbot 16 | 17 | # build application 18 | # [TIP] minimize image rebuilds needs by isolating dependencies from declarative aspects 19 | COPY package.json /home/node/sparkbot/package.json 20 | RUN npm install 21 | 22 | # check the .dockerignore file 23 | COPY . /home/node/sparkbot 24 | 25 | # Switch to user mode 26 | RUN chown -R node:node /home/node/sparkbot 27 | USER node 28 | ENV HOME /home/node 29 | ENV SCRIPT templates/onEvent-all-all.js 30 | 31 | # Run default sample 32 | CMD /usr/local/bin/node $SCRIPT 33 | 34 | -------------------------------------------------------------------------------- /quickstart/onEvent-messages-created.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016-2019 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a Webex Teams webhook that leverages a simple library (batteries included) 8 | * 9 | * note : this example requires that you've set an ACCESS_TOKEN env variable 10 | * 11 | */ 12 | 13 | // Starts your Webhook with default configuration where the Webex Teams API access token is read from the ACCESS_TOKEN env variable 14 | const SparkBot = require("node-sparkbot"); 15 | const bot = new SparkBot(); 16 | 17 | bot.onEvent("messages", "created", function(trigger) { 18 | console.log("new message from: " + trigger.data.personEmail + ", in room: " + trigger.data.roomId); 19 | 20 | bot.decryptMessage(trigger, function (err, message) { 21 | 22 | if (err) { 23 | console.log("could not fetch message contents, err: " + err.message); 24 | return; 25 | } 26 | 27 | // 28 | // YOUR CODE HERE 29 | // 30 | console.log("processing message contents: " + message.text); 31 | 32 | }); 33 | 34 | }); 35 | 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Cisco Systems 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /examples/devnet/README.md: -------------------------------------------------------------------------------- 1 | # DevNet Events 2 | 3 | Tells about upcoming DevNet events. 4 | 5 | Invite _CiscoDevNet@sparkbot.io_ to meet the bot. 6 | 7 | ![](../../docs/img/bot-ciscodevnet-now-and-next.png) 8 | 9 | 10 | ## What you can learn here 11 | 12 | Go through the [code](bot.js) to learn how to build a Cisco Spark Bot in NodeJS. 13 | 14 | Less than 100 lines of code, leverages the [node-sparkbot](https://github.com/CiscoDevNet/node-sparkbot) framework: 15 | - Help command to display available commands 16 | - About command to get meta info about the bot 17 | - Welcome message as the bot is added in a room 18 | - Fallback message if a command is not recognized 19 | - Command with integer argument 20 | - Markdown formatting with lists and hyperlinks 21 | - Uses [node-sparky](https://github.com/nmarus/sparky) library to wrap calls to the Cisco Spark REST API 22 | 23 | 24 | ## What about the Event data 25 | 26 | The bot invokes a [public REST Events API](https://devnet-events-api.herokuapp.com/api/v1/events?limit=100) from which Cisco DevNet events are fetched. 27 | 28 | If you need to deploy your own Event API, check the [source code](https://github.com/ObjectIsAdvantag/events-api). 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /quickstart/README.md: -------------------------------------------------------------------------------- 1 | # Templates for the node-sparkbot library 2 | 3 | A set of templates to quickly bootstrap a Webex Teams chatbot: 4 | 5 | - [onEvent-all-all](onEvent-all-all.js), [onEvent-messages-created](onEvent-messages-created.js): examples of listeners to specific Webhook (Resources/Event) triggers. Leverages node-sparkbot function: webhook.onEvent(). 6 | 7 | - [onMessage](onMessage.js): examples of listeners invoked when new message contents are succesfully fetched from Webex Teams. Leverages node-sparkbot function: webhook.onMessage(). 8 | 9 | - [onMessage-asCommand](onMessage-asCommand.js): illustrates how to interpret the message as a bot command. Leverages node-sparkbot function: webhook.onMessage(). 10 | 11 | - [onCommand](onCommand.js): shortcut to listen to a specific command. Leverages node-sparkbot function: webhook.onCommand(). 12 | 13 | 14 | If you're looking for something even lighter, check [express-webhook.js](express-webhook.js) which illustrates how to create a bot from pure nodejs code (without any magic library). 15 | 16 | - [express-webhook](express-webhook.js): a simple HTTP service based on Express, listening to incoming Resource/Events from Webex Teams. 17 | 18 | 19 | ## Run locally 20 | 21 | Each template can be launched from the command line. 22 | 23 | Note that the ACCESS_TOKEN environment variable is required to read message contents. 24 | 25 | Once your bot is started, read this [guide to expose it to the world and create a webhook and start receiving events from Webex](../docs/README.md). 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /quickstart/onCardSubmission-webhook.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2019 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a Webex Teams webhook that leverages a simple library (batteries included) 8 | * note: 9 | * - this example requires that you've set an ACCESS_TOKEN env variable with a Bot access token so that you can submit data from your Webex User account 10 | * - the code creates or updates a webhook that posts data to a publically accessible URL 11 | * 12 | */ 13 | 14 | 15 | // Starts your Webhook with a default configuration where the Webex API access token is read from ACCESS_TOKEN 16 | const SparkBot = require("node-sparkbot"); 17 | const bot = new SparkBot(); 18 | 19 | // Create webhook 20 | const publicURL = process.env.PUBLIC_URL || "https://d3fc85fe.ngrok.io"; 21 | bot.secret = process.env.WEBHOOK_SECRET || "not THAT secret"; 22 | bot.createOrUpdateWebhook("register-bot", publicURL, "attachmentActions", "created", null, bot.secret, function (err, webhook) { 23 | if (err) { 24 | console.error("could not create Webhook, err: " + err); 25 | 26 | // Fail fast 27 | process.exit(1); 28 | } 29 | 30 | console.log("webhook successfully checked, with id: " + webhook.id); 31 | }); 32 | 33 | bot.onCardSubmission(function (trigger, attachmentActions) { 34 | 35 | // 36 | // ADD YOUR CUSTOM CODE HERE 37 | // 38 | console.log(`new attachmentActions from personId: ${trigger.data.personId} , with inputs`); 39 | Object.keys(attachmentActions.inputs).forEach(prop => { 40 | console.log(` ${prop}: ${attachmentActions.inputs[prop]}`); 41 | }); 42 | 43 | }); 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /quickstart/express-webhook.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016-2019 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a Webex Teams webhook based on pure Express.js. 8 | * 9 | * goal here is to illustrate how to create a bot without any library 10 | * 11 | */ 12 | 13 | const express = require("express"); 14 | const app = express(); 15 | 16 | const bodyParser = require("body-parser"); 17 | app.use(bodyParser.urlencoded({extended: true})); 18 | app.use(bodyParser.json()); 19 | 20 | const debug = require("debug")("samples"); 21 | 22 | const started = Date.now(); 23 | app.route("/") 24 | // healthcheck 25 | .get(function (req, res) { 26 | res.json({ 27 | message: "Congrats, your bot is up and running", 28 | since: new Date(started).toISOString(), 29 | code: "express-all-in-one.js", 30 | tip: "Register your bot as a WebHook to start receiving events: https://developer.webex.com/endpoint-webhooks-post.html" 31 | }); 32 | }) 33 | 34 | // webhook endpoint 35 | .post(function (req, res) { 36 | 37 | // analyse incoming payload, should conform to Webex Teams webhook trigger specifications 38 | debug("DEBUG: webhook invoked"); 39 | if (!req.body || !Utils.checkWebhookEvent(req.body)) { 40 | console.log("WARNING: Unexpected payload POSTed, aborting..."); 41 | res.status(400).json({message: "Bad payload for Webhook", 42 | details: "either the bot is misconfigured or Webex Teams is running a new API version"}); 43 | return; 44 | } 45 | 46 | // event is ready to be processed, let's send a response to Webex without waiting any longer 47 | res.status(200).json({message: "message is being processed by webhook"}); 48 | 49 | // process incoming resource/event, see https://developer.webex.com/webhooks-explained.html 50 | processWebhookEvent(req.body); 51 | }); 52 | 53 | 54 | // Starts the Bot service 55 | // 56 | // [WORKAROUND] in some container situation (ie, Cisco Shipped), we need to use an OVERRIDE_PORT to force our bot to start and listen to the port defined in the Dockerfile (ie, EXPOSE), 57 | // and not the PORT dynamically assigned by the host or scheduler. 58 | const port = process.env.OVERRIDE_PORT || process.env.PORT || 8080; 59 | app.listen(port, function () { 60 | console.log("Webex Teams bot started at http://localhost:" + port + "/"); 61 | console.log(" GET / for health checks"); 62 | console.log(" POST / to procress new Webhook events"); 63 | }); 64 | 65 | 66 | // Invoked when the webhook is triggered 67 | function processWebhookEvent(trigger) { 68 | 69 | // 70 | // YOUR CODE HERE 71 | // 72 | console.log("EVENT: " + trigger.resource + "/" + trigger.event + ", with data id: " + trigger.data.id + ", triggered by person id:" + trigger.actorId); 73 | 74 | } -------------------------------------------------------------------------------- /quickstart/onCommand-webhook.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016-2019 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a Webex Teams webhook that leverages a simple library (batteries included) 8 | * 9 | * note : this example requires that you've set a ACCESS_TOKEN env variable 10 | * 11 | */ 12 | 13 | const SparkBot = require("node-sparkbot"); 14 | 15 | // Starts your Webhook with default configuration where the Webex Teams API access token is read from the SPARK_TOKEN env variable 16 | const bot = new SparkBot(); 17 | 18 | // Registers the bot to the Webex platform to start receiving notifications 19 | // We list here various options to register your bot: pick one and update the code with your bot name and its public endpoint 20 | 21 | // Simplissime registration where defaults apply (all, all, no filter, no secret), and no callback 22 | //bot.createOrUpdateWebhook("register-bot", "https://f6d5d937.ngrok.io"); 23 | 24 | // Registration without any filter, secret, and callback 25 | //bot.createOrUpdateWebhook("register-bot", "https://f6d5d937.ngrok.io", "all", "all"); 26 | 27 | // Registration with a filter, no secret, no callback 28 | //bot.createOrUpdateWebhook("register-bot", "https://f6d5d937.ngrok.io", "all", "all", "roomId=XXXXXXXXXXXXXXX"); 29 | 30 | // Registration with no filter, but a secret and a callback 31 | // note that the secret needs to be known to the bot so that it can check the payload signatures 32 | const publicURL = process.env.PUBLIC_URL || "https://f6d5d937.ngrok.io"; 33 | bot.secret = process.env.WEBHOOK_SECRET || "not THAT secret"; 34 | bot.createOrUpdateWebhook("register-bot", publicURL, "all", "all", null, bot.secret, function (err, webhook) { 35 | if (err) { 36 | console.error("could not create Webhook, err: " + err); 37 | 38 | // Fail fast 39 | process.exit(1); 40 | } 41 | 42 | console.log("webhook successfully checked, with id: " + webhook.id); 43 | }); 44 | 45 | // Registration with no filter, but a secret and a callback 46 | // bot name and public endpoint are read from env variables, the WEBHOOK_SECRET env variable is used to initialize the secret 47 | // make sure to initialize these env variables 48 | // - BOT_NAME="register-bot" 49 | // - WEBHOOK_SECRET="not THAT secret" 50 | // - PUBLIC_URL="https://f6d5d937.ngrok.io" 51 | // example: 52 | // DEBUG=sparkbot* BOT_NAME="register-bot" PUBLIC_URL="https://f6d5d937.ngrok.io" WEBHOOK_SECRET="not THAT secret" ACCESS_TOKEN="MjdkYjRhNGItM2E1ZS00YmZjLTk2ZmQtO" node tests/onCommand-register.js 53 | //bot.createOrUpdateWebhook(process.env.BOT_NAME, process.env.PUBLIC_URL, "all", "all", null, bot.secret, function (err, webhook) { 54 | // if (err) { 55 | // console.log("Could not register the bot, please check your env variables are all set: ACCESS_TOKEN, BOT_NAME, PUBLIC_URL"); 56 | // return; 57 | // } 58 | // console.log("webhook successfully created, id: " + webhook.id); 59 | //}); 60 | 61 | 62 | // Override default prefix "/" to "" so that our bot will obey to "help"" instead of "/help" 63 | bot.interpreter.prefix=""; 64 | 65 | bot.onCommand("help", function(command) { 66 | // ADD YOUR CUSTOM CODE HERE 67 | console.log("new command: " + command.keyword + ", from: " + command.message.personEmail + ", with args: " + JSON.stringify(command.args)); 68 | }); 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /examples/devnet/events.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | var debug = require("debug")("samples"); 7 | var fine = require("debug")("samples:fine"); 8 | 9 | var request = require("request"); 10 | 11 | 12 | module.exports.fetchNext = function(limit, cb) { 13 | 14 | // Get list of upcoming events 15 | var options = { 16 | method: 'GET', 17 | url: "https://devnet-events-api.herokuapp.com/api/v1/events/next?limit=" + limit 18 | }; 19 | 20 | request(options, function (error, response, body) { 21 | if (error) { 22 | debug("could not retreive list of events, error: " + error); 23 | cb(new Error("Could not retreive upcoming events, sorry [Events API not responding]"), null); 24 | return; 25 | } 26 | 27 | if ((response < 200) || (response > 299)) { 28 | console.log("could not retreive list of events, response: " + response); 29 | sparkCallback(new Error("Could not retreive upcoming events, sorry [bad anwser from Events API]"), null); 30 | return; 31 | } 32 | 33 | var events = JSON.parse(body); 34 | debug("fetched " + events.length + " events"); 35 | fine(JSON.stringify(events)); 36 | 37 | if (events.length == 0) { 38 | cb(null, "**Guess what? No upcoming event!**"); 39 | return; 40 | } 41 | 42 | var nb = events.length; 43 | var msg = "**" + nb + " upcoming events:**"; 44 | if (nb == 1) { 45 | msg = "**1 upcoming event:**"; 46 | } 47 | for (var i = 0; i < nb; i++) { 48 | var current = events[i]; 49 | msg += "\n- " + current.beginDay + " - " + current.endDay + ": [" + current.name + "](" + current.url + "), " + current.city + " (" + current.country + ")"; 50 | } 51 | 52 | cb(null, msg); 53 | }); 54 | } 55 | 56 | 57 | module.exports.fetchCurrent = function (cb) { 58 | 59 | // Get list of upcoming events 60 | var options = { 61 | method: 'GET', 62 | url: "https://devnet-events-api.herokuapp.com/api/v1/events/current" 63 | }; 64 | 65 | request(options, function (error, response, body) { 66 | if (error) { 67 | debug("could not retreive list of events, error: " + error); 68 | cb(new Error("Could not retreive current events, sorry [Events API not responding]"), null); 69 | return; 70 | } 71 | 72 | if ((response < 200) || (response > 299)) { 73 | console.log("could not retreive list of events, response: " + response); 74 | sparkCallback(new Error("Could not retreive current events, sorry [bad anwser from Events API]"), null); 75 | return; 76 | } 77 | 78 | var events = JSON.parse(body); 79 | debug("fetched " + events.length + " events"); 80 | fine(JSON.stringify(events)); 81 | 82 | if (events.length == 0) { 83 | cb(null, "**No event is currently going on. May you check for upcoming events...**"); 84 | return; 85 | } 86 | 87 | var nb = events.length; 88 | var msg = "**" + nb + " events are running now:**"; 89 | if (nb == 1) { 90 | msg = "**1 event is running now:**"; 91 | } 92 | for (var i = 0; i < nb; i++) { 93 | var current = events[i]; 94 | msg += "\n- " + current.beginDay + " - " + current.endDay + ": [" + current.name + "](" + current.url + "), " + current.city + " (" + current.country + ")"; 95 | } 96 | 97 | cb(null, msg); 98 | }); 99 | } 100 | 101 | 102 | -------------------------------------------------------------------------------- /examples/helloworld.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a Webex Teams bot that: 8 | * - sends a welcome message as he joins a room, 9 | * - answers to a /hello command, and greets the user that chatted him 10 | * - supports /help and a 'fallback' helper message 11 | * 12 | * + leverages the "node-sparkclient" library for bot to Webex communications. 13 | * 14 | */ 15 | 16 | const WebexChatBot = require("node-sparkbot"); 17 | const bot = new WebexChatBot(); 18 | 19 | // Remove comment to overload default '/' prefix to identify bot commands 20 | //bot.interpreter.prefix = "#"; 21 | 22 | const SparkAPIWrapper = require("node-sparkclient"); 23 | if (!process.env.ACCESS_TOKEN) { 24 | console.log("Could not start as this bot requires a Webex Teams API access token."); 25 | console.log("Please add env variable ACCESS_TOKEN on the command line"); 26 | console.log("Example: "); 27 | console.log("> ACCESS_TOKEN=XXXXXXXXXXXX DEBUG=sparkbot* node helloworld.js"); 28 | process.exit(1); 29 | } 30 | const client = new SparkAPIWrapper(process.env.ACCESS_TOKEN); 31 | 32 | 33 | // 34 | // Help and fallback commands 35 | // 36 | bot.onCommand("help", function (command) { 37 | client.createMessage(command.message.roomId, "Hi, I am the Hello World bot !\n\nType /hello to see me in action.", { "markdown":true }, function(err, message) { 38 | if (err) { 39 | console.log("WARNING: could not post message to room: " + command.message.roomId); 40 | return; 41 | } 42 | }); 43 | }); 44 | bot.onCommand("fallback", function (command) { 45 | client.createMessage(command.message.roomId, "Sorry, I did not understand.\n\nTry /help.", { "markdown":true }, function(err, response) { 46 | if (err) { 47 | console.log("WARNING: could not post Fallback message to room: " + command.message.roomId); 48 | return; 49 | } 50 | }); 51 | }); 52 | 53 | 54 | // 55 | // Bots commands here 56 | // 57 | bot.onCommand("hello", function (command) { 58 | let email = command.message.personEmail; // User that created the message orginally 59 | client.createMessage(command.message.roomId, `Hello, your email is: **${email}**`, { "markdown":true }, function(err, message) { 60 | if (err) { 61 | console.log("WARNING: could not post message to room: " + command.message.roomId); 62 | return; 63 | } 64 | }); 65 | }); 66 | 67 | 68 | // 69 | // Welcome message 70 | // sent as the bot is added to a Room 71 | // 72 | bot.onEvent("memberships", "created", function (trigger) { 73 | let newMembership = trigger.data; // see specs here: https://developer.webex.com/endpoint-memberships-get.html 74 | if (newMembership.personId != bot.interpreter.person.id) { 75 | // ignoring 76 | console.log("new membership fired, but it is not us being added to a room. Ignoring..."); 77 | return; 78 | } 79 | 80 | // so happy to join 81 | console.log("bot's just added to room: " + trigger.data.roomId); 82 | 83 | client.createMessage(trigger.data.roomId, "Hi, I am the Hello World bot !\n\nType /hello to see me in action.", { "markdown":true }, function(err, message) { 84 | if (err) { 85 | console.log("WARNING: could not post Hello message to room: " + trigger.data.roomId); 86 | return; 87 | } 88 | 89 | if (message.roomType == "group") { 90 | client.createMessage(trigger.data.roomId, "**Note that this is a 'Group' room. I will wake up only when mentionned.**", { "markdown":true }, function(err, message) { 91 | if (err) { 92 | console.log("WARNING: could not post Mention message to room: " + trigger.data.roomId); 93 | return; 94 | } 95 | }); 96 | } 97 | }); 98 | }); 99 | 100 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Webex Teams Chatbot examples in Node.js 2 | 3 | Interested in creating your own Webex Teams Chatbots ? 4 | Go through the examples below. 5 | 6 | If you feel inspired, run your own version of these bots. 7 | Simply take the step-by-step tutorials at DevNet: [Run a Webex Teams bot locally](https://learninglabs.cisco.com/tracks/collab-cloud/spark-apps/collab-spark-botl-ngrok/step/1). 8 | 9 | Then, pick a [template](templates/) that suits your scenario, and customize it. 10 | 11 | Note that these bot samples leverage the [node-sparkbot](https://github.com/CiscoDevNet/node-sparkbot) Chatbot framework. 12 | 13 | __Also, if you're new to Webex Teams API, note that DevNet provides a full learning track: [Learning track](https://learninglabs.cisco.com/tracks/collab-cloud).__ 14 | 15 | 16 | 17 | ## [inspect](examples/inspector.js) 18 | 19 | Provides instant access to Webex Teams technical data (such as the space id, or the email of a space participant). 20 | 21 | Features illustrated by this example: 22 | - **Help command to display available commands** 23 | - **About command to get meta info about the bot** 24 | - **Welcome message as the bot is added in a room** 25 | - **Fallback message if a command is not recognized** 26 | - Uses the "node-sparky" library to requests the Webex Teams API 27 | 28 | This bot can be run as is with either a Developer or a Bot access token 29 | 30 | Invite _inspect@webex.bot_ to meet the bot. 31 | 32 | ![](docs/img/bot-inspect-welcome.png) 33 | 34 | 35 | 36 | ## [roomId](examples/roomid-phantom.js) 37 | 38 | Fetches the identifier of the space in which this bot has just been added, 39 | pushes the roomId via a direct message, and leaves the inquired space right away. 40 | 41 | Features illustrated by this example: 42 | - Help command to display available commands 43 | - About command to get meta info about the bot 44 | - Fallback message if a command is not recognized 45 | - **Send a direct message and leaves the room** 46 | - Uses "node-sparky" library to interact with Webex Teams 47 | 48 | Invite _roomid@webex.io_ to meet the bot. 49 | 50 | ![](docs/img/bot-roomId.png) 51 | 52 | 53 | 54 | ## [room-stats](examples/room-stats.js) 55 | 56 | Computes stats for the space it is invoked from. 57 | 58 | Features illustrated by this example: 59 | - Help message to display bot commands 60 | - Welcome message as the bot is added in a room 61 | - **Custom command prefix #** 62 | - **Markdown formatting with lists & mentions** 63 | - **Runs with a Developer account** 64 | - Uses "node-sparky" library to invoke the Webex Teams API 65 | 66 | Note that this webhook must be run with a personal access token (from a fake Webex Teams account), because the bot must be able to fetch all messages from spaces, not only those for which bot is mentionned. 67 | 68 | Invite _stats@chatbot.land_ to meet the bot. 69 | 70 | ![](docs/img/bot-room-stats.png) 71 | 72 | 73 | 74 | ## [events](examples/devnet/bot.js) 75 | 76 | Tells you about upcoming DevNet events. 77 | 78 | Features illustrated by this example: 79 | - Help command to display available commands 80 | - About command to get meta info about the bot 81 | - Welcome message as the bot is added in a room 82 | - Fallback message if a command is not recognized 83 | - **Command with integer argument** 84 | - **Markdown formatting with lists and hyperlinks** 85 | - Uses "node-sparky" library to wrap calls to the Webex Teams REST API 86 | 87 | Invite _CiscoDevNet@webex.bot_ to meet the bot. 88 | 89 | ![](docs/img/bot-ciscodevnet-next.png) 90 | 91 | 92 | 93 | ## [helloworld](examples/helloworld.js) 94 | 95 | A simple template to start from. 96 | 97 | Features illustrated by this example: 98 | - Welcome message as the bot is added in a room 99 | - Help command to display available commands 100 | - Fallback message if a command is not recognized 101 | - Markdown formatting 102 | - Leverages the "node-sparkclient" library to wrap calls to the Webex Teams REST API 103 | 104 | This bot can be run as is with either a Developer or a Bot access token 105 | 106 | ![](docs/img/bot-helloworld.png) -------------------------------------------------------------------------------- /examples/roomid-phantom.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a bot that gives you instant info about a room id 8 | * 9 | * note : this example could work with both a human (developer) or a bot account, 10 | * but the philosophy of this bot is really to use it with a bot account 11 | * 12 | */ 13 | 14 | const debug = require("debug")("samples"); 15 | const fine = require("debug")("samples:fine"); 16 | 17 | // Starts your Bot with default configuration. The Webex Teams API access token is read from the ACCESS_TOKEN env variable 18 | const WebexChatBot = require("node-sparkbot"); 19 | const bot = new WebexChatBot(); 20 | 21 | // do not listen to ourselves 22 | // uncomment if you're running the bot from your Developer access token and you want to invoke in a 1-1 room 23 | //bot.interpreter.ignoreSelf = false; 24 | 25 | // Removing the bot default triggering '/' filter 26 | bot.interpreter.prefix = ""; 27 | 28 | const SparkClient = require("node-sparky"); 29 | const sparky = new SparkClient({ token: process.env.ACCESS_TOKEN }); 30 | 31 | 32 | bot.onCommand("about", function (command) { 33 | sparky.messageSend({ 34 | roomId: command.message.roomId, 35 | markdown: "```\n{\n 'author':'Stève Sfartz ',\n 'code':'https://github.com/CiscoDevNet/node-sparkbot-samples/blob/master/examples/roomid-phantom.js',\n 'description':'a handy tool to retreive Webex Teams space identifiers',\n 'healthcheck':'GET https://sparkbot-roomid.herokuapp.com',\n 'webhook':'POST https://sparkbot-roomid.herokuapp.com'\n}\n```" 36 | }); 37 | }); 38 | 39 | 40 | bot.onCommand("fallback", function (command) { 41 | // so happy to join 42 | sparky.messageSend({ 43 | roomId: command.message.roomId, 44 | text: "sorry, I did not understand. Try help." 45 | }) 46 | .then(function (message) { 47 | // show how to use 48 | showHelp(command.message.roomId); 49 | }); 50 | }); 51 | bot.onCommand("help", function (command) { 52 | showHelp(command.message.roomId); 53 | }); 54 | function showHelp(roomId) { 55 | sparky.messageSend({ 56 | roomId: roomId, 57 | markdown: "Well, I am an ephemeral bot, serving developers. My primary mission is to fetch identifiers: add me to a space, and I'll send back - the room's identifier - in a private 1-1 message, then will silently leave the space I just got added to.\n\nAlso, be aware that my skills are limited:\n- about\n- help" 58 | }); 59 | } 60 | 61 | 62 | 63 | bot.onEvent("memberships", "created", function (trigger) { 64 | let newMembership = trigger.data; // see specs here: https://developer.webex.com/endpoint-memberships-get.html 65 | if (newMembership.personId == bot.interpreter.person.id) { 66 | debug("bot has just been added to space: " + trigger.data.roomId); 67 | 68 | // only take action if it is not the bot who created the room, to send the message back 69 | if (trigger.actorId != bot.interpreter.person.id) { 70 | 71 | // Retreive actorEmail 72 | sparky.personGet(trigger.actorId) 73 | .then(function (person) { 74 | let email = person.emails[0]; 75 | debug("found inquirer: " + email); 76 | 77 | // Send a direct message 78 | sparky.messageSend({ 79 | toPersonEmail: email, 80 | markdown: "Found roomId: **" + newMembership.roomId + "**\n\nWill now leave the space you asked me to inquire on..." 81 | }) 82 | .then(function (message) { 83 | 84 | // Leave inquired room 85 | sparky.membershipRemove(newMembership.id) 86 | .then(function () { 87 | sparky.messageSend({ 88 | toPersonEmail: email, 89 | markdown: "Job done: I have silently left the space... Let me know when you need other identifiers ;-)" 90 | }); 91 | }) 92 | }); 93 | }) 94 | } 95 | } 96 | }); 97 | 98 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # How to Guide: run your Webex Teams Bot 2 | 3 | This guide details how to run your bot locally (ie, running on a dev machine or a private network), and make it talk with the Webex cloud platform. 4 | 1. Start you bot 5 | 2. Check your bot is healthy 6 | 3. Expose your bot 7 | 4. Create a webhook 8 | 9 | 10 | ## Start you bot 11 | 12 | **Skip this (if you have already started your bot)** 13 | 14 | Here are the steps to install this project samples and run them 15 | 16 | 1. Clone the repo 17 | 2. Install dependencies 18 | 3. Run an example 19 | 20 | ``` bash 21 | # Clone repo 22 | > git clone https://github.com/CiscoDevNet/node-sparkbot-samples 23 | # Install dependencies 24 | > cd node-sparkbot-samples 25 | > npm install 26 | # Run an example 27 | # add an ACCESS_TOKEN environment variable to configure your bot with the Webex Teams API access token of your bot account 28 | > DEBUG=sparkbot*,samples* ACCESS_TOKEN=123456789 node templates/onEvent-all-all.js 29 | ... 30 | bot started at http://localhost:8080/ 31 | GET / for health checks 32 | POST / receives Webhook events 33 | ``` 34 | 35 | ## Check your bot is healthy 36 | 37 | Hit localhost to check your bot is running, either via [your Web browser](http://localhost:8080) or via CURL (see below) 38 | You should get back an JSON payload with your bot properties. 39 | 40 | ``` bash 41 | # Ping your bot 42 | > curl http://localhost:8080 43 | ... 44 | { 45 | "message": "Congrats, your webhook is up and running", 46 | "since": "2016-09-01T13:15:39.425Z", 47 | "listeners": [ 48 | ... 49 | ``` 50 | 51 | 52 | ## Expose you bot 53 | 54 | To expose your boot on the internet, we'll leverage a tunnelling tool. 55 | You may pick any tool, the steps below leverage localtunnel. 56 | 57 | There you need to choose a unique subdomain name, which localtunnel will use to create your bot public internel URL. 58 | 59 | Replace **** in the following steps by your bot subdomain name. 60 | 61 | Note : make sure you hit your bot **secured** HTTPS endpoint. 62 | 63 | 64 | ``` bash 65 | # Install local tunnel 66 | > npm install localtunnel -g 67 | # Create the tunnel 68 | > lt -s -p 8080 69 | your url is: http://.localtunnel.me 70 | 71 | # In another terminal, check your bot is accessible 72 | > curl https://.localtunnel.me/ 73 | { 74 | "message": "Congrats, your bot is up and running", 75 | "since": "2016-09-01T13:15:39.425Z", 76 | "tip": "Register your bot as a WebHook to start receiving events: https://developer.webex.com/endpoint-webhooks-post.html", 77 | "listeners": [ 78 | "messages/created" 79 | ], 80 | "token": true, 81 | "account": { 82 | "type": "human", 83 | "person": { 84 | "id": "Y2lzY29zcGFyazovL3VzL1BFT1BMRS85MmIzZGQ5YS02NzVkLTRhNDEtOGM0MS0yYWJkZjg5ZjQ0ZjQ", 85 | "emails": [ 86 | "stsfartz@cisco.com" 87 | ], 88 | "displayName": "Steve Sfartz", 89 | "avatar": "https://1efa7a94ed216783e352-c62266528714497a17239ececf39e9e2.ssl.cf1.rackcdn.com/V1~c2582d2fb9d11e359e02b12c17800f09~aqSu09sCTVOOx45HJCbWHg==~1600", 90 | "created": "2016-02-04T15:46:20.321Z" 91 | } 92 | }, 93 | "interpreter": { 94 | "prefix": "/", 95 | "trimMention": true, 96 | "ignoreSelf": false 97 | }, 98 | "commands": [ 99 | "help" 100 | ] 101 | } 102 | ``` 103 | 104 | 105 | ## Register a webhook for your bot 106 | 107 | Last step, is to create a Webhook for your bot to start receiving events for Webex Teams. 108 | 109 | This can be done via the Webex Developer Portal / [Create a WebHook](https://developer.webex.com/endpoint-webhooks-post.html) interactive documentation, 110 | but also via Postman or a CURL command as will see right after. 111 | 112 | ### via the interactive documentation 113 | 114 | For the scope of this example, we'll associate our bot to all resources and events. 115 | 116 | Note: even if our webhook can process all events, you can register a webhook with a more limited set of events. Then Webex will then invoke your webhook only if those events happen (whatever your bot can process). 117 | 118 | ![](img/spark4devs-create-webhook-all-all.png) 119 | 120 | 121 | ### via CURL 122 | 123 | As an alternative, you can run this CURL command. 124 | 125 | ``` bash 126 | > curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer YOUR_SPARK_TOKEN" -d '{ 127 | "name": "Bot Samples", 128 | "resource": "all", 129 | "event": "all", 130 | "targetUrl": "https://yourbot.localtunnel.me/" 131 | }' "https://api.ciscospark.com/v1/webhooks/" 132 | ``` 133 | 134 | 135 | ### via postman 136 | 137 | Or you can also create this webhook via Postman. 138 | 139 | ![](img/postman-create-webhook-all-all.png) 140 | 141 | 142 | -------------------------------------------------------------------------------- /examples/inspector.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a bot that gives you instant access to Webex Teams technical data 8 | * 9 | * note : this example can work with any type of token (from a developer or bot account) 10 | * 11 | */ 12 | 13 | const debug = require("debug")("samples"); 14 | const fine = require("debug")("samples:fine"); 15 | 16 | // Start your Bot with default configuration where the Webex Teams API access token is read from the ACCESS_TOKEN env variable 17 | const WebexChatBot = require("node-sparkbot"); 18 | const bot = new WebexChatBot(); 19 | 20 | // Do not listen to ourselves 21 | // Uncomment if you're running the bot a 'User' developer access token 22 | //bot.interpreter.ignoreSelf = false; 23 | 24 | // Overloading the bot default triggering '/' filter 25 | bot.interpreter.prefix = ""; // no prefix 26 | 27 | const SparkClient = require("node-sparky"); 28 | const sparky = new SparkClient({ token: process.env.ACCESS_TOKEN || process.env.SPARK_TOKEN }); 29 | 30 | 31 | bot.onCommand("about", function (command) { 32 | sparky.messageSend({ 33 | roomId: command.message.roomId, 34 | markdown: "```\n{\n 'author':'Stève Sfartz ',\n 'code':'https://github.com/CiscoDevNet/node-sparkbot-samples/blob/master/examples/inspector.js',\n 'description':'an handy tool to reveal Webex Teams technical data',\n 'healthcheck':'GET https://sparkbot-inspector.herokuapp.com',\n 'webhook':'POST https://sparkbot-inspector.herokuapp.com'\n}\n```" 35 | }); 36 | }); 37 | 38 | 39 | bot.onCommand("fallback", function (command) { 40 | // so happy to join 41 | sparky.messageSend({ 42 | roomId: command.message.roomId, 43 | text: "sorry, I did not understand" 44 | }) 45 | .then(function (message) { 46 | // show how to use 47 | showHelp(command.message.roomId); 48 | }); 49 | }); 50 | bot.onCommand("help", function (command) { 51 | showHelp(command.message.roomId); 52 | }); 53 | function showHelp(roomId) { 54 | sparky.messageSend({ 55 | roomId: roomId, 56 | markdown: "I can give you quick access to Webex Teams technical data. Simply type:\n- **about**\n- **help**\n- **roomId**: reveals this room identifier\n- **whoami**: shows your account info\n- **whois @mention**: inquire about other participants" 57 | }); 58 | } 59 | 60 | 61 | bot.onCommand("roomId", function (command) { 62 | sparky.messageSend({ 63 | roomId: command.message.roomId, 64 | markdown: "roomId: " + command.message.roomId 65 | }); 66 | }); 67 | 68 | 69 | bot.onCommand("whoami", function (command) { 70 | sparky.messageSend({ 71 | roomId: command.message.roomId, 72 | markdown: "personId: " + command.message.personId + "\n\nemail: " + command.message.personEmail 73 | }); 74 | }); 75 | 76 | 77 | bot.onCommand("whois", function (command) { 78 | // Check usage 79 | if ((!command.message.mentionedPeople) || (command.message.mentionedPeople.length != 2)) { 80 | sparky.messageSend({ 81 | roomId: command.message.roomId, 82 | markdown: "sorry, I cannot proceed if you do not mention a room participant" 83 | }); 84 | return; 85 | } 86 | 87 | let participant = command.message.mentionedPeople[1]; 88 | 89 | sparky.personGet(participant).then(function (person) { 90 | sparky.messageSend({ 91 | roomId: command.message.roomId, 92 | markdown: "personId: " + person.id + "\n\ndisplayName: " + person.displayName + "\n\nemail: " + person.emails[0] 93 | }); 94 | }); 95 | }); 96 | 97 | 98 | bot.onEvent("memberships", "created", function (trigger) { 99 | let newMembership = trigger.data; // see specs here: https://developer.ciscosparky.com/endpoint-memberships-get.html 100 | if (newMembership.personId == bot.interpreter.person.id) { 101 | debug("bot's just added to room: " + trigger.data.roomId); 102 | 103 | // so happy to join 104 | sparky.messageSend({ 105 | roomId: trigger.data.roomId, 106 | text: "Hi, I am the Inspector Bot!" 107 | }) 108 | .then(function (message) { 109 | if (message.roomType == "group") { 110 | sparky.messageSend({ 111 | roomId: message.roomId, 112 | markdown: "**Note that this is a 'Group' room. I will wake up only when mentionned.**" 113 | }) 114 | .then(function (message) { 115 | showHelp(message.roomId); 116 | }); 117 | } 118 | else { 119 | showHelp(message.roomId); 120 | } 121 | }); 122 | } 123 | }); 124 | -------------------------------------------------------------------------------- /examples/devnet/bot.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a bot to list current and upcoming DevNet events 8 | * 9 | * reads events from a REST API which reflects https://developer.cisco.com/site/devnet/events-contests/events/ 10 | * 11 | */ 12 | 13 | var debug = require("debug")("samples"); 14 | var fine = require("debug")("samples:fine"); 15 | 16 | // Starts a bot with default configuration, access token read from the ACCESS_TOKEN env variable 17 | var SparkBot = require("node-sparkbot"); 18 | var bot = new SparkBot(); 19 | // removing the bot default triggering filter 20 | bot.interpreter.prefix = ""; // not more "/" prepend to commands 21 | 22 | // nodejs client to write back to Cisco Spark 23 | var SparkClient = require("node-sparky"); 24 | var sparky = new SparkClient({ token: process.env.ACCESS_TOKEN }); 25 | 26 | // event API wrapper that preformats markdown messages to send back to Webex Teams 27 | var Events = require("./events.js"); 28 | 29 | 30 | 31 | bot.onCommand("help", function (command) { 32 | showHelp(command.message.roomId); 33 | }); 34 | bot.onCommand("fallback", function (command) { 35 | // so happy to join 36 | sparky.messageSend({ 37 | roomId: command.message.roomId, 38 | markdown: "**sorry, I did not understand.**" 39 | }) 40 | .then(function (message) { 41 | // show how to use 42 | showHelp(command.message.roomId); 43 | }); 44 | }); 45 | function showHelp(roomId) { 46 | sparky.messageSend({ 47 | roomId: roomId, 48 | markdown: "I can tell about upcoming events at DevNet. Try:\n- about\n- help\n- next [#max]: upcoming events, defaults to 5\n- now: events happening now\n" 49 | }); 50 | } 51 | 52 | 53 | bot.onCommand("about", function (command) { 54 | sparky.messageSend({ 55 | roomId: command.message.roomId, 56 | markdown: "```\n{\n 'author':'Stève Sfartz ',\n 'code':'https://github.com/CiscoDevNet/node-sparkbot-samples/blob/master/examples/devnet/bot.js',\n 'description':'inquire about upcoming events at DevNet',\n 'healthcheck':'GET https://devnet-events-sparkbot.herokuapp.com'\n}\n```" 57 | }); 58 | }); 59 | 60 | bot.onCommand("next", function (command) { 61 | 62 | // let's acknowledge we received the order 63 | sparky.messageSend({ 64 | roomId: command.message.roomId, 65 | markdown: "_heard you! asking my crystal ball..._" 66 | }); 67 | 68 | var limit = parseInt(command.args[0]); 69 | if (!limit) limit = 5; 70 | if (limit < 1) limit = 1; 71 | 72 | Events.fetchNext(limit, function (err, events) { 73 | if (err) { 74 | sparky.messageSend( { 75 | roomId: command.message.roomId, 76 | markdown: "**sorry, ball seems broken :-(**" 77 | }); 78 | return; 79 | } 80 | 81 | sparky.messageSend({ 82 | roomId: command.message.roomId, 83 | markdown: events 84 | }); 85 | }); 86 | }); 87 | 88 | 89 | bot.onCommand("now", function (command) { 90 | // let's acknowledge we received the order 91 | sparky.messageSend({ 92 | roomId: command.message.roomId, 93 | markdown: "_heard you! let's check what's happening now..._" 94 | }); 95 | 96 | Events.fetchCurrent(function (err, events) { 97 | if (err) { 98 | sparky.messageSend({ 99 | roomId: command.message.roomId, 100 | markdown: "**sorry, could not contact the organizers :-(**" 101 | }); 102 | return; 103 | } 104 | 105 | sparky.messageSend({ 106 | roomId: command.message.roomId, 107 | markdown: events 108 | }); 109 | }); 110 | }); 111 | 112 | 113 | bot.onEvent("memberships", "created", function (trigger) { 114 | var newMembership = trigger.data; // see specs here: https://developer.webex.com/endpoint-memberships-get.html 115 | if (newMembership.personId == bot.interpreter.person.id) { 116 | debug("bot's just added to room: " + trigger.data.roomId); 117 | 118 | // so happy to join 119 | sparky.messageSend({ 120 | roomId: trigger.data.roomId, 121 | text: "Hi, I am the DevNet Bot !" 122 | }) 123 | .then(function (message) { 124 | if (message.roomType == "group") { 125 | sparky.messageSend({ 126 | roomId: message.roomId, 127 | markdown: "**Note: this is a 'Group' room, I will wake up only when mentionned, ex: @" + bot.interpreter.nickName + " " + bot.interpreter.prefix + "help**" 128 | }) 129 | .then(function (message) { 130 | showHelp(message.roomId); 131 | }); 132 | } 133 | else { 134 | showHelp(message.roomId); 135 | } 136 | }); 137 | } 138 | }); 139 | -------------------------------------------------------------------------------- /examples/room-stats.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016 Cisco Systems 3 | // Licensed under the MIT License 4 | // 5 | 6 | /* 7 | * a Webex Teams bot that computes stats for a space 8 | * 9 | * note : this example requires you set up an ACCESS_TOKEN env variable for a human account (NOT a bot account), 10 | * as this code reads past, and all messages in the space 11 | * 12 | */ 13 | 14 | const debug = require("debug")("samples"); 15 | const fine = require("debug")("samples:fine"); 16 | 17 | // Starts your Bot with default configuration. The Webex Teams API access token is read from the ACCESS_TOKEN env variable 18 | const WebexChatBot = require("node-sparkbot"); 19 | const bot = new WebexChatBot(); 20 | 21 | // Changes command prefix to # : 22 | // because this bot uses a 'HUMAN' account, it is necessary to have him invoked only if the prefix is used 23 | bot.interpreter.prefix = "#"; 24 | 25 | const SparkClient = require("node-sparky"); 26 | const sparky = new SparkClient({ token: process.env.ACCESS_TOKEN }); 27 | 28 | 29 | bot.onCommand("about", function (command) { 30 | sparky.messageSend({ 31 | roomId: command.message.roomId, 32 | markdown: "```\n{\n 'author':'Stève Sfartz ',\n 'code':'https://github.com/CiscoDevNet/node-sparkbot-samples/blob/master/examples/room-stats.js',\n 'description':'computes the top contributors for a space',\n 'healthcheck':'GET https://sparkbot-room-stats.herokuapp.com',\n 'webhook':'POST https://sparkbot-room-stats.herokuapp.com'\n}\n```" 33 | }); 34 | }); 35 | 36 | 37 | bot.onCommand("fallback", function (command) { 38 | // so happy to join 39 | sparky.messageSend({ 40 | roomId: command.message.roomId, 41 | text: "sorry, I did not understand" 42 | }) 43 | .then(function (message) { 44 | // show how to use 45 | showHelp(command.message.roomId); 46 | }); 47 | }); 48 | bot.onCommand("help", function (command) { 49 | showHelp(command.message.roomId); 50 | }); 51 | function showHelp(roomId) { 52 | sparky.messageSend({ 53 | roomId: roomId, 54 | markdown: "I am all about Stats for your spaces\n- " 55 | + "\\" + bot.interpreter.prefix + "about\n- " 56 | + "\\" + bot.interpreter.prefix + "help\n- " 57 | + "\\" + bot.interpreter.prefix + "stats [nb_messages] : computes stats from past messages, defaults to 100" 58 | }); 59 | } 60 | 61 | 62 | bot.onCommand("stats", function (command) { 63 | 64 | // Max number of fetched messages, default is 100 65 | let max = command.args[0]; 66 | if (!max) { 67 | max = 100; 68 | } 69 | 70 | // As computing stats takes time, let's acknowledge we received the order 71 | sparky.messageSend({ 72 | roomId: command.message.roomId, 73 | markdown: "_heard you ! now computing stats from past " + max + " messages..._" 74 | }); 75 | 76 | // Build a map of participations by participant email 77 | let participants = {}; 78 | let totalMessages = 0; // used to get %ages of participation 79 | sparky.messagesGet({roomId: command.message.roomId}, max) 80 | .then(function (messages) { 81 | // Process messages 82 | messages.forEach(function (message) { 83 | totalMessages++; 84 | 85 | // [WORKAROUND] Remove incoming integrations as they are not supported in mentions 86 | if (!isIncomingIntegration(message)) { 87 | var current = participants[message.personEmail]; 88 | if (!current) { 89 | participants[message.personEmail] = 1; 90 | } 91 | else { 92 | participants[message.personEmail] = current + 1; 93 | } 94 | } 95 | }); 96 | 97 | // Sort participants by participation DESC 98 | let top = Object.keys(participants) //Create a list from the keys of your map. 99 | .sort( //Sort it ... 100 | function (a, b) { // using a custom sort function that... 101 | // compares (the keys) by their respective values. 102 | return participants[b] - participants[a]; // DESC order 103 | }); 104 | 105 | // Display top 10 participants 106 | let length = top.length; 107 | let limit = Math.min(length, 10); 108 | switch (limit) { 109 | case 0: 110 | sparky.messageSend({ 111 | roomId: command.message.roomId, 112 | text: "did not find any participant! is the space active?" 113 | }); 114 | break; 115 | case 1: 116 | sparky.messageSend({ 117 | roomId: command.message.roomId, 118 | markdown: "**kudos to <@personEmail:" + top[0] + ">" + ", the only active participant in here!**" 119 | }); 120 | break; 121 | default: 122 | var stats = "**kudos to the top participants**"; 123 | for (var i = 0; i < limit; i++) { 124 | var email = top[i]; 125 | var number = participants[email]; 126 | var pourcentage = Math.round(number * 100 / totalMessages); 127 | 128 | // Display only relevant contributors 129 | if (pourcentage >= 2) { 130 | stats += "\n\n" + (i + 1) + ". <@personEmail:" + email + ">, " + pourcentage + "% (" + number + ")"; 131 | } 132 | } 133 | sparky.messageSend({ 134 | roomId: command.message.roomId, 135 | markdown: stats 136 | }); 137 | break; 138 | } 139 | }); 140 | 141 | }); 142 | 143 | 144 | bot.onEvent("memberships", "created", function (trigger) { 145 | let newMembership = trigger.data; // see specs here: https://developer.webex.com/endpoint-memberships-get.html 146 | if (newMembership.personId == bot.interpreter.person.id) { 147 | debug("bot's just added to room: " + trigger.data.roomId); 148 | 149 | // so happy to join 150 | sparky.messageSend({ 151 | roomId: trigger.data.roomId, 152 | text: "Hi, I am so happy to join !" 153 | }) 154 | .then(function (message) { 155 | showHelp(trigger.data.roomId); 156 | }); 157 | } 158 | }); 159 | 160 | 161 | // Filter for incoming integration as these are automatically created by Spark back-end by creating a fake account 162 | // This fake account has an email built from the owner email and suffixed with a number 163 | // email: -@ 164 | function isIncomingIntegration(message) { 165 | let matched = message.personEmail.match(/-\d+@/); 166 | if (!matched) { 167 | return false; 168 | } 169 | 170 | fine("identified as integration: " + message.personEmail); 171 | return true; 172 | } 173 | 174 | 175 | --------------------------------------------------------------------------------