Quick Start
On this page we'll get you setup using the SDK to provide a simple "Hello World" reply to a users message.
In this guide we are going to setup a simple web server that can respond to requests. This web server will be triggered using the "webhook" capability within logicdialog. There are just a few steps we'll need to take to get you all setup. These are as follows :
Setting the Webhook URL settings
Building some content that will trigger the webhook
Setting up a project and creating an instance of the Webhook Client
Adding functionality to the project to handle specific types of request
These steps are all described below.
Setting the webhook URL
In this example we are going to use ngrok
to provide an internet accessible hostname. You will need to install ngrok
first. Once installed open a command terminal and type
ngrok http <server port to expose>
In this case the <server port to expose>
is going to be 8080
.
The command will start and provide to URLs, one on http and the other on https. Make a note of the https
URL as you will need this shortly.
Once you have the URL we'll need to add this to the settings in IA. To do this :
Login to logicdialog
Go to Settings -> Webhook
Set Endpoint to the forwarding URI from
ngrok
Please make a note of the JWT secret that is shown on the Webhook settings page. We'll use this to authenticate our requests later.
Building Content in IA
Using Visual Bot Builder in logicdialog, add new Choice using plus buttons to the far left or right of the existing choices, or add to existing choice by using the plus button on said choice
Choose New Block and then Function Block
Give block a name, and pick module if applicable
If function has not been implemented, leave Todo field ticked, and add Temporary Text, usually a description of function implementation, and add button to simulate response. If you want your webhook to receive an event when this block is hit by a user, "Todo" must be unchecked
Pick Form from dropdown if applicable
Pick Handler Name, note this as it is used when adding handlers to the
WebhookClient
We will also need to...
In logicdialog go to the Forms page
Click add new form, and give form a descriptive title
Add new question, or pick one from the question bank
Give descriptive title to question
Write question text, to be displayed when question is asked
Pick input type given to the user, followed by data type
A question can also be added to the question bank from the Question Bank tab
Creating a project and code
Install the library
The best way to interact with our API is to use one of our official libraries:
# Install via NPM
npm install --save @webuildbots/webuildbots-sdk
Setting up an express server
The webhook from IA will make an HTTP request to a webserver containing your application logic. This could be a number of things, including a serverless function however in this example we are going to use express
to host our API. We can setup express
using the following simple bits of code.
import { createServer } from 'http';
import express, { Request, Response } from 'express';
import { divisionHandler } from './handler';
import { WebhookClient } from '@webuildbots/webuildbots-sdk/lib/util/webhook-client';
import dotenv from 'dotenv';
// Load Webhook Secret, this can be found in IntelAgent settings
dotenv.config();
const secret = process.env['WEBHOOK_SECRET'] || '';
// WebhookClient used to run handlers, intialised with JWT token copied previously
const whClient: WebhookClient = new WebhookClient(secret);
// Add handler to the list of handlers in the Client, name must match the functions handler-name
whClient.addHandler('division-handler', divisionHandler);
// Function to getToken from request, used to authorise request and secret
function getToken(request: Request): string {
const token = request.headers.authorization?.split('Bearer ')[1];
if (!token) {
throw Error('No token found');
}
return token;
}
const app: express.Application = express();
// Text body-parser, as handleRequest function takes body from request as a string
// Content-type of request is plaintext, which is parsed by the handleRequest function
app.use(express.text());
// This should match the endpoint set in IntelAgent
app.post('/', async (req: Request, res: Response) => {
// handleRequest returns a JSON object and a statusCode
const { status, body } = await whClient.handleRequest(
req.body,
getToken(req)
);
res.status(status).send(body);
});
const server = createServer(app);
server.listen(8080);
This example will allow us to POST
data to the /
endpoint running on port 8080
. First we create an instance of the WebhookClient
which will allow us to handle the request and return various values back to the user. You'll notice on line 13
we construct a handler
which will handle the division-handler
requests. By adding this handler we can build an application that can handle different requests from different parts of the application, each one using a different name that is set in IA on a block by block level. On line 36
the webhook client will handle the request - specifically looking for a handler that matches the incoming requests handle name.
Make your first hander
A webhook handler is a simple function that will be called any time a block is triggered from IA. Its passed the webhookReq
object which represents the information in the conversation, and a responseBuilder
that helps you construct a reply to the user.
The following example shows a simple case where one number is divided by another, and an error is thrown if this combination of numbers provides a divide by zero error. A plain text message will be sent back to the user containing the answer.
export const divisionHandler: WebhookHandler = async (
webhookReq: WebhookRequest,
responseBuilder: ResponseBuilder
): Promise<void> => {
// read values from the form completed by the user before the call over the webhook was made
const { value: baseNumber } = webhookReq.formValue.baseNumber;
const { value: divisionNumber } = webhookReq.formValue.divisionNumber;
if (divisionNumber.value === 0) {
responseBuilder.functionFailure(failureParams);
return;
}
const resultNumber = baseNumber / divisionNumber;
responseBuilder.pushBlockPointer(resultBlock);
const basicBB = new BasicBB()
.addText(Languages.ENGLISH, `${resultNumber}!`)
.pushChoice(backToMenu());
responseBuilder
// Add the block to the response
.pushBlock(basicBB)
// Reset the form values after the response is sent to the user
.unsetFunctionForm();
};
For more information please see the following pages :
WebhookClientResponseBuilderLast updated