Skip to content

Commit

Permalink
Adding snippets needing for new docs.
Browse files Browse the repository at this point in the history
  • Loading branch information
Stevenic committed Mar 1, 2017
1 parent 1003f26 commit a7e4677
Show file tree
Hide file tree
Showing 16 changed files with 269 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Node/snippets/basics-askingQuestions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Create your bot with a waterfall to ask user their name
var bot = new builder.UniversalBot(connector, [
function (session) {
builder.Prompts.text(session, "Hello... What's your name?");
},
function (session, results) {
var name = results.response;
session.send("Hi %s!", name);
}
]);
17 changes: 17 additions & 0 deletions Node/snippets/basics-chatConnectorSetup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
var restify = require('restify');
var builder = require('botbuilder');

// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});

// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});

// Listen for messages from users
server.post('/api/messages', connector.listen());
6 changes: 6 additions & 0 deletions Node/snippets/basics-endingConversations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Create bot and default message handler
var bot = new builder.UniversalBot(connector, function (session) {
session.send("Hi... We sell shirts. Say 'show shirts' to see our products.");
}).endConversationAction('goodbyeAction', "Ok... See you next time.", {
matches: /^goodbye/i
});
10 changes: 10 additions & 0 deletions Node/snippets/basics-greetingUsers-contactRelationUpdate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Listen for 'contactRelationUpdate' event to detect user adding bot to contacts.
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.", name || 'there');
bot.send(reply);
}
});
29 changes: 29 additions & 0 deletions Node/snippets/basics-greetingUsers-conversationUpdate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Listen for 'conversationUpdate' event to detect members joining conversation.
bot.on('conversationUpdate', function (message) {
if (message.membersAdded) {
message.membersAdded.forEach(function (identity) {
if (identity.id == message.address.bot.id) {
// Bot is joining conversation
// - For WebChat channel you'll get this on page load.
var reply = new builder.Message()
.address(message.address)
.text("Welcome to my page");
bot.send(reply);
} else {
// User is joining conversation
// - For WebChat channel this will be sent when user sends first message.
// - When a user joins a conversation the address.user field is often for
// essentially a system account so to ensure we're targeting the right
// user we can tweek the address object to reference the joining user.
// - If we wanted to send a private message to teh joining user we could
// delete the address.conversation field from the cloned address.
var address = Object.create(message.address);
address.user = identity;
var reply = new builder.Message()
.address(address)
.text("Hello %s", identity.name);
bot.send(reply);
}
});
}
});
16 changes: 16 additions & 0 deletions Node/snippets/basics-greetingUsers-firstRun.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Add first run dialog
bot.dialog('firstRun', function (session) {
// Set firstRun flag to avoid being re-started every message.
session.userData.firstRun = true;
session.send("Hello...").endDialog();
}).triggerAction({
onFindAction: function (context, callback) {
// Only trigger if we've never seen user before
if (!context.userData.firstRun) {
// Return a score of 1.1 to ensure the first run dialog wins
callback(null, 1.1);
} else {
callback(null, 0.0);
}
}
});
19 changes: 19 additions & 0 deletions Node/snippets/basics-handleCommands.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Create your bot with a function to receive messages from the user
var bot = new builder.UniversalBot(connector, function (session) {
var msg = session.message;
if (/^help/i.test(msg.text || '')) {
// Send user help message
session.send("I'll repeat back anything you say or send.");
} else if (msg.attachments && msg.attachments.length > 0) {
// Echo back attachment
session.send({
text: "You sent:",
attachments: [
msg.attachments[0]
]
});
} else {
// Echo back uesrs text
session.send("You said: %s", session.message.text);
}
});
21 changes: 21 additions & 0 deletions Node/snippets/basics-handleCommandsUsingDialogs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Create your bot with a function to receive messages from the user
var bot = new builder.UniversalBot(connector, function (session) {
var msg = session.message;
if (msg.attachments && msg.attachments.length > 0) {
// Echo back attachment
session.send({
text: "You sent:",
attachments: [
msg.attachments[0]
]
});
} else {
// Echo back uesrs text
session.send("You said: %s", session.message.text);
}
});

// Add help dialog
bot.dialog('help', function (session) {
session.send("I'll repeat back anything you say or send.").endDialog();
}).triggerAction({ matches: /^help/i });
21 changes: 21 additions & 0 deletions Node/snippets/basics-rememberingAnswers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Create your bot with a waterfall to ask user their name and then remember answer.
var bot = new builder.UniversalBot(connector, [
function (session, args, next) {
if (!session.userData.name) {
// Ask user for their name
builder.Prompts.text(session, "Hello... What's your name?");
} else {
// Skip to next step
next();
}
},
function (session, results) {
// Update name if answered
if (results.response) {
session.userData.name = results.response;
}

// Great user
session.send("Hi %s!", session.userData.name);
}
]);
10 changes: 10 additions & 0 deletions Node/snippets/basics-sendCards-confirmPrompts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Add dialog to handle 'Buy' button click
bot.dialog('buyButtonClick', [
// ... waterfall steps ...
]).triggerAction({
matches: /(buy|add)\s.*shirt/i,
confirmPrompt: "This will cancel adding the current item. Are you sure?"
}).cancelAction('cancelBuy', "Ok... Item canceled", {
matches: /^cancel/i,
confirmPrompt: "are you sure?"
});
44 changes: 44 additions & 0 deletions Node/snippets/basics-sendCards-handleButton.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Add dialog to handle 'Buy' button click
bot.dialog('buyButtonClick', [
function (session, args, next) {
// Get color and optional size from users utterance
var utterance = args.intent.matched[0];
var color = /(white|gray)/i.exec(utterance);
var size = /\b(Extra Large|Large|Medium|Small)\b/i.exec(utterance);
if (color) {
// Initialize cart item
var item = session.dialogData.item = {
product: "classic " + color[0].toLowerCase() + " t-shirt",
size: size ? size[0].toLowerCase() : null,
price: 25.0,
qty: 1
};
if (!item.size) {
// Prompt for size
builder.Prompts.choice(session, "What size would you like?", "Small|Medium|Large|Extra Large");
} else {
//Skip to next waterfall step
next();
}
} else {
// Invalid product
session.send("I'm sorry... That product wasn't found.").endDialog();
}
},
function (session, results) {
// Save size if prompted
var item = session.dialogData.item;
if (results.response) {
item.size = results.response.entity.toLowerCase();
}

// Add to cart
if (!session.userData.cart) {
session.userData.cart = [];
}
session.userData.cart.push(item);

// Send confirmation to users
session.send("A '%(size)s %(product)s' has been added to your cart.", item).endDialog();
}
]).triggerAction({ matches: /(buy|add)\s.*shirt/i });
5 changes: 5 additions & 0 deletions Node/snippets/basics-sendCards-handleCancel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Add dialog to handle 'Buy' button click
bot.dialog('buyButtonClick', [
// ... waterfall steps ...
]).triggerAction({ matches: /(buy|add)\s.*shirt/i })
.cancelAction('cancelBuy', "Ok... Item canceled", { matches: /^cancel/i });
29 changes: 29 additions & 0 deletions Node/snippets/basics-sendCards.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Create bot and default message handler
var bot = new builder.UniversalBot(connector, function (session) {
session.send("Hi... We sell shirts. Say 'show shirts' to see our products.");
});

// Add dialog to return list of shirts available
bot.dialog('showShirts', function (session) {
var msg = new builder.Message(session);
msg.attachmentLayout(builder.AttachmentLayout.carousel)
msg.attachments([
new builder.HeroCard(session)
.title("Classic White T-Shirt")
.subtitle("100% Soft and Luxurious Cotton")
.text("Price is $25 and carried in sizes (S, M, L, and XL)")
.images([builder.CardImage.create(session, 'http://petersapparel.parseapp.com/img/whiteshirt.png')])
.buttons([
builder.CardAction.imBack(session, "buy classic white t-shirt", "Buy")
]),
new builder.HeroCard(session)
.title("Classic Gray T-Shirt")
.subtitle("100% Soft and Luxurious Cotton")
.text("Price is $25 and carried in sizes (S, M, L, and XL)")
.images([builder.CardImage.create(session, 'http://petersapparel.parseapp.com/img/grayshirt.png')])
.buttons([
builder.CardAction.imBack(session, "buy classic gray t-shirt", "Buy")
])
]);
session.send(msg).endDialog();
}).triggerAction({ matches: /^(show|list)/i });
4 changes: 4 additions & 0 deletions Node/snippets/basics-sendReceive.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Create your bot with a function to receive messages from the user
var bot = new builder.UniversalBot(connector, function (session) {
session.send("You said: %s", session.message.text);
});
21 changes: 21 additions & 0 deletions Node/snippets/basics-sendReceiveAttachments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Create your bot with a function to receive messages from the user
var bot = new builder.UniversalBot(connector, function (session) {
var msg = session.message;
if (msg.attachments && msg.attachments.length > 0) {
// Echo back attachment
var attachment = msg.attachments[0];
session.send({
text: "You sent:",
attachments: [
{
contentType: attachment.contentType,
contentUrl: attachment.contentUrl,
name: attachment.name
}
]
});
} else {
// Echo back users text
session.send("You said: %s", session.message.text);
}
});
7 changes: 7 additions & 0 deletions Node/snippets/basics-sendTyping.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Create bot and default message handler
var bot = new builder.UniversalBot(connector, function (session) {
session.sendTyping();
setTimeout(function () {
session.send("Hello there...");
}, 3000);
});

0 comments on commit a7e4677

Please sign in to comment.