Create a trivia chatbot with Node.js and Heroku

Chatbot (s) have now taken up a significant emphasis when we talk about tomorrow’s technologies.

MessengerX.io is excited to launch our brand new Node.js SDK for all the Node developers out there.

Technical Requirements

  • Node.js – Basic Understanding
  • Desktop Terminal (Windows / Mac / Linux)
  • Brew / Snap (Mac / Windows)
  • Ngrok (For testing the chatbot locally)
  • Free Heroku Account (For hosting the chatbot)
  • Platform API Token / Key
  • Active Internet Connection
  • Javascript Enabled Browser (Chrome / Safari / Firefox)
  • MessengerX Wiki (Reference)
  • Visual Studio Code (You may choose to use another JS/Text editor. We will be using VSCode in this article)

Quizzy

Quizzy

Scope: For the purpose of this article we are going to build a simple trivia chatbot that will perform following tasks:

The chatbot will:

  1. Greet the user and offer them to begin the Trivia.
  2. Present the user with a question and 4 choices of answers.
  3. Upon user’s selection, respond the user with the result of their selection i.e. Correct/Incorrect Answer.
  4. Continue the quiz with next question.

Messaging: For sending chatbot responses, we will be using the Messaging API’s and to store user’s answers, we will utilise the Tags API.

Trivia Questions: To dynamically fetch questions and answers for the user, we will use Open Trivia Database API.

Let’s begin!

Register

In order to configure the trivia bot later, you will need to be a registered developer on MessengerX Developer Portal. If you haven’t already, head over to https://portal.messengerx.io/register to get started.

NOTE: If you are an existing developer, have reached your bot limit and wish to make more chat apps, please write to us via this link.

Create a Chat App

When you logon to the developer portal for the first time, you will see a pop up dialog like below which will prompt you to make your first chat app.

Create a new chat app

Proceed further by giving your chat app a name, description. The Webhook Url and Image Url can have a value NONE for now as we will change this later once we host our bot.

Select “Create” and you shall see an entry for your bot on the screen within seconds.

Click on “SETTINGS” and make note of Token value as we will need this to build out the bot.

NOTE: If you have created your first chat app already, you may very well choose to repurpose an existing bot token and that will work just fine. The only implication is it will break connection with the already configured settings of the previous bot.

Conversation Flow

In order to build the backend, we will first design for the conversation(s) that the user will have with the bot. For the sake of this tutorial, the bot will cater for 4 types of response messages:

  • Welcome message: This will be the default greeting message the bot will send when the user first begins the conversation along with a Quick Reply to begin the quiz.
  • Question message: This message will contain the question along with 4 quick replies that represent the answers (1 correct and 3 incorrect).
  • Result message: Represents the message shown to user as to whether their answer is correct or not.
  • Fallback message: Message sent when the chatbot receives an incoming message where it is not sure what to do and tries to bring user back to quiz.

Backend

Let’s start by creating an empty project directory. Open a Terminal/Command Line and run npm init in the project directory to initialise the Node project.

Next, we will install the MessengerX SDK and Express by running npm i --save machaao express in the terminal.

Store and fetch using Tags API

For every question asked to the user, we will be first storing the user’s question along with all the answers to MessengerX.io using Tags API. Essentially, Tags API allow us to assign a specific tag to a user along with the ability to use it as a key/value storage.

Every time a user requests for a new trivia question, our flow will be to first fetch a new question via Open Trivia Database API, store it against the user via Tags API and then present the user with the question.

When the user responds with an answer, we first fetch the current question for the given user via Tags API, compare the answer and respond the user with a result.

The logic to handle above will follow in the later article.

Incoming Message Pseudocode

Below is a diagram that explains how we will handle incoming user messages to the chatbot. We basically breakdown these messages by “action_type” which represents the type of input.

Incoming message logic

When we convert the above pseudocode into actual logic, below is what it looks like:

const express = require('express');
const server = express();
const MxSdk = require('machaao');
const lib = new MxSdk('<-----Bot Token------->', 'dev', server);
const api = 'https://opentdb.com/api.php?amount=1&category=9&difficulty=easy&type=multiple';
const rp = require('request-promise');
const welcome_responses = [
	'hi',
	'hello',
	'bojour',
	'namaste',
	'kia ora',
	'bula',
	'kemunacho',
	'hey',
	'yo',
	'sup',
	'whats up?',
	'wassup',
	'get_started',
	'get started',
];
server.post('/incoming', async (req, res) => {
	//get incoming messages
	const x = await lib.getUserMessages(req);

	//manage user response
	if (x.length > 0) {
		const incoming = x[0].message_data;

		switch (incoming.action_type) {
			case 'postback':
				if (welcome_responses.includes(incoming.text)) sendWelcomeMessage(req);
				else sendFallbackMessage(req);
				break;
			case 'quick_reply':
				if (welcome_responses.includes(incoming.text)) sendWelcomeMessage(req);
				else if (incoming.text === 'start') sendQuestionMessage(req);
				else checkResult(incoming, req);
				break;
			case 'get_started':
				if (welcome_responses.includes(incoming.text)) sendWelcomeMessage(req);
				else sendFallbackMessage(req);
				break;
		}
	}

	res.sendStatus(200);
});

Above code shows our setup MessengerX SDK initialisation, logic to handle incoming webhook requests. Notice in Line number 4 of above snippet, you will need to pass in your “Bot Token” that you made note of from the Developer Portal earlier.

The supporting methods for checking result, outgoing messages and fetching new questions are as below:

async function getQuestion() {
	const options = {
		method: 'GET',
		uri: api,
		headers: {
			'Content-Type': 'application/json',
		},
		transform: function (body, response) {
			if (typeof body === 'string') {
				response.body = JSON.parse(body);
				return response.body.results[0];
			} else return response.body.results[0];
		},
	};

	return rp(options);
}
function _getUserQuestion(payload) {
	return payload.filter((q) => q.name === 'currentQuestion');
}
async function checkResult(incoming, req) {
	const answer = await lib.getUserMessages(req);
	const userTags = await lib.getUserTags(req);
	if (userTags.length > 0) {
		const currentQ = _getUserQuestion(userTags);
		const correct_answer = currentQ[0].values[0].correct_answer;
		if (correct_answer === incoming.text) await sendCorrectAnswerMessage(req);
		else await sendWrongAnswerMessage(req, correct_answer);
	}
}

async function sendWelcomeMessage(req) {
	return lib.sendButtonsOrQuickRepliesMessage(
		req,
		"Hi I'm Quizzy, here to entertain you with multi choice Trivia Questions! Click Start to begin!",
		[],
		[{ title: 'Start', content_type: 'text', payload: 'start' }] // sample quick reply
	);
}

async function sendCorrectAnswerMessage(req) {
	return lib.sendButtonsOrQuickRepliesMessage(
		req,
		'Correct Answer!',
		[],
		[{ title: 'Next Question', content_type: 'text', payload: 'start' }] // sample quick reply
	);
}

async function sendWrongAnswerMessage(req, correct_answer) {
	return lib.sendButtonsOrQuickRepliesMessage(
		req,
		`Sorry, the right answer is ${correct_answer}.`,
		[],
		[{ title: 'Next Question', content_type: 'text', payload: 'start' }] // sample quick reply
	);
}

async function sendFallbackMessage(req) {
	return lib.sendButtonsOrQuickRepliesMessage(
		req,
		"I'm not sure I understand, to begin the quiz, tap Start below!",
		[],
		[{ title: 'Start', content_type: 'text', payload: 'start' }] // sample quick reply
	);
}

async function sendQuestionMessage(req) {
	//generate question
	//set user tag
	//send question

	const q = await getQuestion();
	const response = await lib.addUserTag('currentQuestion', [q], req);
	let answers = [...q.incorrect_answers, q.correct_answer];
//randomize options	
answers = answers.sort((a, b) => {
		return 0.5 - Math.random();
	});

	const qrs = [];
	answers.map((a) => {
		qrs.push({ title: a, content_type: 'text', payload: a });
	});
	return lib.sendButtonsOrQuickRepliesMessage(req, q.question, [], qrs);
}

//run express server on port 3000
server.listen(3000, () => {
	console.log('Listening on port 3000');
});

Debugging Locally

We will be using Ngrok.io which will enable us to temporarily open a tunnel making our locally running project accessed by the outside world. Below is how we will make it work:

  1. In your terminal, run node index.js. This should spit out "Listening on port 3000" on your terminal.
  2. Open a new terminal window and run ngrok http 3000. This will successfully generate a custom URL that will forward all incoming requests to the chatbot. An example screen is shows as below:
Ngrok

Next, we now want to go back to the Developer Portal and update the webhook URL using below format:

<NGROK URL>/incoming

So in above example it will be https://14f53735fd55.ngrok.io/incoming. Copy the URL and paste it in Webhook URL value of your chatbot in the portal and click on “SAVE CHANGES” as shown as 1 and 2 in screenshots below.

And you are now ready to test/debug your chatbot 🙂

To speak to your chatbot, click on “WEBCHAT” button in the portal and it will take you to the webchat. Click on “Get Started” to begin talking to the chatbot. You should successfully see messages routing through your locally running project.

Webhook URL and Webchat in Developer Portal

Free Hosting on Heroku

Register: If you haven’t already, visit Heroku and sign up for a free account. Once you have registered, open a new comand line/ terminal window and install the Heroku CLI as we will use this to deploy our bot.

Authorise: Upon a successful installation, run heroku login in your command line, this will prompt you to open a tab and take you through a process of authorising your machine with your Heroku account.

Configure:

  • Open package.json in your project directory and add below property to the main object in order to let Heroku know the version of Node we wish to run the chatbot.

, “engines”: { “node”: “10.x” }}

  • We need to tell Heroku how to start our project upon successful deployment. We will achieve this by specifying a start script. Open package.json file, under scripts, add a key value : "start": "node index.js",

Create App on Heroku: Run heroku create in the command line. If this runs successfully, you shall see a message like below acknowledging the app creation:

Heroku

Next, we need to add the newly created app to our git by running below where app name is the app name generated by Heroku. For example, in above screenshot it would be mighty-brushlands-98971. Make sure you commit your changes using Git locally.

heroku git:remote -a <app-name>

In order to deploy the chatbot to heroku, make sure you have first created at least one commit locally. To deploy, simply run git push --set-upstream heroku master

Once you receive a successful deployment message in your console, head over to the developer portal and update the Webhook URL with the new Heroku URL. In the case above that would be https://mighty-brushlands-98971.herokuapp.com/incoming

And that’s it 🙂

To sum up, in this article we learnt how to get started with MessengerX.io using the Node SDK, build a Trivia Chatbot using OpenTrivia Database API and successfully deploy the chatbot on Heroku for free.

Full Source Code is available via Github: https://github.com/machaao/TriviaBot

Live Demo: https://dev.messengerx.io/quizzy

If you have reached this far, I am sure you have a great knack for chatbots. I hope you enjoyed the article and look forward to hearing your thoughts below.

Follow our blog for more updates!

Get Started with building deeply personalised chatbots today with MessengerX.io