A Step By Step Guide To Develop A Conversational Facebook ChatBot Using Microsoft Bot Framework
The year 2016 made ‘BOTS’ the zeitgeist of this era. As the annual dev. conferences of Silicon Valley bigwigs rolled out, the ‘Bots’ became the ‘talk of the town’ in the tech arena. This gave birth to a notion ‘Are we at the brink of next paradigm shift’?
Let me ask you one question, what is the activity or rather habit that keeps us hooked up to our cell phones most of the time.
It’s messaging or the conversations we perform daily with our friends and family. As a matter of fact, the industry has already started to make a leap for this low-hanging fruit through “BOTS”.
BOTS are the conversational agents that live inside our messaging platforms. For example, Facebook messenger and slack. Experts have already termed this as an era of ‘conversational apps’.
This blog post simply explores How to set up Bot with MS Framework.
Bots have mushroomed and they are everywhere. The new avatar ‘bots’ with ‘intelligent context’ have made them the ‘best bet’ to succeed apps & websites. Consequently, Microsoft rolled out its own framework ‘Microsoft Bot Framework’ to induce a good push to DEV. Community for building conversational bots. FB announced ‘Bots in Facebook messenger’.
For a better understanding on the potential of bots, you can read our insight on How Chatbots Are Disrupting Customer Experience Across Industries.
The end-users are spending more and more time inside messaging apps and even surpassed social media user-base this year. It will be appropriate to say that we need to go where the people are and showcase our work. But the interface is simply a conversation UI which means ‘presenting the awesome work to the user as a bot’. This is where Microsoft Bot Framework jumps into play!
1.Gather An Understanding On The Microsoft Bot Framework
If we take a look at the messaging platforms, fb messenger, slack, skype etc. They all allow us to perform one simple thing, ‘converse through messaging’. To support bot into their platforms, they all expose their own APIs. Microsoft Bot Framework gives us abstractions to build bots against a single API and take care of its integration with various services. This gives developers a free hand to work more closely over the bot experience rather than channel integration details.
We can say this is the edge provided to developers in Microsoft Bot Framework.
Bot Framework Overview
Check out the image below. It scintillatingly illustrates the components involved in the Microsoft Bot Framework.
- Bot’s API endpoint (Built though BotBuilder SDK)
- Bot Connector – serves as the genesis of Microsoft Bots. It provides services such as registration, tracking and routing of messages to various message channels.
- Bot message channels – The various channels that support bots in their platform.
Understand Bot Connector Service
Like I said above, Bot Connector service serves as the genesis of the Bot Framework. One of the key highlight is the abstraction provided to developers for seamless integration of their bot with various messaging channels.
About BotBuilder SDK
The BotBuilder SDK is an open source SDk hosted on GitHub. It provides various features like building conversation Dialog, Activities, composing the dialogs and yes LUIS.ai support for natural language processing. It is basically in two forms: BotBuilder SDK in C# and NodeJS.
2. Identify The Pre-Requisites
- Install Visual Studio 2015.
- Install a NuGet package ‘Microsoft.Bot.Builder’.
- Microsoft account (can be Hotmail, Live, Outlook) to log into ‘BotFramework Developer Portal’ to register you Bot.
- Account on Facebook (as our bot will live inside Facebook messenger).
- An accessible REST endpoint on Azure OR AWS with HTTPS exposing a callback.
Get started in Visual Studio
- In Visual Studio 2015, download & install the bot application template. You can download it from: http://aka.ms/bf-bc-vstemplate
- Save the .zip file into your VisualStudio 2015 templates gallery which is in “%USERPROFILE%\Documents\Visual Studio 2015\Templates\ProjectTemplates\Visual C#\”
- Create a new project using the new Bot Application template.
Code aka ‘building blocks’ of your Bot
- When you load your project, you will see a POST method. This is the endpoint that is exposed to the BotConnector.
- It receives all the messages sent by the user.The flow is:
- FacebookPage àWebhook àBotConnector àAPI Endpoint àProcess the message à Reply back
‘Activities’ (Send a simple message)
- Bot Framework models the conversation between the end-user and the bot in terms of ‘Activity’. That is any type of message sent by the user is encapsulated in ‘Activity’ and received by the bot.
- Below is the example of a simple Echo Bot which sends back the count of characters in the message sent by the user.
- The ‘emulator’ shot below depicts the message ‘JSON’ sent/received.
- Microsoft BotFramework involves multiple ActivityTypes in if. The below screenshot displays the multiple types available to capture the activity on the end-user’s side and trigger the appropriate logic.
Send ‘Rich/Structured’ content
- Conversation being the crux element in a Bot. Therefore, the messaging channels allow the ability to add/show rich content objects.
‘State maintain’ of a conversation
- Many times you will have this requirement arise that you need to main as to what was the last thing user asked or in my case I used it for maintaining whether the user is a ‘first-time user’ or a regular one.
- Bot Framework provides us with BotState service. It allows us to save multiple data-basgs upto a memory of 32k. By default, the storage is in BotConnector service at Microsoft’s end but we can plug our own IBotStorage for our data-bags.
‘Securing’ the bot conversation
We developers should ensure that our bot’s endpoint can only be called by the Bot Connector.
So to accomplish this, we need to:
- Configure the endpoint to use only HTTPs.
- Use the bot framework’s authentication: MicrosoftAppId & MicrosoftAppPassword.
- To make it easy, Bot Framework provides an attribute [BotAuthentication] which does this for your method or controller.
3.Unit-Test The Bot
‘Emulator’ to the rescue
Well now we ordinary developers do extraordinary work and put a dent in the universe. However, universe has something else for in store for us. Therefore, guys we need to test out built bot. So use ‘Bot Framework emulator’ to test your conversation. It provides you a channel emulator that lets you simulate your conversation.
- To install Bot Framework emulator, click here: https://aka.ms/bf-bc-emulator.
- Build your application and deploy. The web browser will open and show the application Default.htm file (part of the Bot Application project).
- Some configuration you need to set for running emulator:
- The URL for your bot set the localhost:<port> pulled from the last step.
- Empty out the MicrosoftAppId field.
- Empty out the MicrosoftAppPassword field.
- Now that everything is setup, you may interact with your service. The bottom of the Bot Emulator has a textbox to enter a message.
4. Publish Your Bot To Azure
- In this blog post, we use Microsoft Azure to host the Bot Application. Although please note that there is no constraint as to where you host your bot but it should have a valid HTTPs certificate.
- Make changes whatever you like to your code and then right-click your project and click ‘Publish’.
- The ‘Publish to Azure’ wizard shall start. Select ‘Microsoft Azure App Service’ as your project type.
- Create ‘App Service’ now. Click on ‘New’ in the right side. It will take you to next screen. Also if you have any existing resource in Azure, you may select that as well.
- Select the type of App as ‘Web App’ instead of API App which is default type.
- Hit ‘Publish’ button to publish your app to azure.
- Check out the ‘Azure App Service Activity’ for successful publish.
5. Register Your Bot With Microsoft Bot Framework
Registering your bot tells the bot connector how to call your bot’s web service. Also note that for the conversation to happen, we need a MicrosoftAppId & MicrosoftAppPassword. They are used to authenticate the conversation. It also allows the developer to configure their bot with various channels.
- Go to Microsoft Bot Framework portal at https://dev.botframework.com and sign in with your Microsoft account.
- Click ‘register a bot’ button and fill out the form.
- Use the endpoint generated from your Azure deployment and don’t forget to extend the url with “/API/messages”.
- You also need to prefix the url with HTTPS instead of HTTP. Azure will automatically take care of providing HTTPS support on your bot.
- Save your changes in the form by hitting ‘Register’ at the bottom of the form.
- Once your registration is completed, Microsoft Bot framework shall take you through generating MicrosoftAppId & MicrosoftAppPassword.
- When you generate MicrosoftAppPassword, make sure you record it. It is shown to the creator only once. You won’ be able to see it again.
- After key generation, we need to update web.config file. Change the highlighted keys below in web.config.
- Republish to azure.
- Test connection to bot. To verify that your bot is successfully authenticated to talk to BotConnector, click ‘Test connection to your bot’.
6. Setup Bot in Facebook Messenger
Microsoft Bot Framework lists down the steps and enables us to configure our bot with Facebook much faster.
Create a new ‘Facebook Page’
Each and every Facebook messenger bot has an associated page. It serves as a doorway to our bot. For end-users it may be like just messaging to a page. Only this time they will be getting automated responses.
You can use an existing page or create a new one.
Create a Facebook App and copy the AppID & AppSecret. Save it for later use
Now as we need to setup a bot. Therefore we shall add & enable ‘Messenger’ for our app. Click on ‘+Add Product’ and the list that appears click on ‘Messenger’.
Generate ‘Page Access Token’ for usage
Introduct a web-hook in your bot
Enter your credentials generated
After successful submission, the bot shall appear in the configured channels list:
Important Notes for Developers
- Your Facebook bot is available directly to the public. It needs to go through a FB bot app review approval process. Once approved, you can set your bot to be available to public. In development mode, it shall only be available to the FB app creator. FB provisions adding ‘testers’, ‘developers’ who may want to interact with the bot.
- In publish through Visual Studio, if the option ‘Azure App Service’ does not appear, that means you need to install ‘Azure SDK’ in Visual Studio.
- Microsoft Bots can be hosted anywhere provided you have a valid HTTPs certificate. You may refer this link for valid vendor participants with Microsoft: http://social.technet.microsoft.com/wiki/contents/articles/31634.microsoft-trusted-root-certificate-program-participants-v-2016-april.aspx
- Make sure in the App-Approval process you submit test-user credentials for sure. Otherwise, your app may not get approved through FB.
- Personalize your bot: You can set facebook greeting screen, greeting text and persistent menu for better user experience. Follow the source links below for the code.
- Setup a Facebook bot greeting screen: https://developers.facebook.com/docs/messenger-platform/thread-settings/get-started-button
- Setup a Facebook bot greeting text https://developers.facebook.com/docs/messenger-platform/thread-settings/greeting-text
- Setup a Facebook bot persistent menu https://developers.facebook.com/docs/messenger-platform/thread-settings/persistent-menu
You can successfully create and deploy your very own Facebook Messenger Bot using Microsoft Bot Framework. While using this framework for building a Facebook bot, you will be able to clearly visualize the advantages this Framework provides in accelerating the setup and message delivery to the channels. You will be excited that as per Microsoft’s figures there are already 45,000 developers working with bots and 11,000 bots already on Facebook messenger. So, are you up for the challenge?