Start building your own chatbot now >
Note: This article is deprecated. It uses Recast.AI API version 1. You can find an updated tutorial here: NodeJS chatbot tutorial: A Github bot with Recast.AI.

Introduction:

Facebook recently opened up their Messenger platform to enable bots to chat with users through Facebook Apps and on Facebook Pages. With Recast.AI you will be able to create a conversational bot that will understand natural language.
Here is a tutorial on how to create your own messenger bot with Recast.AI and Microsoft bot connector in one hour.
In this tutorial, we’ll use the example of our latest bot: Pokébot. He is a smart Pokédex and gives you information about Pokémons, their moves, resistance and weakness, the way they evolve etc…

screen pokebot

Tools:

  • Microsoft Bot connector will connect the bot to channels like Messenger or Slack.
  • Recast.AI will understand the messages you’ll send to your bot
  • PokeApi will provide us all the informations we need about Pokémons

Requirements:

  • Create an account on Recast.AI
  • Create a Microsoft account
  • Make sure you have node v6 installed, we’ll use nodejs with ES6 syntax

Links:

  • Try PokeBot on Messenger here
  • See the Bot on Github here
  • See the Bot on Recast.AI here

Get started:

  • mkdir PokeBot && cd PokeBot
  • npm init

 

 STEP 1: Connect your bot to Messenger

As you can see on the graph below, we’ll have to make 2 connections: one between the bot and Microsoft, and one between Microsoft and Messenger.recast-ai-connections-graph

1. Manage Bot connection:

  • Log into Microsoft Bot framework.
  • Click on “Register a new bot” and follow the procedure. Don’t fill ‘Messaging Endpoint’ yet.
  • Create a microsoft AppId and password and keep them preciously.

recast-ai-microsoft-bot-creation

 

2. Manage your Bot channels:

  • Click on “Add” for the Facebook Messenger Channel.
  • Follow the procedure, it’s very thorough.

 

3. Get an online url for your future server:

Whenever the bot receives a message on Messenger, it will be sent to the server running on the endpoint url specified on Microsoft Bot Platform.
Problem: the server will be running locally (no url)
That’s why you will use
ngrok which make a local server run online.

  • Download ngrok and run it
./ngrok http 8080
  • Copy and paste the secured url (https) on the endpoint field of your bot in Microsoft Bot Framework.

ngrok-console

  • Send a message to your bot using messenger and look on ngrok. A new line appear with a POST request. If not, you did something wrong in the previous steps, go through them again.

 

4. Create your server:

  • create  new file:
touch pokebot.js
  • Install the modules we need: restify for the server, and botbuilder for the microsoft connection.
npm install --save restify botbuilder
  • Make the server listening on 8080 port.
pokebot.js:
const restify = require('restify')
const builder = require('botbuilder')
const server = restify.createServer().listen(8080)

 

5. Use your credentials:

  • create a config file:
config.js
  • fill it with your credentials you preciously saved earlier:
const config = {
  appid: 'YOUR APPID',
  secret: 'YOUR SECRET',
}

module.exports = config
  • import this file at the beginning of pokebot.js
const config = require('./config.js')

 

6. Catch the message:

pokebot.js:

const config = require('./config.js')
const restify = require('restify')
const builder = require('botbuilder')

// Connection to Microsoft Bot Framework
const connector = new builder.ChatConnector({
  appId: config.appid,
  appPassword: config.secret,
})

const bot = new builder.UniversalBot(connector)

// Event when Message received
bot.dialog('/', (session) => {
  console.log(session.message.text)
})

// Server Init
const server = restify.createServer()
server.listen(8080)
server.post('/', connector.listen())

 

7. Launch your server:

  • Run this command:
node pokebot.js
  • Chat with your bot on Messenger. You can now see that ‘session.message.text’ contains the message you’ve sent. That means you’re now done connecting the bot to Messenger! 😉

 

STEP 2: Analyse Bot features

 

1. Vocabulary:

By using Recast.AI you will encounter some specific terms, that you can get familiar with here with a crystal-clear guide of the platform’s good practices.

  • In your bot, an intent is an action the user, you, wants to perform.
  • Intents are boxes including expressions that mean the same thing but are constructed differently.
  • Entities are key words the Recast.AI API detects in your inputs and uses in the answer, like a city, a name, a datetime, etc.

2. Overview of the bot intents:

recast-ai-intents-graph

Entity:

  • Pokemon (here, Pikachu and bulbasaur)

Basic Intents:

  • Greetings: “Hello!”
  • Feelings: “How are you?”
  • Goodbyes: “Bye”
  • Help: “Help me”

Dynamic Intents:

  • info pokemon: information (picture/name/types/description) about a specific pokemon
  • stat pokemon: the stats of a specific pokemon
  • move pokemon: the list of moves a specific pokemon can learn

 

3. Other features

Buttons:

  • Quick access to the different intents.

Entity checking:

  • When an entity is detected, we check if it’s an existing pokemon.
  • When there’s a small input like “And bulbasaur?”, “Charmeleon?”, we check if the word is a pokemon.

Memory:

  • The last intent is saved and can be reused: “Show me raichu’s stats” “and bulbasaur?”
  • The last pokemon is saved and can be reused: “Show me pikachu moves” – “And it’s stats?”

 

STEP 3: Use Recast.AI

 

1. Create a Bot:

  • Log into Recast.AI.
  • Click on the ‘NEW BOT’ blue button and create your bot.

recast-ai-homepage

2. Create the ‘Greetings’ intent:

  • Type “Greetings” in the intent search bar, select one result that matches your expectations, and click on “FORK” button to copy.
  • Add some expressions like “Hey you”, “Hello bot”, “Hi”, anything you’d like your bot to understand as greetings.

greeting intent

3. Create the ‘Infopokemon’ Intent:

  • Fork it from the community or create it from scratch with your expressions.

infopokemon intent

  • Start tagging entities to train the bot on where the name of the pokemon should be in the sentence. To do that, click on the expression then on the word you want to tag and choose the entity “POKEMON”

entity-tagging

4. Try the console:

  • Toggle the console on the right to test your bot, send a message and look at the answer.

How to show recast console

  • The 2 important fields are ‘intents’ and ‘entities’. You can see the bot did match the good intent and detected the right pokemon.

console recast tests

STEP 4: Connect your bot to Recast.AI

 

 1. Get your Recast.AI request access token:

  • Go to your main bot page
  • Click on the settings icon on the right
  • recast-ai-settingsAdd your Request access token in config.js
recast-ai-request-tokenconst config = {


  recast: 'Recast Request access token',
  appid: 'Microsoft AppId',
  secret: 'Microsoft password',
}

module.exports = config

 

2. Make a request with the message received :

  • Install Recast.AI SDK
npm install --save recastai
  • Import the SDK in pokebot.js
const recast = require('recastai')
  • Connect your bot with your token
const recastClient = new recast.Client(config.recast)
  • In the bot.dialog function, add a Recast.AI request with the message received.
// Event when Message received
bot.dialog('/', (session) => {
  recastClient.textRequest(session.message.text)
  .then(res => console.log(res))
  .catch(() => session.send('I need some sleep right now... Talk to me later!'))
})

  • Run the server, say hello to your bot on Messenger, and notice that res contains the same json that the console on the platform!

 

3. Catch the intent and entity:

  • Use res.intent() to get the intent
const intent = res.intent()
  • Use res.get(‘entityName’) to get the entity
const entity = res.get('pokemon')
  • Send your first message using session.send(‘yourMessage’): When the user says something, make the bot reply the intent and the entity matched. Try to ask for a pokemon on Messenger.
pokebot.js:

recastClient.textRequest(session.message.text)
 .then(res => {
   const intent = res.intent()
   const entity = res.get('pokemon')
   session.send(`Intent: ${intent.slug}`)
   session.send(`Entity: ${entity.name}`)
 })
 .catch(() => session.send('I need some sleep right now... Talk to me later!'))
})

4. Train your Bot:

  • if no intent has been matched, you may have to train your bot on Recast.AI. Go on the train tab and add the expression to one of your intent (don’t forget to tag if needed)
  • You can watch this video if you need some help.

recast-ai-bot-training

5. Structure your project:

Each intent is a function that returns the appropriate answer. It’s really important to keep that kind of architecture because that makes it easier to work and add new intents.

  • Create a folder named ‘intents’
mkdir intents
  • Create a file for each of your intents: greetings and infopokemon.
touch intents/greetings.js intents/infopokemon.js
pokebot
  ├ config.js
  ├ pokebot.js
  ├ intents/
    ├ greetings.js
    ├ infopokemon.js
  └ node_modules/

 

6. Answer to Greeting intent:

  • Write a getGreetings function in the greetings.js file that replies the answer.
  • To make it a bit more ‘human’, we’re use a random function with an array of different answers.
greetings.js:

const random = array => { return array[Math.floor(Math.random() * array.length)] }

const getGreetings = () => {
  const answers = [
    'Hello!',
    'Yo ;)',
    'Hey, nice to see you.',
    'Welcome back!',
    'Hi, how can I help you?',
    'Hey, what do you need?',
  ]
  return random(answers)
}

module.exports = getGreetings
  • To use the right function depending on the intent, we could just use in pokebot.js:
pokebot.js:

...
if (intent.slug === 'greetings') {
  session.send(getGreetings())
  } else if (intent.slug === 'infopokemon') {
  session.send(getInfoPokemon(entity))
}
...
  • A better way to do this is to create an object with the intents as key, and the intent function as value. So if the bot matches greetings for example, INTENTS[intent.slug] is actually getGreeting.
pokebot.js:

const getGreetings = require('./intents/greetings.js')
const getInfoPokemon = require('./intents/infopokemon.js')

const config = require('./config.js')
const restify = require('restify')
const builder = require('botbuilder')

// Connection to Microsoft Bot Framework
const connector = new builder.ChatConnector({
  appId: config.appid,
  appPassword: config.secret,
})

const bot = new builder.UniversalBot(connector)

const INTENTS = {
  greetings: getGreetings,
  infopokemon: getInfoPokemon,
}

bot.dialog('/', (session) => {
  recastClient.textRequest(session.message.text)
  .then(res => {
    const intent = res.intent()
    const entity = res.get('pokemon')
    if (intent) {
      session.send(INTENTS[intent.slug](entity))
    } })
  .catch(() => session.send('I need some sleep right now... Talk to me later!'))
})

// Server Init
const server = restify.createServer()
server.listen(8080)
server.post('/', connector.listen())

 

You just achieved the basics! Now your bot is connected to Messenger, to recast, and answer to Greetings. In the next part we’ll start the development of dynamics intent using PokeApi.

Access to step 2 here.

Want to build your own conversational bot? Get started with Recast.AI !

Subscribe to our newsletter


  • pauline olivier

    Hello!
    I always have the problem {“code”:”ResourceNotFound”,”message”:”/ does not exist”} when I try to connect to my bot. Has somebody the same error?

    • Hugo Cherchi

      I’m glad you sorted that out! What was the problem?

      • pauline olivier

        Missing a /api/messages after the https://******.ngrok.io in the endpoint field

        • Hugo Cherchi

          You’re right! I forgot to specify. I think you can also just put ‘/’ in the code and don’t add ‘/api/messages’ on the endpoint. Good job, keep going 😉

  • Raghu

    Just following these steps. I have quite a bit working and all seems ok when i use the “TEST” button on the BOT Framework page. Nothings seems to be happening when i use Facebook Messenger. What could i be doing wrong? Any guidance / suggestions?

    • Raghu

      Working fine. I had the wrong Facebook Page ID. Thanks.

      • Julien Blancher

        Hi Raghu!
        Great to hear you’ve solved your problem.
        Let us know if you have any other question.
        Julien

  • Omer Biran

    Hey guys, quick comment, I’d suggest that links would open in a new tab in order to allow the reader to keep on reading while launching links in parallel 😉

  • Omer Biran

    Hi again, sorry to be a pain, but I think there’s an extra s in “module(s).exports” in the greetings.js code example, isn’t it?

  • Luis Carlos Parra Raffan

    I have done all you said in this awesome tutorial, but I dont know why I always receive this message when I try to read the message from the chat in my nodeJS console.

    ERROR: ChatConnector: receive – invalid token. Check bot’s app ID & Password.