Chapter 2. Chatbot integration with different platforms

Most messaging applications provide extensive tools to measure connected devices, including bots. These platforms are flexible and broad, and they make tracking new devices and new technologies simple.

How are these programs integrated into messaging apps? Do all messaging platforms support bots? Is it necessary to code? Can anyone create chatbots?

This chapter describes the process of how to integrate your bot with the top three messaging applications.

Chatbot Frameworks

Big companies and startups interested in chatbots are making it easier for users from different disciplines to build their own bots whether they are familiar with developing aspects or not. The superpowers of the Internet, like Microsoft and Facebook, released complete frameworks for building massive bots, and many startups joined the race with assistants. This section examines some of these frameworks and their offerings.

Facebook Messenger Platform

Facebook launched the Messenger Platform at the F8 conference on April 2016. The platform offers to its users the ability to have conversations with people on Messenger. It integrates tools destined to build and promote chatbots so developers can create a user experience for their unique audience.

Using plugins, codes, and links, you can discover the chatbot and start conversations. Using Customer Matching, the bot can reach people on Messenger if the developer has their phone number and they have agreed to be contacted by the bot. Powerful discovery tools such as plugins for websites, usernames, Messenger Codes, and a prominent search surface in Messenger are accessible too.

User experience is the core of everything in Messenger Platform. As much as businesses start to interact with people, these businesses can’t be served without putting people in control. A new update of the platform gives developers the ability to create a welcome screen and to set context as well as different controls for their threads. Messenger requires developers to submit their bots for review on behalf of publishing the bot.

The platform is responsive and the submissions aim to ensure the best experiences for everyone on Messenger.

Main Capabilities in Messenger Platform Bots:

  1. Send/Receive API : Like any other platform, Messenger has The Messenger Send/Receive API enabling a Facebook application to interact as a chatbot. Other than supporting the sending and receiving of text messages, the API also includes images and interactive rich bubbles containing multiple calls-to-action.
  2. Generic Message Templates: People like to see beautiful images, scanned text and tap buttons, rather than learn a completely new programming language to interact with a bot. That’s why Messenger Platform provides structured messages with calls-to-action, horizontal scroll, URLs, and postbacks.
  3. Welcome Screen: Before entering the conversation for the first time, the welcome screen helps you to discover the bot, and it might lead to a greeting or call-to-action to “Get Started.”

A demo is presented in the next section to help you build and connect your bot to Facebook Messenger Platform.

Microsoft Bot Framework

Earlier in 2016, Microsoft launched Microsoft Bot Framework and its initial iteration of the Bot Connector API, with Bot Builder and Bot Connector SDK. Since construction, Microsoft has actively worked in improving the REST and SDK API to be ready for the future, including better support for attachments as well as improved performance.

It is a complete offer to create and deploy high quality bots. Bots developers all face the same problems: bots require basic I/O. They must have linguistic and dialogue skills, they must be performing, reactive and evolving, and they must connect to users.

The Microsoft Bot framework offers many capabilities. The Bot Framework provides everything needed to build, connect, manage and publish smart bots that naturally interact whenever the user speaks - from text/SMS to Skype, Slack, Facebook Messenger, Kik, Office 365 Mail and other popular services. There is even a PaaS option on Azure, which is an intelligent, serverless bot service that scales on demand.

In short, chatbots can offer a user experience much more fluid and satisfying than applications, transforming the messaging into multi-service platforms. And do chatbots really jeopardize mobile applications? Time will tell.

The Microsoft Bot Framework provides a .Net SDK and a Node.js SDK. They make building bots easier because of the features they afford such as built-in prompt and dialogs. The REST API is implemented for those using other programming languages. The Bot Builder SDK is an open source project on Github (BotBuilder). Adding intelligence to a bot on Microsoft is included via Language Understanding Intelligent Service (LUIS) for natural language processing, Cortana for voice understanding, and the Bing APIs for search.

After building the bot, it has to be registered, connected to channels and published. The framework provides a registration, which produces the bot’s app ID and password used for authentication. Some channels are preconfigured on the framework such as Skype and WeChat. As soon as a channel is configured, the bot can be shared with users. After publishing the bot, users can select it in the directory and add it to one or more of the configured channels they use.

Example

The following example is based on Bot Builder for Node.js, which is a powerful framework for constructing bots. It uses both guided interactions and more freeform ones where the possibilities are explicitly shown to the users. It models frameworks like Express & Restify.

  • Build a bot

Create a folder for your bot, cd into it, and run npm init.

mkdir myBot
cd myBot
npm init

A sequence of questions should be answered so the file package.json can be configured and written. Reasonable guesses about how thing should be set will be given. If there is already a package.json file in the present directory, it will read that first, and default to the options in there.

Using NPM (Node.js Package Manager), get the Bot Builder and Restify modules.

npm install --save botbuilder
npm install --save restify

Make a file named bot.js containing these few lines of code.

/*
*bot.js file
*"require" calls the specified module previously installed
*/

var restify = require('restify');
var builder = require('botbuilder');

/*=========================================================
* Bot Setup
*=========================================================

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

/* Create chat bot
* MICROSOFT_APP_ID and MICROSOFT_APP_PASSWORD should be recovered at the
* registration
*/

var connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
    });

var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());

/*=========================================================
* Bots Dialogs
*=========================================================*/

bot.dialog('/', function (session) {
    session.send("Hello World");
     });

A bot application has just been created.

  • Test the bot (for Windows Only)

The easiest way to test a localhost bot is to use the Bot Framework Emulator.

After installing the emulator, the bot application should be run using the command:

node bot.js

The final thing to do is to start the emulator and send Hello to the bot.

Chatfuel: Build a Facebook bot without coding

Chatfuel is a full-featured platform for launching chatbots without coding.

Chatfuel was founded by Russian entrepreneurs Dmitrii Dumik and Artem Ptashnik last year. The company has 12 staff members across offices in Moscow and San Francisco, and it has earned the backing of Russian Internet Yandex — The Google Of Russia — that led its most recent funding round.

It provides typical interaction patterns and buttons/blocks for answering user questions or interactions. In fact, it is very intuitive, even if there is obviously a certain complexity.

The real added value of Chatfuel remains its integration of the AI. It is indeed possible to enter terms, and create automatic replies according to the terms created. Chatfuel is ideal to start setting up really interactive bots. Its bots serve up news, allow users to narrow down topics, and users can even ask questions about items or people in the news.

Chatfuel is powering a new kind of conversation. It enables owners to send news, collect feedback, receive and answer questions and share contents as GIFs and documents. Making chatbots is easy for Internet users because coding is not required. Although, the framework provides a reliable and free hosting for the chatbot code. Data streams are effortlessly plugged in because Chatfuel has hundreds of integrations like Instgram, Facebook, Twitter, Youtube and many more.

The most popular bots created with Chatfuel are Forbes, TechCrunch, The Verge, and National Geography. The company is currently focusing their efforts on Telegram, which is the only chat app to open its bots to everyone. Beyond investing in media, it has a self-service platform that anyone can use. Thus far, that has been used to make over 120,000 bots, which serve over five million users. Presently, there are more than 100k robots that were created on Chatfuel serving 5M+ users worldwide.

Motion AI

Motion AI is a platform based on a flowchart that allows you to build a chatbot without a line of code. The company, founded in Chicago, guides you through the different aspect of the bot’s flow, including deployment across almost all platforms (Facebook Messenger, Telegram, Slack, SMS, email, the Web, and more).

The Motion AI platform is designed around the modular creation of bots. Modules are packages that fold the required functionalities for building bot features. It is an appropriate way for beginners and experienced developers to gain time because it saves many steps. Some modules are predefined in the platform. For example, there are the “Yes/No” and “Multiple Choice” modules. They are used to build a customer service triage and serve the quick replies as well. There are modules that enable sending and receiving data from services.

Motion AI also handles the basic infrastructure for deploying bots, so you don’t have to sign up to Twilio to run a bot over SMS or SendGrid to run it over email. It also allows the importing of artificial intelligence or natural language processing services to the bot.

The idea of modules was inspired by David Nelson, due to the significant time a developer can spend reinventing the wheel each time they have to create a new bot with the same services.

Motion AI also handles analytics and reports on how the bot is being used after deployment. All messages sent to the bot from other users are stored and are visible on the platform.

Recently, Motion AI launched the new Node.js module. It allows interacting with an external database, connecting with a third party API, and more. Each Node.js function created through Motion AI is passed a payload object that contains metadata based on an end-user’s response to the bot. This data can be acted upon within the Node.js module to create a bot response to be returned at the end of the function.

Complex conversation flows can be structured through the use of Connections. Users can setup and define connections within each Module’s configuration screen.

Each bot response corresponds with a Module. To modify the modules, the user should click the “Configure” button on the desired Module. Collectively, a series of modules create and define the flow of conversation.

Different messaging platforms

“The chat apps will become the new browsers, the bots will be the new websites. This is the beginning of a new Internet”, Ted Livingston - Kik Founder.

From simple discussion spaces, messaging applications operate a mutation to become service platforms in their own right. Most of them are supporting conversational robots. These applications are a new way for brands to reach consumers.

Bots are lightweight. They do not have their own UIs. Instead, users interact with them via text or voice messaging with their preferred messaging app. Whether they are the result of artificial intelligence or human operators handling them, bots have the unprecedented skill to integrate into the core of messaging platforms and offer customized services.

Technological advancement increasingly helps in the simplicity of creating chatbots. Thanks to the recent application-programming interface, APIs, offered by instant messaging providers, brands now have the possibility to simply develop their bot by feeding them with typical questions and queries that a user can formulate. These queries are the bot’s skills and functionalities. In addition, for each query, the APIs set the corresponding action that the bot must execute. For example, they can search for a response to the question asked, or display a list of products.

One of the main problems with applications today is the famous “download and create your account” that annoys the user, discouraging her from trying a new product or service. “The majority of Americans do not download any apps per month.”

Bots offer a single interface for most tasks, which eliminates the problem of signing up. All service companies can simply create their own bot and users just have to start a conversation by expressing their request: no installation, and no registration!

Chatbots retain their simplicity of integration into chat platforms due to five main characteristics:

  • Single: Chatbots do not need interfaces. That means that the developers will have no problems with ergonomics and they will focus on their customers.

  • Fast: Counter to usual applications, chatbots do not require a downloading, so users do not waste time searching and installing an app.

  • Natural: Messages are delivered depending on the users’ actions.

  • Fluid: The conversation is similar to an accompanying experiment.

  • Universal: No matter the platform, the conversation resumes where it stopped.

The core of a chatbot generally contains four components:

  1. Server for communicating with various service integrations (APIs or data stores).
  2. Chat bot app itself, which is really another web app.
  3. Chat platform connectors, so that you can route messages from places like Messenger, Skype, Slack, Kik, WeChat, or Telegram.
  4. Optionally a NLP or CS service to process messages before replying back with a response.

In general, whenever someone interacts with your bot or sends you a message, the bot platform sends an update via your Webhook integration. The response generally contains information about the message and the user. The information is used to answer the user back. The message is passed to the bot engine via your webhooks. The Bot Engine processes the message received according to your bot’s skills and functionalities, builds an observed response, and sends it back to the platform respecting its API requirements. The platform will then deliver the response message to the final user.

We will concentrate on how to use the third component to connect our bot to the chat platform. In this chapter, four top messaging apps are presented.

Facebook Messenger

Facebook Messenger is the first instant messaging service in the world, and currently has more than one billion users. More than 60 billion messages are sent every day on Facebook and Whatsapp.

Facebook said that robots will improve quickly as developers create them. Today, more than 11,000 live in Messenger. They can answer with GIFs, audio, and video. These bots can now link Messenger profiles to customer accounts, such as a bank or an online merchant.

Facebook has announced new tools to developers allowing them to create bots for Facebook Messenger. These robots can add a new range of functions to the Facebook messaging app. For example, Facebook has envisaged a future where Messenger will be used to interact with business and vice versa. Let’s create a Node.js chatbot in Facebook.

Step 1: Create a webhook endpoint

  • Setup the server : The server used in this demo is Heroku. You can install the Heroku toolbelt from here Heroku Toolkit Page to launch, stop and monitor instances. Sign up for free at the Heroku Page if you do not have an account.

  • Install Node from the NodeJs Officiel website. It will be the server environment. Then open up Terminal or the Command Line Prompt.

  • Reinstall npm in order to have the most recent version:

sudo npm install npm -g
  • Create a new folder and then a Node.js Project. You can skip all of the configuration steps for the “package.json” by hitting Enter:
mkdir botProject
cd botProject
npm init
  • We will need external dependencies: Express is for the server, Request is for sending out messages, and body-parser is to process messages.
npm install express request body-parser –save
  • Create an index.js file in the folder. We will start by authenticating the bot.

Copy these lines to the file:

'use strict'

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.set('port', (process.env.PORT || 5000));

// Process application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));

// Process application/json
app.use(bodyParser.json());

// Index route
app.get('/', function (req, res) {
    res.send('Hello ! I’m a chatbot. Say something.')
});

// for Facebook verification
app.get('/webhook/', function (req, res) {
    if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
        res.send(req.query['hub.challenge'])
    }
    res.send('Error, wrong token')
});

// Spin up the server
app.listen(app.get('port'), function() {
    console.log('running on port', app.get('port'))
});

To make sure you are able to receive messages, you need to check the POST calls to the Webhooks. To receive messages, verify the messagingEvent.message field and use the receivedMessage functionality:

app.post('/webhook', function (req, res) {
  var data = req.body;

  // Make sure this is a page subscription
  if (data.object === 'page') {

    // Iterate over each entry - there may be multiple if batched
    data.entry.forEach(function(entry) {
      var pageID = entry.id;
      var timeOfEvent = entry.time;

      // Iterate over each messaging event
      entry.messaging.forEach(function(event) {
        if (event.message) {
          receivedMessage(event);
        } else {
          console.log("Webhook received unknown event: ", event);
        }
      });
    });

    // Everything went well.
    //
    // You must send back a 200, within 20 seconds, to let the platform know
    // you've successfully received the callback. Otherwise, the request
    // will time out and Fawebook Messenger Platform will keep trying to resend.
    res.sendStatus(200);
  }
});

function receivedMessage(event) {
  // echo the received message for now
  console.log("Message data: ", event.message);
}
  • Heroku needs to know which file should be run. Create a Prockfile and copy this in it:
web: node index.js
  • The bot is now able to be authenticated using the code above. You will have to push the application to a Heroku application. To do so, open GIT and commit the project files, then create a Heroku instance and push it all to it.
git init
git add .
git commit --message 'hello world'
heroku create
git push heroku master

Step 2: Setup the Facebook Page

The page is the identity of the bot through the page name and picture that other users will be interacting with. You can skip through most of the setup steps and save.

Step 3: Setup the Facebook application

Build your app on Facebook Developer’s Quickstart Page.

Choose the basic setup then “Page for Apps” as a category. Give your app a name, category, and a contact email.

Your App ID is given at the top right on the next page. Scroll down and click “Get Started” next to Messenger.

There are a few configurations that should be done to wire up the chatbot application to Heroku endpoint. In the Messenger settings, you need to use the page you created earlier to generate the Page Access Token.

DO NOT SHARE YOUR TOKEN.

Click on the Page Access Token to copy it. You will need to set it as an environment variable for the Heroku application. It will be used to authenticate requests whenever the bot tries to send a message or reply to someone.

On the command line, in the same folder where you cloned the application, run:

heroku config:add PAGE_ACCESS_TOKEN=$your_page_token_here

You can notice the webhook step under the Token Generation. To add a webhook to your page you will need the following:

• Callback URL - The Heroku (or other) URL that you setup earlier. • Verification Token - A secret value sent to the bot to verify the request is coming from Facebook.

The Verification Token should be added your Heroku environment using:

heroku config:add VERIFY_TOKEN=$your_verification_token_here

• Subscription Fields - This tells Facebook what messaging events you care about and you want it to notify your webhook about. Start with “messages.” Right after setting up the webhook, make sure you subscribe to the specific page you want to receive message notifications for.

This was a simple Node.js backend for a Facebook chatbot.

Slack

Slack was built to be easy and fun to use. It offers a comprehensive set of APIs that allows developers to extend its capabilities.

One of the most powerful features from Slack is the Slackbot, a friendly robot available in every Slack team to guide users to create their profiles and to explain to them how Slack works.

Slack provides APIs that help developers create their own bots and connect them to the messaging app.

We will build a second a custom bot using NodeJs that lives in Slack.

Slack Real Time messaging API is a websocket-based API that allows you to receive events in real time and send messages to channels, private groups and users. This API provides a NodeJs module “slackbot,” written by Mikhail Mokrushin that makes things a lot easier than using websockets directly. With this library, all you need to write is just some straightforward JavaScript code.

You need to configure the channel extensions and create a new bot. This way you will obtain the API token that is required to authenticate the bot.

Step 1: Create a new bot in a Slack Domain

In order to add a Bot in your Slack domain you need to visit the following URL https://yourdomain.slack.com/services/new/bot, where “yourdomain” must be substituted with the name of your organization. Choose a name for your bot. Then you will move to another screen where the API Token is given. Copy it and save it. (It should not be shared)

Step 2: Setup the project

In this step, we will use a well-known bot library called Botkit. Howdyai made it before Slack acquired the startup.

The library provides a solution of Slack RTM implementation and makes it easy for developers to design and run useful, creative bots that live inside Slack, Facebook Messenger, Twilio IP Messaging, and other messaging platforms.

It provides a semantic interface to sending and receiving messages so that developers can focus on creating novel applications and experiences instead of dealing with API endpoints.

Install Botkit directly from NPM or Github and build a new app from scratch. Via NPM:

npm install --save botkit

Via Git:

git clone [email protected]:howdyai/botkit.git

After cloning the Git repository, you have to install the node dependencies. Navigate to the root of your cloned repository and use npm to install all necessary dependencies.

npm install

After you have installed Botkit using one of these methods and you have registered your bot with a Slack, you need to run your bot. Run the example bot app, using the token you just copied:

Token=REPLACE_THIS_WITH_YOUR_TOKEN node slack_bot.js

The slack_bot.js file content is:

var Botkit = require('botkit');

var controller = Botkit.slackbot({
    debug: false
    //include "log: false" to disable logging
    //or a "logLevel" integer from 0 to 7 to adjust logging verbosity
    });

// connect the bot to a stream of messages
controller.spawn({
   token: <my_slack_bot_token>,
   }).startRTM();

// give the bot something to listen for.
controller.hears(['hello', 'hi'], ['direct_message', 'direct_mention', 'mention'], function(bot,message) {
    bot.reply(message,'Hello yourself.');
    });

This bot is waiting for the word “hello” to be said to it -- either as a direct mention ("@bot hello"), an indirect mention ("hello @bot"), or a direct message (a private message inside Slack between the user and the bot). The Botkit constructor (Botkit.slackbot) returns a controller object.

Event handlers attached to the controller object allow you to specify what your bot should listen and respond to. This includes keywords, patterns and various messaging and status events.

Each event handler is similar to a new “When a human says THIS the bot does THAT.” Check if your bot is online, then send any direct quick message to say hello. The bot should say hello back.

Wechat

WeChat is first a messaging app for sending text, voice and photos to friends and family. Second, it is actually more of a gateway, a platform and even a mobile operating system. It can indicate where mobile commerce future may lie.

The start of WeChat was not a website before being adapted to mobile. It was shaped by it. In Chinese WeChat is Weixin which means “micro letter”. Tencent, an investment holding company and one of the largest Internet companies in the world, launched it four years ago. The app was created by a special projects team within the company (Tencent also owns the dominant desktop messaging software in China, QQ).

In three short years, WeChat has exploded in popularity and has become the dominant mobile messaging platform in China, with approximately 700M monthly active users (MAUs) among over more than 1 billion registered users, almost all of them in Asia. 400 million people love WeChat because it’s fast, reliable, private, and always on. To put that in context: That’s only 150M MAUs fewer than Facebook Messenger, almost 3x the MAUs of Japan’s Line, and 10x the MAUs of Korea’s Kakao (which Tencent is also an investor in).

Contrary to US trends, where increasingly specific and single-purpose apps are the norm, WeChat focuses on a huge number of features in a single app.

On WeChat, users are able to:

  • Create and send stickers
  • Hail a taxi
  • Order food delivery
  • Buy movie tickets
  • Customize and order a pair of Nikes
  • Send an order to the nearest Starbucks
  • Track your daily fitness progress
  • Shop Burberry’s latest collection
  • Meet strangers near you
  • Book doctor’s appointments
  • Host a business conference call
  • Read the news
  • Pay your water bill

Moreover, here are some of WeChat core features:

  • Talk faster on the go with voice messages
  • Crystal clear voice and video calls
  • Instant messaging with group chats and animated smileys
  • Chat with your friends or with people nearby
  • Sending photos and videos has never been simpler
  • Real walkie talkie mode with up to 40 friends
  • Always on, no logouts, never miss a message
  • Get message alerts instantly with push notifications
  • Share, like, and comment on photos with your friends
  • Import contacts and add friends instantly
  • Available on Windows Phone and all other smartphones, all for free
  • WeChat works over your phone’s existing data plan or any WiFi connection

This all made WeChat an e-commerce powerhouse. Especially with its rich API functionality provided to business accounts. Businesses can create free accounts on WeChat and immediately begin connecting with customers. Consumers create connections with businesses, who can then broadcast messages to its customers, setup e-commerce storefronts, and conduct chat conversations, and even promote and sell products directly within those chat conversations (users just have to say “I want it” to buy).

Over 10 million businesses are on WeChat, including brands like Nike and Burberry. There is an enormous amount of experimentation and innovation in creating new, conversational and direct ways of interacting with customers on WeChat, and US companies (in particular Facebook) are taking note.

WeChat supports chatbots. In its jargon, a bot account is called a “public account”. They are extremely successful, and people can start a business by creating a public account bot before even having a website. This kind of businesses already exist and operates in WeChat.

WeChat’s Developer API supports many functions that are useful for chatbots, such retrieving text-to-speech output, says Mr. Collier from Colliers International’s WeChat.

Build a bot in WeChat

After submitting all your data to register a WeChat official account, which is currently given only in Chinese, it takes about 3 business days for your app to be approved. Once this is done, you will have access to WeChat API.

In the Developers area, two main data points are needed.

  • The URL is a web server. Use a simple stack running on Heroku with Node.js and Express for your backend. The API is available in PHP, Ruby on Rails and more too, in order to receive an HTTP request with the details of a message that was sent by a user.

  • The application Token When you register an application with WeChat, you will receive an authorization request to your URL. It includes the token you provided earlier, plus various other OAuth credentials, and an parameter called echo_str, which you should return if everything checks out OK. To figure out the authentication issues, you can simply return the echo_str for all requests.

exports.index = function(request, response, next){

      echo_str = request.param(echostr, null);
      response.send(echo_str);
  }

Receiving a message in your WeChat account is modeled with an HTTP request that joins a JSON payload. Unluckily, Tencet decided to use XML. A text message looks like this:

<xml>
 <ToUserName><![CDATA[toUser]]></ToUserName>
 <FromUserName><![CDATA[fromUser]]></FromUserName> 
 <CreateTime>1348831860</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[this is a test]]></Content>
 <MsgId>1234567890123456</MsgId>
 </xml>
  • ToUserName : WeChat ID of your app
  • FromUserName : a unique ID for the sender
  • CreateTime : create time of the message
  • MsgType : message type (“text” for text messages)
  • Content : message contents
  • MsgId : a unique ID for the message (64 bit integer)

Moreover, the image message has this format:

<xml>
 <ToUserName><![CDATA[toUser]]></ToUserName>
 <FromUserName><![CDATA[fromUser]]></FromUserName>
 <CreateTime>1348831860</CreateTime>
 <MsgType><![CDATA[image]]></MsgType>
 <PicUrl><![CDATA[this is a url]></PicUrl>
 <MsgId>1234567890123456</MsgId>
 </xml>
  • MsgType : message type (“image” for image messages)
  • PicUrl : URL for the image

FromUserName and ToUserName are encrypted so developers don’t have access to the user’s real WeChat ID. There is also a timestamp, the type of message (text, image, video or voice), and the text content.

To parse this in Node.js, you need the express-xml-bodyparser package. Get it with npm and configure Express to use it.

npm install express-xml-bodyparser –save

//in bot.js file 
var xmlparser = require(‘express-xml-bodyparser’);
App.use(xmlparser());

To handle the request and parse the values out of the XML, use this implementation:

 exports.receive = function(request, response, next) {
       tousername = request.body.xml.tousername[0];
       fromusername = request.body.xml.fromusername[0];
       msgtype = request.body.xml.msgtype[0];
       content = request.body.xml.content[0];
    createtime = parseInt(request.body.xml.createtime[0]);
    }

Once this is completed, construct an XML response to send it back to the user. To ensure that the message gets to the recipient, switch the two children: ToUserName and FromUserName. Let’s make an echo bot by sending the user’s message back to them. The text to reply is “ echo : (message content)”.

response.contentType(application/xml);
replyMessage = echo : +content;
xmlMessage = util.format(<xml>
            <ToUserName>%s</ToUserName>
            <FromUserName>%s</FromUserName>
            <CreateTime>%d</CreateTime>
            <MsgType>text</MsgType>
            <Content><![CDATA[%s]]></Content>
            </xml>”,
            fromusername, tousername, createtime+1, replyMessage);
response.send(xmlMessage);

Your very first version of your bot had just been completed. Send a “hello” to it. Finally, while WeChat has a significant head start on the bot ecosystem, it also have a lot artificial restrictions that block innovation. The most glaring restrictions for content providers is censorship.

In addition, the state of NLP and AI research has advanced significantly over the past three years, with a lot of attention focused on the English language.

Telegram

Telegram is a cloud-based mobile and desktop messaging app launched in 2013 by Nikolai Durov and Pavel Durov, Russian programmer and entrepreneur brothers. Telegram focuses on security and speed.

In Telegram 3.15 for Android, they brought three great features: High-precision rotation and cropping in the photo editor, a new player for Youtube videos with Picture-In-Picture mode, and forwarding messages and media to secret chats.

Moreover, bots are one of the latest updates for this messenger. Earlier this year they announced BotPrize, an initiative to award $25,000-$50,000 grants to the creators of the best Telegram bots. In November 2016, five bots were selected for the batch of grants, amounting to a total of over $200,000. Winner Bots had already a massive popularity in some markets. They are branded in five very different categories: Finance, Productivity, Dating, Games, and Photo-editing. The prize money is meant to help the developers create an even better experience for their existing and future users.

  • Finance @octopocket_bot – a smart-wallet bot that allows users from the EU to transfer money to each other, and is integrated into the ATM system of Spain. More: https://octopocket.com
  • Productivity @integram_bot – a bot that allows you to set up integrations with third-party services for developers such as Trello, Gitlab, Bitbucket, and more. More : https://integram.com
  • Dating @strangerbot – a bot that connects two random users to chat anonymously, which gained huge popularity after going viral in Southern Europe. More: https://strangerbot.com
  • Games @werewolfbot – a ‘Werewolf Game’ bot for group chats that gained popularity in SE Asia long before we launched our gaming platform last month. More: https://tgwerewolf.com
  • Photo-editing @icon8bot – an AI-based bot that allows you to apply great-looking filters to photos using neural networks and machine learning technology. More: https://icon-ai.com

The company will keep awarding creators of great bots during this year and the following year in $200,000 batches.

The Telegram team has developers working on producing useful chatbots personalized for their users. They decided to capitalize on this. The team is inspired by the huge announcement of a series of grants of $1 million to fund projects and ideas.

Using Telegram Bots is simple. All a user needs is an account. The instant messaging app is available on Android, iOS, Windows Phone, Ubuntu Touch, Firefox OS, MS Windows, Linux and OS X. It is accessible in the browser as well, which is very useful for computer routines.

There are more than 100 million active users monthly on Telegram. 350,000 signing up every day and 15 billion messages sent daily. The interface shows the label “Bot” as a subtle reminder that the users is in fact talking to an AI, not a human.

One of very popular Bots on the platform is “App Of The Day.” It shows that Bots are not trying to make Apps obsolete. To start a conversation, you type in @getbestapp_bot and will then be prompted with three questions: your country, time zone, and the operating system you would like to receive app suggestions for. The Bot sends an app suggestion at 11am on each day. More interactive Bots, like Andy Learn English, are ready to chat instantly with users, and users are soon willing to forget they are speaking to an AI.

Telegram’s open platform makes text-based bot games. The API enables visually attractive games to live inside chats on the platform. For example: PokerBot or WerewolfBot. In a few hours, any developer of an HTML5-based game is able to integrate it with the Telegram social graph. Games in Telegram are loaded on-demand and require “0 bytes of disk space.” Users can play games in their chats, graphics and sound.

Telegram has a Bot API which is an HTTP-based interface created for developers keen on building bots for Telegram.

Summary

This chapter has shed light on one of the technical aspects of chatbots. We’ve seen the biggest bot Frameworks on the internet (Microsoft Bot Framework, Facebook Messenger Platform, Chatfuel ...). Then, we examined the main instant messaging apps and how to integrate chatbots via backends in NodeJS since it is the most commonly used.

In the next chapter, we will focus on a concrete example of chatbot on the Messenger Platform, covering all of the stages of creation and learn more about different features and API offers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset