Salesforce Skype Bot
Introduction
In this blog, I am going to explain the step by step how to set up a skype bot with salesforce by using node js,jsforce, and botbuilder.
Setup Node Js Project
1. Create an empty folder to start the node js project.
2. Create a new package.json file and paste the below code into the package.json file
{ "name": "bot", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node app.js" }, "author": "", "license": "ISC", "dependencies": { "botbuilder": "^3.1.1", "jsforce": "^1.8.0", "restify": "^4.1.1" } }
3. Run npm install from the command promote to load all the node modules from the package.json
4.Now create a new file and name it as app.js and paste this code into app.js file.
var restify = require('restify'); var builder = require('botbuilder'); var server = restify.createServer(); var jsforce = require('jsforce'); server.listen(process.env.port || process.env.PORT || 8080, function () { console.log('%s listening to %s', server.name, server.url); }); var connector = new builder.ChatConnector({ appId: "Microsoft App Id", appPassword: "App password" }); var conn = new jsforce.Connection({ loginUrl: 'https://login.salesforce.com' }); var username = 'salesforce user name'; var password = 'password and token'; conn.login(username, password, function (err, userInfo) { if (err) { return console.error(err); } }); console.log(conn); var bot = new builder.UniversalBot(connector); server.post('/api/messages', connector.listen()); bot.on('conversationUpdate', function (message) { // Check for group conversations if (message.address.conversation.isGroup) { // Send a hello message when bot is added if (message.membersAdded) { message.membersAdded.forEach(function (identity) { if (identity.id === message.address.bot.id) { var reply = new builder.Message() .address(message.address) .text("Hello everyone!"); bot.send(reply); } }); } // Send a goodbye message when bot is removed if (message.membersRemoved) { message.membersRemoved.forEach(function (identity) { if (identity.id === message.address.bot.id) { var reply = new builder.Message() .address(message.address) .text("Goodbye"); bot.send(reply); } }); } } }); bot.on('contactRelationUpdate', function (message) { if (message.action === 'add') { var name = message.user ? message.user.name : null; var reply = new builder.Message() .address(message.address) .text("Hello %s... Thanks for adding me. Say 'hello' to see some great demos.", name || 'there'); bot.send(reply); } else { // delete their data } }); bot.on('deleteUserData', function (message) { // User asked to delete their data }); bot.use(builder.Middleware.dialogVersion({ version: 1.0, resetCommand: /^reset/i })); bot.endConversationAction('goodbye', 'Goodbye :)', { matches: /^goodbye/i }); bot.beginDialogAction('help', '/help', { matches: /^help/i }); bot.dialog('/', [ function (session) { // Send a greeting and show help. var card = new builder.HeroCard(session) .title("Salesforce Skype Bot") .images([ builder.CardImage.create(session, "https://c1.sfdcstatic.com/content/dam/web/en_us/www/images/home/sfdc-jetpack-card.jpg") ]); var msg = new builder.Message(session).attachments([card]); session.send(msg); session.beginDialog('/menu'); }, function (session, results) { // Display menu session.beginDialog('/menu'); }, function (session, results) { // Always say goodbye session.send("Ok... See you later!"); } ]); bot.dialog('/menu', [ function (session) { builder.Prompts.choice(session, "What would you like to do?", "posttochat|CreateOrder|ContactDetails|(quit)"); }, function (session, results) { if (results.response && results.response.entity != '(quit)') { // Launch demo dialog session.beginDialog('/' + results.response.entity); } else { // Exit the menu session.endDialog(); } }, function (session, results) { // The menu runs a loop until the user chooses to (quit). session.replaceDialog('/menu'); } ]).reloadAction('reloadMenu', null, { matches: /^menu|show menu/i }); bot.dialog('/posttochat', [ function (session) { builder.Prompts.text(session, "Please say the message to post to chatter?"); }, function (session, results) { // session.userData.name = results.response; //builder.Prompts.number(session, "Hi " + results.response + ", How many years have you been coding?"); conn.chatter.resource('/feed-elements').create({ body: { messageSegments: [{ type: 'Text', text: results.response }] }, feedElementType: 'FeedItem', subjectId: 'me' }, function (err, result1) { if (err) { return console.error(err); } console.log("Id: " + result1.id); console.log("URL: " + result1.url); console.log("Body: " + result1.body.messageSegments[0].text); console.log("Comments URL: " + result1.capabilities.comments.page.currentPageUrl); session.send("Message is posted Succefully: Record is for your reference " + result1.id); }); }, function (session, results) { // The menu runs a loop until the user chooses to (quit). session.replaceDialog('/menu'); } ]); bot.dialog('/CreateOrder', [ function (session) { builder.Prompts.text(session, "What is the name of the order"); }, function (session, results) { conn.sobject("Order").create({ Name: results.Name, EffectiveDate: '2018-02-01', Status: 'Draft', Contract: '8006A0000000N5M', Account: '0016A000004BtSv' }, function (err, ret) { if (err || !ret.success) { return console.error(err, ret); } session.send("Order is created with record is " + ret.id); }); }, function (session, results) { // The menu runs a loop until the user chooses to (quit). session.replaceDialog('/menu'); } ]); bot.dialog('/ContactDetails', [ function (session, results) { session.send("No Logic is implemented here Simply"); session.replaceDialog('/menu'); } ]);
5.Change appId & appPassword with your own appId and appPassword for chatbot and Salesforce username and password to get data from the salesforce.To get App Id and password follow below steps.
6.First login into your Microsoft account.
7.Goto this link: Click Here and complete sign in process
8.Click on Register a bot and create a new bot.
9.Click create button to register your bot Register an existing bot built using Bot Builder SDK

10.Now fill in your required details, select your bot image as shown below
11.Click on Create Microsoft App ID and password and then click on generate app Password to continue
12.Now You got your App ID and Password and update them in code.
13.Now you need to add https messaging endpoint to listen for requests.
14.You can create one for free that will run locally on your system using the tool called ngrok and Download ngrok from here Click Here .You will get a zip file, Extract that zip file into any folder and then open the file named ngrok.exe
15.Type and enter : ngrok http 8080
16.Now copy the https address from the command line of ngrok. Make sure you don’t close the ngrok after creating address cause then the endpoint address will not listen to any request.
17.Now paste this address into endpoint field and add “api/messages” in the end as shown below on Bot Registration configuration sections.
18.Click on the register and save the bot.
19.Now go back to command prompt and type ‘ node app.js ‘ to start your node js application.
20.After the application starts you can test from the test section on the application.
Then type /help to start the bot conversion as shown below.
As shown in the above image you can post to chatter from the skype chatbot. once you test your application you can push the skype and use it.
Understand the Code
You can register the bot chat connect from the below code and it is going to Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({ appId: "7fd91532-0cb1-49e6-8100-883682ece5da", appPassword: "twrITAZ192>_aarsGUG69;&" });
And most important think how we are going to establish the conversation as the communication between a bot and a user through one or more dialogs. A dialog, at its most basic level, is a reusable module that performs an operation or collects information from a user. the below code shows how to start the dialog
bot.dialog('/', [ function (session) { // Send a greeting and show help. var card = new builder.HeroCard(session) .title("Salesforce Skype Bot") .images([ builder.CardImage.create(session, "https://c1.sfdcstatic.com/content/dam/web/en_us/www/images/home/sfdc-jetpack-card.jpg") ]); var msg = new builder.Message(session).attachments([card]); session.send(msg); session.beginDialog('/menu'); }, function (session, results) { // Display menu session.beginDialog('/menu'); }, function (session, results) { // Always say goodbye session.send("Ok... See you later!"); } ]);
You can refer more details on dialogs below links
https://docs.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-quickstart
https://docs.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-dialog-overview